Search code examples
pythonwebsocketmultiprocessing

The fastest way to reconnect websocket with update url


I need to recieve some data from binance api. And when coins changes, i need to update url of websocket. But I want to spend as little time as possible.To avoid overloading the main thread, I create the websocket in a separate process This is code, how i impletemented this:

from functools import partial
from threading import Thread
from multiprocessing import Process, Manager
import time
import json
import websocket
import requests

def on_message(_wsa, result, prices):
    result = json.loads(result)
    prices[result['s']]['best_bid'] = result['b']
    prices[result['s']]['best_ask'] = result['a']


def start_stream_currency(curr_list,prices):
    url = 'wss://fstream.binance.com/ws'

    manager = Manager()
    for curr in curr_list:
        url += '/' + curr.lower() + '@bookTicker'
    wsa = websocket.WebSocketApp(url, on_message=partial(on_message, prices=prices))

    for curr in curr_list:
        prices[curr] = manager.dict()

    wsa.run_forever()


def check_price_symbols(prices): # This func check prices from websocket
    while True:
        for key, value in prices.copy().items():
            print(f"{key} {value}")
            #some calculations
        time.sleep(1)

def main():
    prices = Manager().dict()
    th = Thread(target=check_price_symbols, args=(prices,))
    th.start()

    curr_list = ['BTCUSDT','ADAUSDT']
    
    pr = Process(target=start_stream_currency, args=(curr_list,prices))
    pr.start()

    time.sleep(15)
    print('Restart starting')
    curr_list2 = ['ADAUSDT','XRPUSDT']
    pr2 = Process(target=start_stream_currency, args=(curr_list2, prices))
    pr2.start()
    pr.terminate()
    del prices['BTCUSDT']
    pr2.join()

if __name__ =='__main__':
    main()

Need to close old process when new process is already running. Can anyone tell me how best to implement this?


Solution

  • There's no need to restart the process or even the WebSocket connection.

    A cleaner way to continue the same WebSocket connection but with a change of symbols is through the 'Live Subscribe/Unsubscribe' method, which is described in the Futures API documentation in the 'WebSocket Market Stream' section.