1

I try to plot binance marktet live data in a very simple way. The code retrieves the data but depending on where I place the line of code with the ws variable declaration - the code either prints the market data but there's no plot shwoing up - or - the plot window shows up but stays empty and no market data is printed. If I close the plot window the market data will be retrieved and printed
What am I doing wrong?

import websocket, json, pprint
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

SOCKET = "wss://stream.binance.com:9443/ws/ethusdt@kline_1m"

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

time = 0
close = 0


def on_open(ws):
    print('opened connection')

def on_close(ws):
    print('closed connection')

def on_message(ws, message):

    json_message = json.loads(message)
    
    global time
    global close
    
    time = json_message['k']['T']
    
    pprint.pprint(json_message)

    close = json_message['k']['c']
    
  
    is_bar_closed = json_message['k']['x']
    
    if is_bar_closed:
        print("bar closed at {}".format(close))


def animate(i):
    
    x_vals.append(time)
    y_vals.append(close)

    plt.cla()
    plt.plot(x_vals, y_vals)


ani = FuncAnimation(plt.gcf(), animate, interval = 200)

plt.tight_layout()
plt.show()

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()
stanvooz
  • 522
  • 3
  • 19

1 Answers1

0

Both plt.show() and ws.run_forever() block the execution of the program. Depending on which of these instructions is executed before, the code either plots an empty image (and the execution stops until you close the plot window) or it starts getting data from the socket but the plot instructions are never reached.

In this example, to avoid the program to stop at plt.show() you could use plt.show(block=False) as recommended here.

frblazquez
  • 115
  • 1
  • 10