def launch(): while True: to_general_log('wsBinance1', 'start websocket Binance') DATABASE.set(RUN_MONITOR_FLAG1, 'False') time.sleep(1) try: subs = '' count = 0 for symbol in SYMBOLS[:100]: subs += symbol.lower() + '@kline_1h/' subs += symbol.lower() + '@kline_5m/' subs += symbol.lower() + '@ticker/' count += 1 if subs != '': to_general_log('wsBinance1', f'{count} pairs') ws = websocket.WebSocketApp( "wss://stream.binance.com:9443/stream?streams={}".format( subs.strip('/')), on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) ws.run_forever() except: print('wsBinance1 Error: websocket failed') print(traceback.format_exc())
def push_bxin_tick(symbol): while True: try: r = requests.get( f"https://bx.in.th/api/orderbook/?pairing={convert_symbol(symbol)}" ) if r is not None: r = json.loads(r.text) bid = round(float(r['bids'][0][0]), 2) ask = round(float(r['asks'][0][0]), 2) bid_amount = float(r['bids'][0][1]) ask_amount = float(r['asks'][0][1]) # print(symbol, ' ', bid, bid_amount, ' ', ask, ask_amount) DATABASE.set( 'bxin_' + symbol, json.dumps({ 'ask': ask, 'bid': bid, 'ask_amount': ask_amount, 'bid_amount': bid_amount })) # print(DATABASE.get('bxin_' + symbol)) time.sleep(TIMEOUT_PUSH) except ConnectionError: log('Too many requests', 'BXIN') err_log(traceback.format_exc()) time.sleep(4)
def on_message(ws, message): try: message = json.loads(message) stream = message['stream'] data = message['data'] if '@kline' in stream: symbol = data['s'] kline = data['k'] if bool(kline['x']): update_history(symbol, kline['i'], kline) if '@ticker' in stream: symbol = stream.split('@')[0].upper() DATABASE.set(symbol, json.dumps({ 'bid': data['b'], 'ask': data['a'] })) update_price_change_percent(symbol, data['P']) # if symbol == 'BNBBTC': # print(symbol, json.dumps({'bid': data['b'], 'ask': data['a']})) except KeyboardInterrupt: pass except: print(traceback.format_exc())
def on_open(ws): print('### opened ###') mem_cache_init_pusher() for symbol in SYMBOLS[:100]: init_price_change_percent(symbol) mem_cache_init(symbol) DATABASE.set(RUN_MONITOR_FLAG1, 'True') print('### monitor is allowed ###')
def to_general_log(symbol, text): log = DATABASE.get(GENERAL_LOG) if log is None: log = '[]' log = json.loads(log) if len(log) > LOG_LENGTH: log = log[-(len(log) - 1):] dt = datetime.now().replace(microsecond=0).isoformat().replace('T', ' ') log.append(dt + ' ' + symbol + ': ' + text) DATABASE.set(GENERAL_LOG, json.dumps(log)) print(dt + ' ' + symbol + ': ' + text)
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 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 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 update_orders_info(exchange, order_id, symbol, side, status, price, amount, date, timestamp): orders = get_orders_info(exchange) orders.update({ order_id: { 'symbol': symbol, 'side': side, 'status': status, 'price': price, 'amount': amount, 'date': date, 'timestamp': timestamp } }) DATABASE.set(exchange + ':' + ORDERS_INFO, json.dumps(orders))
def push_bank_rate(): while True: try: r = requests.get( 'https://www.krungsri.com/bank/en/Other/ExchangeRate/Todayrates.html' ) if r is not None: bank_rate = \ r.text.split("</td></tr><tr style='background-color:transparent !important'>")[0].split('>')[-1] DATABASE.set(BANK_RATE, bank_rate) # print(bank_rate) time.sleep(TIMEOUT_PUSH) except ConnectionError: log('Too many requests', 'BankRate') err_log(traceback.format_exc()) time.sleep(4)
def on_message(ws, message): # print(type(message), message) message = json.loads(message) if 'e' in message: if message['e'] == 'outboundAccountInfo': balances = message['B'] xd = [] for balance in balances: xd.append({'asset': balance['a'], 'free': balance['f']}) DATABASE.set(BALANCE, json.dumps(xd)) print('WS: balances updated', len(xd)) print(xd) if message['e'] == 'executionReport': update_orders_info('Binance', message['i'], message['s'], message['S'], format_status(message['X']), message['p'], message['q'], message['O'], int(time.time() * 1000)) print('Update orders', format_status(message['X']), message)
def update_history(symbol, time_frame, kline): try: time_now = datetime.datetime.utcfromtimestamp(time.time()).strftime('%H:%M:%S') history = DATABASE.get(symbol + time_frame.upper()) if history is not None: history = json.loads(history) history.pop(0) kline = [kline['t'], kline['o'], kline['h'], kline['l'], kline['c'], kline['v'], kline['T'], kline['q'], kline['n'], kline['V'], kline['Q'], kline['B']] history.append(kline) print(symbol, time_now, time_frame.upper()) DATABASE.set(symbol + time_frame.upper(), json.dumps(history)) except: to_general_log(symbol, 'Connect timeout. Reconnection...')
def push_itbit_tick(symbol): while True: try: r = requests.get( f"https://api.itbit.com/v1/markets/{symbol.replace('_', '')}/ticker" ) if r is not None: r = json.loads(r.text) DATABASE.set( 'itbit_' + symbol, json.dumps({ 'ask': float(r['ask']), 'bid': float(r['bid']), 'ask_amount': float(r['askAmt']), 'bid_amount': float(r['bidAmt']) })) # print(DATABASE.get('itbit_' + symbol)) time.sleep(TIMEOUT_PUSH) except ConnectionError: log('Too many requests', 'ITBIT') err_log(traceback.format_exc()) time.sleep(4)
def on_close(ws): print("### closed ###") DATABASE.set(RUN_MONITOR_FLAG1, 'False')
def remove_orders_info(exchange, order_id): orders = get_orders_info(exchange) orders.pop(order_id, None) DATABASE.set(exchange + ':' + ORDERS_INFO, json.dumps(orders))
def clear_general_log(): DATABASE.set(GENERAL_LOG, '[]')
def set_orders_info(exchange): DATABASE.set(exchange + ':' + ORDERS_INFO, json.dumps({}))
def init_price_change_percent(symbol): DATABASE.set(symbol + ':' + PRICE_CHANGE_PERCENT, json.dumps({}))
def set_price_change_percent(symbol, values): DATABASE.set(symbol + ':' + PRICE_CHANGE_PERCENT, json.dumps(values))
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) ws = websocket.WebSocketApp( f"wss://stream.binance.com:9443/ws/{listen_key}", on_open=on_open, on_message=on_message,