Skip to content

Issue with my python class structure #4623

@NPattanaik1

Description

@NPattanaik1

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 fg() 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 fg(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.fg, daemon=True)
    thread.start()
    stream.run()
    `

Using the Object-Oriented approach (given above), my Queue ends up having null values. 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 fg():
    while 1:
        print(events.get(True))

def fgh():
    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 asd():
    fg_th = threading.Thread(target=fg)
    fg_th.daemon = True
    fg_th.start()
    fgh()
    



if __name__ == "__main__":
    asd()

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

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions