Exemplo n.º 1
0
def performance_indicators():
    total_loss = user_data['total_loss']
    total_gain = user_data['total_gain']
    avg_rrr = user_data['avg_rrr'][-1]
    avg_timespan = user_data['avg_timespan'][-1]/60

    trades = tl.read_trades(user_data['diary_file'], 'closed')
    size = trades['cap. share (%)'].mean()
    risk = trades['risk (%)'].mean()

    no_trades = len(trades)
    no_shorts = len(trades[trades['direction'] == 'SHORT'])
    no_longs = len(trades[trades['direction'] == 'LONG'])

    days_traded = trades['date'].apply(lambda x: datetime.date(x)).nunique()

    trades_per_day = no_trades/days_traded
    shortlongratio = no_shorts/no_longs

    entry = trades['entry']
    qty = trades['size']
    total_volume = sum(entry.mul(qty))
    max_loss = trades['P/L (%)'].min()
    max_win = trades['P/L (%)'].max()

    efficiency = (total_gain-total_loss)/total_volume*100

    return [html.H5('Additional Performance Indicators',
                    style={'margin-bottom': '20px'}),
            html.Div(
                [
                    html.Div(
                        [
                            html.Pre('Average trades per day:\t {:.1f}'.format(trades_per_day)),
                            html.Pre('Average timespan: \t \t {:.1f} h'.format(avg_timespan)),
                            html.Pre('Average r2r: \t \t \t {:.2f}'.format(avg_rrr)),
                            html.Pre('Average size: \t \t \t {:.0f} %'.format(size)),
                            html.Pre('Average risk: \t \t \t {:.1f} %'.format(risk)),
                            html.Pre('Short/long ratio: \t \t {:.1f}'.format(shortlongratio)),
                        ],
                        style={'width': '50%', 'display': 'flex', 'flex-flow': 'column',
                               'justify-content': 'space-between'}
                    ),
                    html.Div(
                        [
                            html.Pre('Efficiency: \t \t \t \t {:.2f} %'.format(efficiency)),
                            html.Pre('Total volume traded: \t {:.2f} $'.format(total_volume)),
                            html.Pre('Total Gain: \t \t \t \t {:.2f} $'.format(total_gain)),
                            html.Pre('Total Loss: \t \t \t \t {:.2f} $'.format(total_loss)),
                            html.Pre('Max loss:\t \t \t \t{:.2f} %'.format(max_loss)),
                            html.Pre('Max Win: \t \t \t \t  {:.2f} %'.format(max_win))
                        ],
                        style={'width': '50%', 'display': 'flex', 'flex-flow': 'column',
                               'justify-content': 'space-between'}
                    )
                ],
                style={'display': 'flex', 'height': '80%', 'overflow': 'auto'}
            )
            ]
Exemplo n.º 2
0
def close_trade(clicks, selected_row, close, note):
    record_file = user_data['diary_file']
    if clicks is None:
        closed_trades = tl.read_trades(record_file, 'closed', dict_output=True)
        open_trades = tl.read_trades(record_file, 'open', dict_output=True)

    elif close is None:
        closed_trades = tl.read_trades(record_file, 'closed', dict_output=True)
        open_trades = tl.read_trades(record_file, 'open', dict_output=True)
        style = {'color': '#fc3003', 'border-color': '#fc3003'}
    else:
        # Retrieve the trade that we want to close:
        open_trades = tl.read_trades(record_file, 'open')
        trade = open_trades.iloc[selected_row]
        # NOTE that trade is still a df and not a series, because we put a list inside iloc

        # Compute features of the closed trade:
        closed_trade = tl.fill_trade(trade, close, note)
        # Write the trade to the records:
        tl.write_trade_to_records(record_file, 'closed', closed_trade)
        # Remove the open trade from the open trade records:
        tl.remove_trade_from_records(record_file, selected_row[0])
        # Update the running average features:
        tl.update_user_data(closed_trade)

        closed_trades = tl.read_trades(record_file, 'closed', dict_output=True)
        open_trades = tl.read_trades(record_file, 'open', dict_output=True)

        style = {}

    return closed_trades, open_trades, style
Exemplo n.º 3
0
def open_profit_string():
    profit = tl.open_profit(tl.read_trades(user_data['diary_file'], 'open'))
    percent = profit / user_data['capital'][-1] * 100
    if profit < 0:
        color = 'red'
    else:
        color = 'green'
    return [
        html.Pre('Open profit/loss: \t '),
        html.P('{:.2f}$ ({:.2f}%)'.format(profit, percent),
               style={'color': color})
    ]
Exemplo n.º 4
0
def submit_trade(clicks, pair, entry, qty, stop, idea, direction, confidence):
    forgotten_input = [
        x == '' or x is None for x in [entry, qty, stop, idea, direction]
    ]

    if clicks is None:
        trades = tl.read_trades(user_data['diary_file'],
                                'open',
                                dict_output=True)
    elif any(forgotten_input):
        trades = tl.read_trades(user_data['diary_file'],
                                'open',
                                dict_output=True)
        style = {'color': '#fc3003', 'border-color': '#fc3003'}
        return trades, 'Missing!', entry, 'Missing!', qty, 'Missing!', stop, idea, direction, confidence, \
            open_risk_string(), style
    else:
        # Add new trade at the top of the diary excel file:
        index = pd.DatetimeIndex([datetime.datetime.now()])
        trade = pd.DataFrame(
            {
                'pair': pair,
                'size': qty,
                'entry': entry,
                'stop': stop,
                'type': idea,
                'direction': direction,
                'confidence': confidence
            },
            index=index)

        tl.write_trade_to_records(user_data['diary_file'], 'open', trade)
        trades = tl.read_trades(user_data['diary_file'],
                                'open',
                                dict_output=True)

    return trades, 0, '', 0, '', 0, '', '', '', 2, open_risk_string(), {}
Exemplo n.º 5
0
def open_risk_string():
    current_capital = user_data['capital'][-1]
    open_risk = sum(
        tl.trade_risk(current_capital,
                      tl.read_trades(user_data['diary_file'], 'open')))

    if open_risk > tl.max_open_risk * 100:
        color = 'red'
    else:
        color = 'green'

    return [
        html.Pre('Open risk: \t'),
        html.P(' {:.2f}%'.format(open_risk), style={'color': color})
    ]
Exemplo n.º 6
0
def timespan_figure():
    # Extract the timespans of winners and losers from the records:
    trades = tl.read_trades(user_data['diary_file'], 'closed')
    data = trades[['P/L (%)', 'timespan (min)']]

    winners = data[data['P/L (%)'] >= 0]
    losers = data[data['P/L (%)'] < 0]

    win_spans = winners.drop(columns=['P/L (%)'])/60  # convert to hours
    lose_spans = losers.drop(columns=['P/L (%)'])/60  # convert to hours

    # Plot the histogram of this data:
    graph_data = [
        {
            'x': list(win_spans.values.squeeze()),
            'name': 'won',
            'type': 'histogram',
            'nbins': 10,
            'histnorm': 'percent',
            'opacity': '0.75',
            'bingroup': 1,
            'marker': {'color': '#3D9970'}
        },
        {
            'x': list(lose_spans.values.squeeze()),
            'name': 'lost',
            'type': 'histogram',
            'nbins': 10,
            'histnorm': 'percent',
            'opacity': '0.75',
            'bingroup': 1,
            'marker': {'color': '#A83232'}
        }
    ]

    figure = {
        'data': graph_data,
        'layout': dict(
            barmode='overlay',
            margin={'l': 40, 'r': 15, 't': 10, 'b': 35},
            paper_bgcolor='#e8e8e8',
            font={'family': 'Dosis', 'size': 13},
            showlegend=False,
            yaxis={'title': 'Win/Lose (%)'},
            xaxis={'title': 'Time [h]'},
        )
    }
    return figure
Exemplo n.º 7
0
def shortlong_figure():
    trades = tl.read_trades(user_data['diary_file'], 'closed')
    shorts = trades[trades['direction'] == 'SHORT']
    longs = trades[trades['direction'] == 'LONG']

    win_s = sum(shorts['P/L (%)'] >= 0)
    win_l = sum(longs['P/L (%)'] >= 0)

    lose_s = sum(shorts['P/L (%)'] < 0)
    lose_l = sum(longs['P/L (%)'] < 0)

    graph_data = [
        {'x': ['SHORT', 'LONG'],
         'y': [win_s, win_l],
         'name': 'won',
         'type': 'bar',
         'marker': {'color': '#3D9970'}
         },
        {'x': ['SHORT', 'LONG'],
         'y': [lose_s, lose_l],
         'name': 'lost',
         'type': 'bar',
         'marker': {'color': '#A83232'}
         }
    ]

    figure = {
        'data': graph_data,
        'layout': dict(
            barmode='stack',
            margin={'l': 20, 'r': 15, 't': 10, 'b': 15},
            height=250,
            paper_bgcolor='#e8e8e8',
            font={'family': 'Dosis', 'size': 13},
            showlegend=False,
        )
    }
    return figure
Exemplo n.º 8
0
def serve_layout():
    return html.Div(
        [
            html.Div(
                [
                    html.Div(id='selected_trade',
                             style={'visibility': 'hidden'}),
                    html.Div([
                        html.H5('Select Position To Close:',
                                style={'margin-bottom': '10px'}),
                        dash_table.DataTable(
                            id='open_table2',
                            columns=tl.open_trade_dict,
                            data=tl.read_trades(user_data['diary_file'],
                                                'open',
                                                dict_output=True),
                            style_table={
                                'height': '102px',
                                'overflow-y': 'scroll',
                            },
                            style_cell_conditional=[{
                                'if': {
                                    'column_id': c
                                },
                                'text-align': 'center'
                            } for c in ['pair', 'direction']],
                            row_selectable='single',
                            selected_rows=[0],
                            style_as_list_view=True,
                            style_cell={'padding': '5px'},
                            style_header={
                                'background-color': 'white',
                                'font-weight': 'bold'
                            })
                    ],
                             className='pretty_container seven columns',
                             style={
                                 'margin-left': '0',
                                 'padding-top': '5px'
                             }),
                    html.Div(
                        [
                            html.Div(
                                [
                                    html.H5('Close Position:',
                                            style={'margin-bottom': '20px'}),
                                    html.Button('Close',
                                                id='close_trade_button',
                                                style={'margin-top': '10px'})
                                ],
                                style={
                                    'justify-content': 'space-between',
                                    'display': 'flex'
                                }),
                            html.Div(
                                [
                                    html.Pre('Exit Price: \t',
                                             style={'line-height': '2.5'}),
                                    dcc.Input(id='exit',
                                              placeholder=0,
                                              type='number',
                                              min=0,
                                              style={'width': '30%'}),
                                ],
                                style={
                                    'display':
                                    'flex',  # 'justify-content': 'space-between',
                                    'vertical-align': 'center'
                                }),
                            html.P('Note:',
                                   style={
                                       'margin-top': '0',
                                       'margin-bottom': '0'
                                   }),
                            dcc.Input(
                                id='note', style={'width': '100%'}, value='')
                        ],
                        className='pretty_container five columns',
                        style={
                            'margin-right': '0',
                            'margin-left': '0',
                            'padding-top': '5px'
                        })
                ],
                className='row flex-display',
            ),
            html.Div(
                [
                    html.H5('Closed Trades:'),
                    dash_table.DataTable(
                        id='closed_table',
                        columns=tl.closed_trade_dict,
                        data=tl.read_trades(user_data['diary_file'],
                                            'closed',
                                            dict_output=True),
                        style_table={
                            'height': '270px',
                            'overflow-y': 'scroll'
                        },
                        # You can use style conditional to color profitable and losing trades!
                        style_cell_conditional=[{
                            'if': {
                                'column_id': c
                            },
                            'text-align': 'center'
                        } for c in ['pair', 'direction', 'type']],
                        style_data_conditional=[{
                            'if': {
                                'column_id': 'P/L (%)',
                                'filter_query': '{P/L (%)} > 0',
                            },
                            'backgroundColor': '#3D9970',
                            'color': 'white',
                        }, {
                            'if': {
                                'column_id': 'P/L (%)',
                                'filter_query': '{P/L (%)} < 0',
                            },
                            'backgroundColor': '#A83232',
                            'color': 'white',
                        }],
                        style_as_list_view=True,
                        style_cell={'padding': '5px'},
                        style_header={
                            'background-color': 'white',
                            'font-weight': 'bold'
                        })
                ],
                className='pretty_container twelve columns',
                style={
                    'margin-top': '0',
                    'padding-top': '5px'
                })
        ], )
Exemplo n.º 9
0
def serve_layout():
    return html.Div([
        # CONTAINER FOR ENTERING A NEW TRADE
        dcc.Interval(id='price_call'),
        html.Div(
            [
                html.Div(
                    [
                        html.H5('Add New Trade:'),
                        html.Div([
                            html.P('Pair:'),
                            dcc.Dropdown(id='pair',
                                         options=tl.pairs,
                                         value='ETHUSDT',
                                         style={
                                             'width': '97%',
                                             'display': 'block',
                                             'height': '40px'
                                         }),
                        ],
                                 style={
                                     'width': '25%',
                                     'display': 'inline-block'
                                 }),
                        html.Div(
                            [
                                html.P('Amount:'),
                                dcc.Input(id='qty',
                                          placeholder=0,
                                          type='number',
                                          min=0,
                                          style={
                                              'width': '90%',
                                              'display': 'inline',
                                              'height': '40px'
                                          })
                            ],
                            style={
                                'width': '15%',
                                'display': 'inline-block',
                                'vertical-align': 'top'
                            }),
                        html.Div(
                            [
                                html.P('Entry:'),
                                dcc.Input(id='entry',
                                          placeholder=0,
                                          type='number',
                                          min=0,
                                          style={
                                              'width': '90%',
                                              'height': '40px'
                                          })
                            ],
                            style={
                                'width': '15%',
                                'display': 'inline-block',
                                'vertical-align': 'top'
                            }),
                        html.Div(
                            [
                                html.P('Stop loss:'),
                                dcc.Input(id='stop',
                                          placeholder=0,
                                          type='number',
                                          min=0,
                                          style={
                                              'width': '90%',
                                              'height': '40px'
                                          })
                            ],
                            style={
                                'width': '15%',
                                'display': 'inline-block',
                                'vertical-align': 'top'
                            }),
                        html.Div(
                            [
                                html.P('Trade type:'),
                                dcc.Dropdown(id='type',
                                             options=tl.types,
                                             value='',
                                             style={
                                                 'width': '100%',
                                                 'display': 'block',
                                                 'height': '40px'
                                             })
                            ],
                            style={
                                'width': '30%',
                                'display': 'inline-block'
                            },
                        ),
                        html.Div(
                            [
                                html.Div(
                                    [
                                        html.P('Confidence:'),
                                        dcc.Slider(id='confidence',
                                                   min=1,
                                                   max=3,
                                                   step=None,
                                                   value=2,
                                                   marks={
                                                       1: 'Unsure',
                                                       2: 'OK',
                                                       3: 'Gonna Win!'
                                                   })
                                    ],
                                    style={
                                        'width': '40%',
                                        'display': 'block-inline',
                                        'vertical-align': 'top'
                                    }),
                                html.Div(
                                    [
                                        # It would be possible to determine SHORT/LONG from entry and stop!
                                        html.P('Direction:'),
                                        dcc.RadioItems(id='direction',
                                                       options=tl.directions,
                                                       value='',
                                                       style={
                                                           'display': 'flex',
                                                           'margin-top':
                                                           '10px',
                                                           'margin-bottom': '0'
                                                       },
                                                       labelStyle={
                                                           'margin-right':
                                                           '10px'
                                                       })
                                    ],
                                    style={'display': 'block-inline'}),
                                html.Div(
                                    [
                                        html.Button('Enter Trade',
                                                    id='enter_trade_button')
                                    ],
                                    style={
                                        'display': 'block',
                                        'align-items': 'flex-end',
                                        'margin-top': '35px'
                                    })
                            ],
                            style={
                                'justify-content': 'space-between',
                                'display': 'flex'
                            })
                    ],
                    className="pretty_container twelve columns",
                    style={
                        'margin-right': '0',
                        'padding-top': '5px'
                    },
                    id="enter-trade"),
            ],
            className='row flex-display'),
        # CONTAINER FOR OPEN POSITIONS
        html.Div(
            [
                html.Div(
                    [
                        html.H5('Open Positions:',
                                style={'margin-bottom': '10px'}),
                        dash_table.DataTable(
                            id='open_table',
                            columns=tl.open_trade_dict,
                            data=tl.read_trades(user_data['diary_file'],
                                                'open',
                                                dict_output=True),
                            style_table={
                                'height': '126px',
                                'overflow-y': 'scroll'
                            },
                            # You can use style conditional to color profitable and losing trades!
                            style_cell_conditional=[{
                                'if': {
                                    'column_id': c
                                },
                                'text-align': 'center'
                            } for c in ['pair', 'direction']],
                            style_as_list_view=True,
                            style_cell={'padding': '5px'},
                            style_header={
                                'background-color': 'white',
                                'font-weight': 'bold'
                            }),
                        html.Div(
                            [
                                html.Div(id='open_risk',
                                         children=open_risk_string(),
                                         style={'display': 'flex'}),
                                html.Div(id='open_profit',
                                         children=open_profit_string(),
                                         style={
                                             'display': 'flex',
                                             'width': '60%'
                                         })
                            ],
                            style={
                                'justify-content': 'space-between',
                                'display': 'flex',
                                'margin-top': '10px'
                            })
                    ],
                    className="pretty_container seven columns",
                    style={
                        'margin-left': '0',
                        'margin-top': '0',
                        'padding-top': '5px'
                    },
                    id="open-positions"),
                # CONTAINER FOR CALCULATING TRADE SIZE
                html.Div(
                    [
                        html.H5('Calculate Position Size:'),
                        html.Div([
                            html.Div([
                                html.P('Entry:'),
                                dcc.Input(id='entry2',
                                          placeholder=0.0,
                                          type='number',
                                          value=np.nan,
                                          min=0,
                                          style={
                                              'display': 'inline',
                                              'width': '90%'
                                          })
                            ], ),
                            html.Div([
                                html.P('Stop loss:'),
                                dcc.Input(id='stop2',
                                          placeholder=0.0,
                                          type='number',
                                          value=np.nan,
                                          min=0,
                                          style={
                                              'display': 'inline',
                                              'width': '90%',
                                          })
                            ],
                                     style={'display': 'inline-block'}),
                            html.Div([
                                html.P('Allowed size:',
                                       style={'display': 'block'}),
                                dcc.Input(id='qty2',
                                          placeholder=0.0,
                                          type='number',
                                          value=np.nan,
                                          min=0,
                                          readOnly=True,
                                          style={
                                              'display': 'inline',
                                              'width': '100%'
                                          })
                            ],
                                     style={'display': 'inline-block'}),
                        ],
                                 style={
                                     'justify-content': 'space-between',
                                     'display': 'flex'
                                 }),
                        html.Div([
                            html.Div(
                                [
                                    html.Pre('Risk:'),
                                    dcc.RadioItems(id='risk',
                                                   options=[{
                                                       'label': '1%  ',
                                                       'value': 0.01
                                                   }, {
                                                       'label': '2%',
                                                       'value': 0.02
                                                   }],
                                                   value=0.01,
                                                   style={
                                                       'display': 'flex',
                                                       'margin-right': '2px'
                                                   },
                                                   labelStyle={
                                                       'margin-right': '24px'
                                                   })
                                ],
                                style={
                                    'display': 'flex',
                                    'justify-content': 'space-between',
                                    'margin-top': '10px'
                                }),
                            html.Div(
                                [
                                    html.P('Use Leverage:'),
                                    dcc.RadioItems(id='leverage',
                                                   options=[{
                                                       'label': 'Yes',
                                                       'value': 5
                                                   }, {
                                                       'label': 'No',
                                                       'value': 1
                                                   }],
                                                   value=1,
                                                   style={
                                                       'display': 'flex',
                                                       'margin-right': '10px'
                                                   },
                                                   labelStyle={
                                                       'margin-right': '20px'
                                                   })
                                ],
                                style={
                                    'display': 'flex',
                                    'justify-content': 'space-between'
                                }),
                            html.Div(
                                [html.Button('GO!', id='calc_size_button')],
                                style={
                                    'display': 'flex',
                                    'justify-content': 'flex-end'
                                })
                        ],
                                 style={'display': 'inline'})
                    ],
                    className="pretty_container five columns",
                    style={
                        'margin-right': '0',
                        'margin-left': '0',
                        'margin-top': '0',
                        'padding-top': '5px'
                    },
                    id="calculate_size")
            ],
            className='row flex-display')
    ])