Reputation: 35
I am using an API which returns a dictionary containing a key whose value keeps changing every second.
This is the API call link which returns the data in this form.
{"symbol":"ETHUSDT","price":"588.15000000"}
Here.. the key "price" keeps changing its value every second.
This is my Python scrips which appends this value in a list.
import requests
import matplotlib.pyplot as plt
url = "https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT"
def get_latest_crypto_price():
r = requests.get(url)
response_dict = r.json()
return float(response_dict['price'])
def main():
last_price = 10
eth_price =[]
while True:
price = get_latest_crypto_price()
if price != last_price:
eth_price.append(price)
fig, ax = plt.subplots()
ax.plot(eth_price)
plt.show()
last_price = price
main()
My Question?
My code does plot the line but every time I have to close the Plot Window and it reopens again showing the new appended value. I know this is happening because my loop starts again after appending each value.
I am struck as to how to plot this in real time. Kindly help me in correcting my script.
Thank You
Upvotes: 0
Views: 173
Reputation: 35155
Animation sets up the basic shape of the graph you want to animate, and then displays it by repeatedly assigning it to the line graph with the animation function. This example shows adding a value to the y-axis and getting a value in a slice and displaying it. 30 frames at 1 second intervals are drawn. You can understand the animation if you check the behavior of the animation while modifying the parameters. I'm in a jupyterlab environment so I have several libraries in place. I have also introduced another library for creating GIF images.
import requests
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML # for jupyter lab
from matplotlib.animation import PillowWriter # Create GIF animation
url = "https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT"
eth_price =[]
last_price = 10
x = np.arange(31)
fig = plt.figure()
ax = plt.axes(xlim=(0, 31), ylim=(580, 600))
line, = ax.plot([], [], 'r-', marker='.', lw=2)
def ani_plot(i):
r = requests.get(url)
response_dict = r.json()
price = float(response_dict['price'])
if price != last_price:
eth_price.append(price)
line.set_data(x[:i], eth_price[:i])
# print(price)
return line,
anim = FuncAnimation(fig, ani_plot, frames=31, interval=1000, repeat=False)
plt.show()
anim.save('realtime_plot_ani.gif', writer='pillow')
# jupyter lab
#plt.close()
#HTML(anim.to_html5_video())
Upvotes: 1