def place_market_order(symbol, side, quantity, marker): if quantity is None: to_general_log(symbol, 'ERROR Qty is NONE') return if side == 'buy': order = BINANCE.order_market_buy(symbol=symbol, quantity=quantity, recvWindow=10000000) to_general_log(symbol, '{} Market order placed ({}) > {}'.format(side, marker, json.dumps(order))) return order else: order = BINANCE.order_market_sell(symbol=symbol, quantity=quantity, recvWindow=10000000) to_general_log(symbol, '{} Market order placed ({}) > {}'.format(side, marker, json.dumps(order))) return order
def mem_cache_init_pusher(): exchange_info = BINANCE.get_exchange_info() if exchange_info is not None: DATABASE.set(EXCHANGE_INFO, json.dumps(exchange_info)) print('exchange_info', len(exchange_info), exchange_info) tickers = BINANCE.get_ticker() if tickers is not None: DATABASE.set(TICKERS, json.dumps(tickers)) print('tickers', len(tickers), tickers) time.sleep(1)
def mem_cache_init(symbol): time_now = datetime.datetime.utcfromtimestamp(time.time()).strftime('%H:%M:%S') history5m = BINANCE.get_klines(symbol=symbol, interval=BINANCE.KLINE_INTERVAL_5MINUTE) history1h = BINANCE.get_klines(symbol=symbol, interval=BINANCE.KLINE_INTERVAL_1HOUR) print(symbol, time_now, '5M') DATABASE.set(symbol + '5M', json.dumps(history5m)) print(symbol, time_now, '1H') DATABASE.set(symbol + '1H', json.dumps(history1h)) time.sleep(0.5)
def cancel_limit_order(symbol, side, order_id, marker): try: remove_orders_info('Binance', order_id) order = BINANCE.cancel_order(symbol=symbol, orderId=order_id) to_general_log(symbol, '{} Limit order canceled ({}) > {}'.format(side, marker, json.dumps(order))) except: pass
def push_volume(): try: global t_volume if time.time() - t_volume > VOLUME_UPDATE: tickers = BINANCE.get_ticker() if tickers is not None: DATABASE.set(TICKERS, json.dumps(tickers)) # print('tickers', len(tickers), tickers) t_volume = time.time() time.sleep(0.5) except requests.exceptions.ConnectionError as e: print(type(e)) print(traceback.format_exc())
def push_market_info(): try: global t_mi if time.time() - t_mi > to_mi: exchange_info = BINANCE.get_exchange_info() if exchange_info is not None: DATABASE.set(EXCHANGE_INFO, json.dumps(exchange_info)) # print('exchange_info', len(exchange_info), exchange_info) t_mi = time.time() time.sleep(0.5) except requests.exceptions.ConnectionError as e: print(type(e)) print(traceback.format_exc())
def stream_keepalive(listen_key): try: BINANCE.stream_keepalive(listen_key) return True except ConnectionError: return False
def get_listen_key(): return BINANCE.stream_get_listen_key()
def keep_alive(): while True: lk = stream_keepalive(listen_key) if lk: time.sleep(30 * 60) else: time.sleep(30) th = threading.Thread(target=keep_alive) th.start() if __name__ == "__main__": try: while True: balances = BINANCE.get_account()['balances'] set_orders_info('Binance') if balances is not None: DATABASE.set(BALANCE, json.dumps(balances)) print('balances', len(balances), balances) else: print('websocket bibox error balances') continue DATABASE.set(BALANCE, json.dumps(balances)) print('REST: balances updated', len(balances)) listen_key = get_listen_key() print(listen_key)
def main(): cerebro = bt.Cerebro(quicknotify=True) if ENV == PRODUCTION: # Live trading with Binance broker_config = { 'apiKey': BINANCE.get("key"), 'secret': BINANCE.get("secret"), 'nonce': lambda: str(int(time.time() * 1000)), 'enableRateLimit': True, } store = CCXTStore(exchange='binance', currency=COIN_REFER, config=broker_config, retries=5, debug=DEBUG) broker_mapping = { 'order_types': { bt.Order.Market: 'market', bt.Order.Limit: 'limit', bt.Order.Stop: 'stop-loss', bt.Order.StopLimit: 'stop limit' }, 'mappings': { 'closed_order': { 'key': 'status', 'value': 'closed' }, 'canceled_order': { 'key': 'status', 'value': 'canceled' } } } broker = store.getbroker(broker_mapping=broker_mapping) cerebro.setbroker(broker) hist_start_date = dt.datetime.utcnow() - dt.timedelta(minutes=30000) data = store.getdata(dataname='%s/%s' % (COIN_TARGET, COIN_REFER), name='%s%s' % (COIN_TARGET, COIN_REFER), timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date, compression=30, ohlcv_limit=99999) # Add the feed cerebro.adddata(data) else: # Backtesting with CSV file data = CustomDataset(name=COIN_TARGET, dataname="dataset/binance_nov_18_mar_19_btc.csv", timeframe=bt.TimeFrame.Minutes, fromdate=dt.datetime(2018, 9, 20), todate=dt.datetime(2019, 3, 13), nullvalue=0.0) cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=30) broker = cerebro.getbroker() broker.setcommission(commission=0.001, name=COIN_TARGET) # Simulating exchange fee broker.setcash(100000.0) cerebro.addsizer(FullMoney) # Analyzers to evaluate trades and strategies # SQN = Average( profit / risk ) / StdDev( profit / risk ) x SquareRoot( number of trades ) cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta") cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn") # Include Strategy cerebro.addstrategy(BasicRSI) # Starting backtrader bot initial_value = cerebro.broker.getvalue() print('Starting Portfolio Value: %.2f' % initial_value) result = cerebro.run() # Print analyzers - results final_value = cerebro.broker.getvalue() print('Final Portfolio Value: %.2f' % final_value) print('Profit %.3f%%' % ((final_value - initial_value) / initial_value * 100)) print_trade_analysis(result[0].analyzers.ta.get_analysis()) print_sqn(result[0].analyzers.sqn.get_analysis()) if DEBUG: cerebro.plot()