CCXT how to refresh prices automatically?

3.3k Views Asked by At

when querying exchange APIs, to get the latest price do I simply keep calling my fetchPrice() method every minute or so? I can get the price once, but is the proper way to update using CCXT to simply keep on fetching? The use case is for a simple market scanner

1

There are 1 best solutions below

0
On

It would have been nice to have some of your code to help you solve this question. Anyway you need to use asyncio event loops.

There are many tutorials online on how to use asyncio but I found this one particularly helpful when I started out.

Here is the code below to get the bid / ask every second on deribit exchange but you can reflace that with any exchange that is supported by ccxt and it will work the same way:

import asyncio
import ccxt

async def cctx_prices():
    deribit = ccxt.deribit()
    while True:
        ticker = deribit.fetch_ticker('BTC-PERPETUAL')
        print(ticker)
        
        bid = ticker['bid']
        ask = ticker['ask']
        print(f"{bid} / {ask}")
        
        # pause asyncio for 1 second
        await asyncio.sleep(1) 

loop = asyncio.get_event_loop()
asyncio.ensure_future(cctx_prices())
loop.run_forever()