Created
February 1, 2022 11:38
-
-
Save Ugbot/4271eb026184863ce1858530aad2585d to your computer and use it in GitHub Desktop.
Realtime plotting with SSE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| from pprint import pprint | |
| from sseclient import SSEClient | |
| from urllib.parse import urlencode, quote_plus | |
| from pydantic import BaseModel | |
| import collections | |
| class coinbaseData(BaseModel): | |
| id : str | |
| timestamp : int | |
| channel : str | |
| data : str | |
| name : str | |
| plt.style.use('ggplot') | |
| def live_plotter(y1_data,line1,pause_time=0.01): | |
| if line1==[]: | |
| plt.ion() | |
| fig = plt.figure(figsize=(13,6)) | |
| ax = fig.add_subplot(111) | |
| line1, = ax.plot(y1_data) | |
| plt.ylabel('Price in Cents') | |
| plt.title("live etherium prices") | |
| plt.show() | |
| line1.set_ydata(y1_data) | |
| if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]: | |
| plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)]) | |
| plt.pause(pause_time) | |
| return line1 | |
| size = 100 | |
| y_vec = collections.deque(np.full(size,250000)) | |
| line1 = [] | |
| chanName = '[product:ably-coindesk/crypto-pricing]eth:usd' | |
| apiKey = 'API-KEY' | |
| params = f'channels={quote_plus(chanName)}&v=1.1&rewind=100&key={apiKey}' | |
| uri = f'https://realtime.ably.io/event-stream?{params}' | |
| price = -1 | |
| timestamp = 1 | |
| messages = SSEClient(uri) | |
| for msg in messages: | |
| try: | |
| data = coinbaseData.parse_raw(msg.data) | |
| price = int(float(data.data) *100) | |
| timestamp = data.timestamp | |
| except Exception as e: | |
| print (e) | |
| pass | |
| print (price) | |
| if ( price > 1000): | |
| y_vec.popleft() | |
| y_vec.append(price) | |
| line1 = live_plotter(y_vec,line1) | |
| pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment