0

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

1
  • 1
    You have to use something called animated plot, i will try to refer you to a page matplotlib.org/3.1.1/gallery/animation/simple_anim.html here is a simple example. I highly recommend you to watch a youtube video because it isnt an easy answer. Commented Dec 4, 2020 at 12:33

1 Answer 1

1

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

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

It's gif. I want the line graph in the matplotlib window
I made it a GIF to show it working, but you can show it with plt.show(). The code has been modified.
I tried and it worked. Thank You. But... it's just a straight line. I wanted this to be like this : i.imgur.com/of4u1m8.png in real time. I hope you understand me @r-beginners
As it is here officially : binance.com/en/trade/ETH_USDT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.