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()