async def main(symbol: str, future: bool): market_type = "future" if future else "spot" print(f'Started Collecting Tick Data of {symbol}...({market_type} market)') client = await AsyncClient.create() bsm = BinanceSocketManager(client) if future: async with bsm.aggtrade_futures_socket(symbol) as socket: while True: res = await socket.recv() process_message(res['data'], future) else: async with bsm.trade_socket(symbol) as socket: while True: res = await socket.recv() process_message(res, future)
class BinanceAPI: def __init__(self, logger=logging.getLogger(), api_key=None, api_secret=None): self.client = AsyncClient(api_key, api_secret) self.bm = BinanceSocketManager(self.client) self.logger = logger self.callbacks = [] self.event_loop = asyncio.get_event_loop() self.queue = asyncio.Queue() def subscribe_futures(self, symbol): self.event_loop.create_task(self.loop(symbol)) def on_message(self, callback): self.callbacks.append(callback) def process_message(self, message): data = message['data'] asyncio.run_coroutine_threadsafe(self.queue.put(data), self.event_loop) async def loop(self, symbol): async with self.bm.aggtrade_futures_socket(symbol) as ts: while True: try: print("wait bin") # self.logger.info("wait bin") data = await asyncio.wait_for(ts.recv(), 5) print("recieved bin") # self.logger.info("recieved bin") if data != None: for callback in self.callbacks: callback('binance-s', data) except Exception as e: print("retry binance") # self.logger.warning("retry binance") self.subscribe_futures(symbol) break