def get_currencies_with_status(): symbol_with_evaluation = {} for key, symbol_evaluator in get_bot().get_symbol_evaluator_list().items(): symbol_with_evaluation[symbol_evaluator.get_symbol()] = \ {exchange.get_name(): symbol_evaluator.get_final(exchange).get_state() for exchange in get_bot().get_exchanges_list().values() if symbol_evaluator.has_exchange(exchange)} return symbol_with_evaluation
def get_currency_graph_update(exchange_name, symbol, time_frame, cryptocurrency_name): symbol_evaluator_list = get_bot().get_symbol_evaluator_list() exchange_list = get_bot().get_exchanges_list() if time_frame is not None: if len(symbol_evaluator_list) > 0: evaluator_thread_managers = symbol_evaluator_list[symbol].get_evaluator_thread_managers( exchange_list[exchange_name]) if time_frame in evaluator_thread_managers: evaluator_thread_manager = evaluator_thread_managers[time_frame] df = evaluator_thread_manager.get_evaluator().get_data() if df is not None: symbol_tag, pair_tag = Exchange.split_symbol(symbol) add_to_symbol_data_history(symbol, df, time_frame) df = get_symbol_data_history(symbol, time_frame) # df.loc[:, PriceStrings.STR_PRICE_TIME.value] /= 1000 X = df[PriceStrings.STR_PRICE_TIME.value] Y = df[PriceStrings.STR_PRICE_CLOSE.value] # Candlestick data = go.Ohlc(x=df[PriceStrings.STR_PRICE_TIME.value], open=df[PriceStrings.STR_PRICE_OPEN.value], high=df[PriceStrings.STR_PRICE_HIGH.value], low=df[PriceStrings.STR_PRICE_LOW.value], close=df[PriceStrings.STR_PRICE_CLOSE.value]) real_trades_prices, real_trades_times, simulated_trades_prices, simulated_trades_times = \ get_trades_by_times_and_prices() real_trades_points = go.Scatter( x=real_trades_prices, y=real_trades_times, mode='markers', name='markers' ) simulated_trades_points = go.Scatter( x=simulated_trades_times, y=simulated_trades_prices, mode='markers', name='markers' ) return {'data': [data, real_trades_points, simulated_trades_points], 'layout': go.Layout( title="{} real time data (per time frame)".format(cryptocurrency_name), xaxis=dict(range=[min(X), max(X)], title=TIME_AXIS_TITLE), yaxis=dict(range=[min(Y) * 0.98, max(Y) * 1.02], title=pair_tag) )} return None
def get_portfolios(): simulated_portfolios = [] real_portfolios = [] traders = [trader for trader in get_bot().get_exchange_traders().values()] + \ [trader for trader in get_bot().get_exchange_trader_simulators().values()] for trader in traders: if trader.get_simulate(): simulated_portfolios.append(trader.get_portfolio().get_portfolio()) else: real_portfolios.append(trader.get_portfolio().get_portfolio()) return real_portfolios, simulated_portfolios
def get_global_profitability(): simulated_global_profitability = 0 real_global_profitability = 0 traders = [trader for trader in get_bot().get_exchange_traders().values()] + \ [trader for trader in get_bot().get_exchange_trader_simulators().values()] for trader in traders: trade_manager = trader.get_trades_manager() # TODO : use other return values current_value, _, _ = trade_manager.get_profitability() if trader.get_simulate(): simulated_global_profitability += current_value else: real_global_profitability += current_value return real_global_profitability, simulated_global_profitability
def get_evaluator_graph_in_matrix_history(symbol, exchange_name, evaluator_type, evaluator_name, time_frame, cryptocurrency_name): symbol_evaluator_list = get_bot().get_symbol_evaluator_list() exchange_list = get_bot().get_exchanges_list() if evaluator_name is not None and len(symbol_evaluator_list) > 0: matrix = symbol_evaluator_list[symbol].get_matrix(exchange_list[exchange_name]) add_to_matrix_history(matrix) formatted_matrix_history = { "timestamps": [], "evaluator_data": [] } for matrix in get_matrix_history(): if evaluator_type == EvaluatorMatrixTypes.TA: eval_note = EvaluatorMatrix.get_eval_note(matrix["matrix"], evaluator_type, evaluator_name, time_frame) else: eval_note = EvaluatorMatrix.get_eval_note(matrix["matrix"], evaluator_type, evaluator_name) if eval_note is not None: formatted_matrix_history["evaluator_data"].append(eval_note) formatted_matrix_history["timestamps"].append(matrix["timestamp"]) data = plotly.graph_objs.Scatter( x=formatted_matrix_history["timestamps"], y=formatted_matrix_history["evaluator_data"], name='Scatter', mode='lines+markers' ) return {'data': [data], 'layout': go.Layout( title="{} strategy".format(cryptocurrency_name), xaxis=dict(range=[get_bot().get_start_time(), time.time()], title=TIME_AXIS_TITLE), yaxis=dict(range=[-1.1, 1.1], title="Buy or sell") )} return None
def get_trades_by_times_and_prices(): simulated_trades_times = [] simulated_trades_prices = [] real_trades_times = [] real_trades_prices = [] traders = [trader for trader in get_bot().get_exchange_traders().values()] + \ [trader for trader in get_bot().get_exchange_trader_simulators().values()] for trader in traders: for trade in trader.get_trades_manager().get_trade_history(): if trader.get_simulate(): simulated_trades_times.append(trade.get_filled_time()) simulated_trades_prices.append(trade.get_price()) else: real_trades_times.append(trade.get_filled_time()) real_trades_prices.append(trade.get_price()) return real_trades_prices, real_trades_times, simulated_trades_prices, simulated_trades_times
def get_portfolio_current_value(): simulated_value = 0 real_value = 0 traders = [trader for trader in get_bot().get_exchange_traders().values()] + \ [trader for trader in get_bot().get_exchange_trader_simulators().values()] for trader in traders: trade_manager = trader.get_trades_manager() current_value = trade_manager.get_portfolio_current_value() # current_value might be 0 if no trades have been made / canceled => use origin value if current_value == 0: current_value = trade_manager.get_portfolio_origin_value() if trader.get_simulate(): simulated_value += current_value else: real_value += current_value return real_value, simulated_value
def get_portfolio_value_in_history(): at_least_one_simulated = False at_least_one_real = False min_value = 0 max_value = 1 reference_market = get_reference_market() portfolio_value_in_history = get_portfolio_value_history() if max(portfolio_value_in_history["real_value"]) > 0: at_least_one_real = True if max(portfolio_value_in_history["simulated_value"]) > 0: at_least_one_simulated = True real_data = plotly.graph_objs.Scatter( x=portfolio_value_in_history["timestamp"], y=portfolio_value_in_history["real_value"], name='Real Portfolio in {}'.format(reference_market), mode='lines' ) simulated_data = plotly.graph_objs.Scatter( x=portfolio_value_in_history["timestamp"], y=portfolio_value_in_history["simulated_value"], name='Simulated Portfolio in {}'.format(reference_market), mode='lines' ) # Title real_simulated_string = "real" if at_least_one_real or not at_least_one_simulated else "" real_simulated_string += " and " if at_least_one_simulated and at_least_one_real else "" real_simulated_string += "simulated" if at_least_one_simulated else "" # merge two portfolio types merged_data = [] if at_least_one_simulated: merged_data.append(simulated_data) min_value = min(portfolio_value_in_history["simulated_value"]) max_value = max(portfolio_value_in_history["simulated_value"]) if at_least_one_real or not at_least_one_simulated: merged_data.append(real_data) min_value = min(min_value, min(portfolio_value_in_history["real_value"])) max_value = max(max_value, max(portfolio_value_in_history["real_value"])) return {'data': merged_data, 'layout': go.Layout( title='Portfolio value ({})'.format(real_simulated_string), xaxis=dict(range=[get_bot().get_start_time(), time.time()], title=TIME_AXIS_TITLE), yaxis=dict(range=[max(0, min_value * 0.99), max(0.1, max_value * 1.01)], title=reference_market) )}
def get_portfolio_currencies_update(): currencies = [] bot = get_bot() traders = [trader for trader in bot.get_exchange_traders().values()] + \ [trader for trader in bot.get_exchange_trader_simulators().values()] for trader in traders: currencies += [ { "Cryptocurrency": [currency], "Total (available)": ["{} ({})".format(amounts[Portfolio.TOTAL], amounts[Portfolio.AVAILABLE])], "Exchange": [trader.exchange.get_name()], "Real / Simulator": ["Simulator" if trader.get_simulate() else "Real"] } for currency, amounts in trader.get_portfolio().get_portfolio().items()] return currencies
def get_traders(bot=None): if bot is None: bot = get_bot() return [trader for trader in bot.get_exchange_traders().values()] + \ [trader for trader in bot.get_exchange_trader_simulators().values()]
def get_global_config(): return get_bot().get_config()
def get_risk(): return next(iter(get_bot().get_exchange_traders().values())).get_risk()
def get_edited_config(): return get_bot().get_edited_config()
def get_backtesting_report(): tools = get_bot().get_tools() if tools[BOT_TOOLS_BACKTESTING]: backtester = tools[BOT_TOOLS_BACKTESTING] return get_bot().run_in_main_asyncio_loop(backtester.get_report()) return {}
def get_trading_mode(): return get_bot().get_trading_mode().get_name()
def _get_config(): return get_bot().edited_config
def is_trading_persistence_activated(): return get_bot( ).exchange_factory.previous_trading_state_manager is not None
def _signal_handler(_, __): # run Commands.BOT.stop_threads in thread because can't use the current asyncio loop stopping_thread = Thread(target=get_bot().stop_threads) stopping_thread.start() stopping_thread.join() os._exit(0)
def get_trading_startup_config(): return get_bot().startup_config[CONFIG_TRADING_TENTACLES]
def reset_trading_history(): previous_state_manager = get_bot( ).exchange_factory.previous_trading_state_manager if previous_state_manager: previous_state_manager.reset_trading_history()
def get_evaluator_startup_config(): return get_bot().startup_config[CONFIG_EVALUATOR]
def get_currency_price_graph_update(exchange_name, symbol, time_frame, list_arrays=True, backtesting=False): bot = get_bot() if backtesting and bot.get_tools() and bot.get_tools( )[BOT_TOOLS_BACKTESTING]: bot = bot.get_tools()[BOT_TOOLS_BACKTESTING].get_bot() symbol = parse_get_symbol(symbol) symbol_evaluator_list = bot.get_symbol_evaluator_list() in_backtesting = Backtesting.enabled(get_global_config()) or backtesting exchange = exchange_name exchange_list = bot.get_exchanges_list() if backtesting: exchanges = [key for key in exchange_list if exchange_name in key] if exchanges: exchange = exchanges[0] if time_frame is not None: if symbol_evaluator_list: evaluator_thread_managers = symbol_evaluator_list[ symbol].get_evaluator_thread_managers(exchange_list[exchange]) if time_frame in evaluator_thread_managers: evaluator_thread_manager = evaluator_thread_managers[ time_frame] data = evaluator_thread_manager.get_evaluator().get_data() if data is not None: candles_key = "candles" real_trades_key = "real_trades" simulated_trades_key = "simulated_trades" result_dict = { candles_key: [], real_trades_key: [], simulated_trades_key: [], } _, pair_tag = split_symbol(symbol) add_to_symbol_data_history(symbol, data, time_frame, in_backtesting) data = get_symbol_data_history(symbol, time_frame) data_x = convert_timestamps_to_datetime( data[PriceIndexes.IND_PRICE_TIME.value], time_format="%y-%m-%d %H:%M:%S", force_timezone=False) real_trades_history, simulated_trades_history = get_trades_history( bot, symbol) if real_trades_history: result_dict[real_trades_key] = _format_trades( real_trades_history) if real_trades_history: result_dict[simulated_trades_key] = _format_trades( simulated_trades_history) if list_arrays: result_dict[candles_key] = { PriceStrings.STR_PRICE_TIME.value: data_x, PriceStrings.STR_PRICE_CLOSE.value: data[PriceIndexes.IND_PRICE_CLOSE.value].tolist(), PriceStrings.STR_PRICE_LOW.value: data[PriceIndexes.IND_PRICE_LOW.value].tolist(), PriceStrings.STR_PRICE_OPEN.value: data[PriceIndexes.IND_PRICE_OPEN.value].tolist(), PriceStrings.STR_PRICE_HIGH.value: data[PriceIndexes.IND_PRICE_HIGH.value].tolist() } else: result_dict[candles_key] = { PriceStrings.STR_PRICE_TIME.value: data_x, PriceStrings.STR_PRICE_CLOSE.value: data[PriceIndexes.IND_PRICE_CLOSE.value], PriceStrings.STR_PRICE_LOW.value: data[PriceIndexes.IND_PRICE_LOW.value], PriceStrings.STR_PRICE_OPEN.value: data[PriceIndexes.IND_PRICE_OPEN.value], PriceStrings.STR_PRICE_HIGH.value: data[PriceIndexes.IND_PRICE_HIGH.value] } return result_dict return None
def get_global_startup_config(): return get_bot().get_startup_config()
def run(self): # wait bot is ready while get_bot() is None or not get_bot().is_ready(): sleep(0.1) # Define the WSGI application object self.app = app_instance self.app.layout = html.Div(children=[ html.H1('CryptoBot Dashboard'), dcc.Graph(id='portfolio-value-graph', animate=True), dt.DataTable(rows=[{}], row_selectable=False, filterable=True, sortable=True, editable=False, selected_row_indices=[], id='datatable-portfolio'), dcc.Interval(id='portfolio-update', interval=3 * 1000), html.Div( [ html.Label('Exchange'), dcc.Dropdown( id='exchange-name', options=[{ 'label': s, 'value': s } for s in get_bot().get_exchanges_list().keys()], value=next(iter( get_bot().get_exchanges_list().keys())), multi=False, ), html.Label('Currency'), dcc.Dropdown( id='cryptocurrency-name', options=[{ 'label': s, 'value': s } for s in self.config[CONFIG_CRYPTO_CURRENCIES].keys()], value=next( iter( self.config[CONFIG_CRYPTO_CURRENCIES].keys())), multi=False, ), html.Label('Symbol'), dcc.Dropdown( id='symbol', options=[], value="BTC/USDT", multi=False, ), html.Label('TimeFrame'), dcc.Dropdown( id='time-frame', options=[], value=None, multi=False, ), html.Label('Evaluator'), dcc.Dropdown( id='evaluator-name', options=[], value="", multi=False, ), ], style={ 'columnCount': 1, 'marginLeft': 25, 'marginRight': 25, 'marginTop': 25, 'marginBottom': 25 }), dcc.Graph(id='live-graph', animate=True), dcc.Interval(id='graph-update', interval=3 * 1000), dcc.Graph(id='strategy-live-graph', animate=True), dcc.Interval(id='strategy-graph-update', interval=3 * 1000), ]) load_callbacks() load_routes() self.app.run_server(host='0.0.0.0', port=5000, debug=False, threaded=True)
def set_command_stop(): get_bot().stop() return os._exit(0)
def close_callback(): Commands.stop_bot(get_bot())
def can_get_community_metrics(): return can_read_metrics(get_bot().edited_config)
def get_optimizer_report(): if get_optimizer_status()[0] == "finished": optimizer = get_bot().get_tools()[BOT_TOOLS_STRATEGY_OPTIMIZER] return optimizer.get_report() else: return []
def get_currency_graph_update(exchange_name, symbol, time_frame, cryptocurrency_name): symbol_evaluator_list = get_bot().get_symbol_evaluator_list() exchange_list = get_bot().get_exchanges_list() if time_frame is not None: if len(symbol_evaluator_list) > 0: evaluator_thread_managers = symbol_evaluator_list[ symbol].get_evaluator_thread_managers( exchange_list[exchange_name]) if time_frame in evaluator_thread_managers: evaluator_thread_manager = evaluator_thread_managers[ time_frame] df = evaluator_thread_manager.get_evaluator().get_data() if df is not None: symbol_tag, pair_tag = Exchange.split_symbol(symbol) add_to_symbol_data_history(symbol, df, time_frame) df = get_symbol_data_history(symbol, time_frame) # df.loc[:, PriceStrings.STR_PRICE_TIME.value] /= 1000 X = df[PriceStrings.STR_PRICE_TIME.value] Y = df[PriceStrings.STR_PRICE_CLOSE.value] # Candlestick data = go.Ohlc( x=df[PriceStrings.STR_PRICE_TIME.value], open=df[PriceStrings.STR_PRICE_OPEN.value], high=df[PriceStrings.STR_PRICE_HIGH.value], low=df[PriceStrings.STR_PRICE_LOW.value], close=df[PriceStrings.STR_PRICE_CLOSE.value]) real_trades_prices, real_trades_times, simulated_trades_prices, simulated_trades_times = \ get_trades_by_times_and_prices() real_trades_points = go.Scatter(x=real_trades_prices, y=real_trades_times, mode='markers', name='markers') simulated_trades_points = go.Scatter( x=simulated_trades_times, y=simulated_trades_prices, mode='markers', name='markers') return { 'data': [data, real_trades_points, simulated_trades_points], 'layout': go.Layout( title="{} real time data (per time frame)".format( cryptocurrency_name), xaxis=dict(range=[min(X), max(X)], title=TIME_AXIS_TITLE), yaxis=dict(range=[min(Y) * 0.98, max(Y) * 1.02], title=pair_tag)) } return None
def get_in_backtesting_mode(): return Backtesting.enabled(get_bot().get_config())
def command_ping(_, update): update.message.reply_text("I'm alive since {0}.".format( datetime.datetime.fromtimestamp( get_bot().get_start_time()).strftime('%Y-%m-%d %H:%M:%S')))
def command_ping(_, update): update.message.reply_text("I'm alive since {0}.".format( datetime.datetime.fromtimestamp(get_bot().get_start_time()).strftime('%Y-%m-%d %H:%M:%S')))
def command_stop(_, update): # TODO add confirmation update.message.reply_text("I'm leaving this world...") get_bot().stop_threads() os._exit(0)
def get_exchange_time_frames(exchange_name): for exchange in get_bot().get_exchanges_list().values(): if not exchange_name or exchange.get_name() == exchange_name: return exchange.get_exchange_manager().get_config_time_frame( ), exchange.get_name() return [], ""
def get_trading_mode(): return get_bot().get_config()[CONFIG_TRADING][CONFIG_TRADER_MODE]
def command_stop(_, update): # TODO add confirmation update.message.reply_text("I'm leaving this world...") Commands.stop_bot(get_bot())
def set_risk(risk): traders = [trader for trader in get_bot().get_exchange_traders().values()] + \ [trader for trader in get_bot().get_exchange_trader_simulators().values()] for trader in traders: trader.set_risk(risk)
def sell_all(currency): orders = [] for trader in get_traders(): orders += get_bot().run_in_main_asyncio_loop(trader.sell_all(currency)) return orders
def command_ping(_, update): update.message.reply_text("I'm alive since {0}.".format( convert_timestamp_to_datetime(get_bot().get_start_time(), '%Y-%m-%d %H:%M:%S')))
def cancel_all_open_orders(currency=None): for trader in get_traders(): if currency is None: get_bot().run_in_main_asyncio_loop(trader.cancel_all_open_orders()) else: get_bot().run_in_main_asyncio_loop(trader.cancel_all_open_orders_with_currency(currency))
def run(self): # wait bot is ready while get_bot() is None or not get_bot().is_ready(): sleep(0.1) # Define the WSGI application object self.app = app_instance self.app.layout = html.Div(children=[ html.H1('CryptoBot Dashboard'), dcc.Graph(id='portfolio-value-graph', animate=True), dt.DataTable( rows=[{}], row_selectable=False, filterable=True, sortable=True, editable=False, selected_row_indices=[], id='datatable-portfolio' ), dcc.Interval( id='portfolio-update', interval=3 * 1000 ), html.Div([ html.Label('Exchange'), dcc.Dropdown(id='exchange-name', options=[{'label': s, 'value': s} for s in get_bot().get_exchanges_list().keys()], value=next(iter(get_bot().get_exchanges_list().keys())), multi=False, ), html.Label('Currency'), dcc.Dropdown(id='cryptocurrency-name', options=[{'label': s, 'value': s} for s in self.config[CONFIG_CRYPTO_CURRENCIES].keys()], value=next(iter(self.config[CONFIG_CRYPTO_CURRENCIES].keys())), multi=False, ), html.Label('Symbol'), dcc.Dropdown(id='symbol', options=[], value="BTC/USDT", multi=False, ), html.Label('TimeFrame'), dcc.Dropdown(id='time-frame', options=[], value=None, multi=False, ), html.Label('Evaluator'), dcc.Dropdown(id='evaluator-name', options=[], value="", multi=False, ), ], style={'columnCount': 1, 'marginLeft': 25, 'marginRight': 25, 'marginTop': 25, 'marginBottom': 25}), dcc.Graph(id='live-graph', animate=True), dcc.Interval( id='graph-update', interval=3 * 1000 ), dcc.Graph(id='strategy-live-graph', animate=True), dcc.Interval( id='strategy-graph-update', interval=3 * 1000 ), ]) load_callbacks() load_routes() self.app.run_server(host='0.0.0.0', port=5000, debug=False, threaded=True)