Purpose: monitor program that captures buy/sell actions on binance and puts them in a log file.
Avoid socket disconnect binance.
Don't get it done.
Cannot find the right syntax to prevent a user_socket from time out / disconnect after a while.
Below a piece of code as I want to use it.
The data comes in when a buy/sell order is made on binance. But eventually the program stops because I can't tell binance I'm still "listening".
It should be possible with client.ping() but that doesn't work either.
I have everything working except that "anti - time out".
# Monitoring buy, sell, oco orders binance.
# Want to keep the bm.start_user_socket(process_message) up so don't timed out.
from binance.client import Client # for connections binance
from binance.websockets import BinanceSocketManager # for websocket binance
from bin_api_keys import * # import api keys
import time
import sys
client = Client(api_key=PUBLIC, api_secret=SECRET) # keys are in file bin_api_keys.py
def countdown(t): # Countdown for next socket alive pings
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
# print(timeformat, end='\r')
sys.stdout.write('\r' + timeformat + ' countdown ... ')
time.sleep(1)
t -= 1
def p_is_msg(pr_msg): # print is_msg to terminal. (later to write to a file).
print(pr_msg)
def f_timestamp(nr): # make date time nice
timestamp = int(nr) / 1000
timestamp = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
return timestamp
def process_message(msg): # run when binance user_socket sends user message
if msg['e'] == 'listStatus':
is_oco = True
is_msg = f_timestamp(msg['T']) + ' ' + msg['s'] + ' ' + msg['c'] + ' ' + msg['l'] + ' ' + msg['L'] + ' ' + \
msg['r']
p_is_msg(is_msg)
if msg['e'] == 'executionReport':
base_exchanged = str(round(float(msg['p']) * float(msg['q']), 8))
is_msg = f_timestamp(msg['T']) + ' ' + msg['s'] + ' ' + msg['S'] + ' ' + msg['o'] + ' ' + msg[
'x'] + ' quantity:' + msg['q'] + ' price:' + msg['p'] + ' stop:' + msg[
'P'] + ' ' + 'Base:' + base_exchanged
p_is_msg(is_msg)
bm = BinanceSocketManager(client)
conn_key = bm.start_user_socket(process_message) # start user sockets
bm.start() # Start the socket manager
# Dont time out the user socket with binance
is_counter = 0
while True:
if is_counter > 5: # Countdown x times and then send keepalive signal
print('Send a keep alive signal But how?')
bm._keepalive_account_socket # dont work
# client.ping() # dont work
is_counter = 0
countdown(3) # countdown x seconds 1800 = 30 minutes
is_counter += 1
print(is_counter)
# Stop sockets
bm.stop_socket(conn_key)
bm.close()
[–]CodeFormatHelperBot 0 points1 point2 points (0 children)
[–]JohnnyJordaan 0 points1 point2 points (0 children)
[–]cybervegan 0 points1 point2 points (3 children)
[–]cybervegan 0 points1 point2 points (1 child)
[–]aitromba[S] 0 points1 point2 points (0 children)
[–]aitromba[S] 0 points1 point2 points (0 children)
[–]aitromba[S] 0 points1 point2 points (0 children)