Friday, 20 August 2021

Unable to get Queue value with Python Class Structure / Transform functions to class structure

I have written an Object-Oriented script in Python to retrieve and process live Binance tick data. The class stores the tick data in a Queue. For further processing, the Queue data is loaded in get_queue() method in the same class. Here is my code:

import websocket, json
from datetime import datetime
import threading
import time
import queue

class stream:

    def __init__(self, event_queue):
        self.event_queue = event_queue

    def on_message(self, ws, message):
        data = json.loads(message)
        timestamp = datetime.utcfromtimestamp(data['E']/1000).strftime('%Y-%m-%d %H:%M:%S')
        symbol = data['s']
        open = data['o']
        high = data['h']
        low = data['l']
        close = data['c']
        volume = data['v']
        trade = data['n'] #No. of Trades
        tick = f'tick :timestamp: {timestamp} :symbol: {symbol} :close_price: {close} :volume: {volume}:open_price: {open}:high_price: {high}:low_price: {low}:trade_qyt: {trade}'
        self.event_queue.put(tick)

    def on_close(self, ws, message):
        print("bang")
    
    def run(self):
        self.socket = websocket.WebSocketApp(
            "wss://stream.binance.com:9443/ws/btcusdt@ticker/ethbtc@ticker/bnbbtc@ticker/wavesbtc@ticker/stratbtc@ticker/ethup@ticker/yfiup@ticker/xrpup@ticker",
            on_message=self.on_message,
            on_close=self.on_close)
        self.wst = threading.Thread(target=lambda: self.socket.run_forever())
        self.wst.daemon = True
        self.wst.start()
        while not self.socket.sock.connected: #and conn_timeout:
            print("this")
            time.sleep(1)
        while self.socket.sock is not None:
            print("that")
            time.sleep(10)

    def get_queue(self):
        while 1:
            print("This is this: ", self.event_queue.get(True))
        

if __name__ == "__main__":
    message_queue = queue.Queue()
    stream = stream(event_queue=message_queue)
    thread = threading.Thread(target=stream.get_queue,daemon=True)
    thread.start()
    stream.run()
    

Using the Object-Oriented approach (given above), my Queue ends up giving no values to my terminal. However, with the procedural approach (give below) I get my desired results. Here is the procedural implementation:

import websocket, json
from datetime import datetime
import threading
import time
import queue

events = queue.Queue()
socket = f'wss://stream.binance.com:9443/ws/btcusdt@ticker/ethbtc@ticker/bnbbtc@ticker/wavesbtc@ticker/stratbtc@ticker/ethup@ticker/yfiup@ticker/xrpup@ticker'

def on_message(ws, message):
    data = json.loads(message)
    timestamp = datetime.utcfromtimestamp(data['E']/1000).strftime('%Y-%m-%d %H:%M:%S')
    symbol = data['s']
    open = data['o']
    high = data['h']
    low = data['l']
    close = data['c']
    volume = data['v']
    trade = data['n'] #No. of Trades
    tick = f'tick :timestamp: {timestamp} :symbol: {symbol} :close_price: {close} :volume: {volume}:open_price: {open}:high_price: {high}:low_price: {low}:trade_qyt: {trade}'
    events.put(tick)
    # print("This is this: ", events.get(True))

def on_close(ws, message):
    print("bang")

def get_queue():
    while 1:
        print(events.get(True))

def run():
    websocket.enableTrace(False)
    ws = websocket.WebSocketApp(
        socket, on_message=on_message, on_close=on_close)
    wst = threading.Thread(target=ws.run_forever)
    wst.daemon = True
    wst.start()
    while not ws.sock.connected: #and conn_timeout:
        print("this")
        time.sleep(1)
    while ws.sock is not None:
        print("that")
        time.sleep(10)
    
def main():
    get_queue_th = threading.Thread(target=get_queue)
    get_queue_th.daemon = True
    get_queue_th.start()
    run()
    



if __name__ == "__main__":
    main()

I want to take the Object-Oriented approach, but I can not spot the bug. Any help would be greatly appreciated.

Thanks!



from Unable to get Queue value with Python Class Structure / Transform functions to class structure

No comments:

Post a Comment