Asynchronous requests with ccxt python library on Bybit

462 Views Asked by At

getting 403 error from Bybit on asynchronous ccxt request

tried without async - everything works

import ccxt.async_support as ccxt
import asyncio

async def main():
    exchange = ccxt.bybit()

    await exchange.load_markets()

    symbol = 'BTC/USDT'

    ticker = await exchange.fetch_ticker(symbol)

    print(f'Стоимость {symbol}: {ticker["last"]}')

asyncio.run(main())

I get the following:

https://api.bybit.com/v5/market/instruments-info?category=spot Request blocked. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.

2

There are 2 best solutions below

1
Abdel On

If the code works without using the async keyword but encounters issues when you switch to an asynchronous approach, it's likely related to the way you're handling asynchronous operations. Asynchronous programming introduces additional complexities that can impact how your code interacts with external services like APIs.

Here are few tips to consider:

1. Event Loop Handling: In asynchronous code, you need to manage an event loop to execute asynchronous operations. Make sure you're properly creating and running an event loop using asyncio.run(main()) in your case.

2. Asynchronous Context Managers: If the library you're using (in this case, ccxt.async_support) provides asynchronous context managers or methods, you need to ensure you're using them correctly. Asynchronous context managers are used with the async with syntax.

3. Awaiting Asynchronous Operations: When calling asynchronous methods, you should await them to allow other tasks to execute while waiting for the result. Make sure you're properly using await before asynchronous function calls.

Using your provided example; and respecting the rules above, something like this should be done:

import ccxt.async_support as ccxt
import asyncio

async def main():
    exchange = ccxt.bybit()
    
    async with exchange:
        await exchange.load_markets()

        symbol = 'BTC/USDT'

        ticker = await exchange.fetch_ticker(symbol)

        print(f'Price of {symbol}: {ticker["last"]}')

asyncio.run(main())

If you're still encountering issues, it's possible that the ccxt.async_support library might have its own specific usage patterns that you need to follow. In such cases, referring to the library's documentation or examples could provide more insight into how to use it asynchronously.

Happy coding.

0
GabrieleTurelli On

If you still need help with working with bybit api in an asynchronous context, this script may help you https://github.com/GabrieleTurelli/BybitAsync.

  • Install the connector:

    git clone https://github.com/GabrieleTurelli/BybitAsync.git

  • Initialize the connector:

     from bybit_async import Bybit_requester`
    
     bybit_requester = Bybit_requester(api_key='your_api_key',api_secret='your_api_secret')
    
  • Send public requests:

    import asyncio
    from bybit_async import Bybit_requester
    
    
    async def fetch_market_data():
        data = await bybit_requester.send_public_request(endpoint='/v5/market/kline', 
                                                     params={'category':'linear',
                                                             'symbol': 'BTCUSDT',
                                                             'interval':'D'})
        print(data)
    
    if __name__ == "__main__":
    bybit_requester = Bybit_requester("your_api_key", "your_api_secret")
    asyncio.run(fetch_market_data())
    
    
  • send private requests:

    import asyncio
    from bybit_async import Bybit_requester
    
    
     async def place_order():
         order_data = {
             'category': 'linear',
             'symbol': 'BTCUSDT',
             'orderType': 'Market',
             'side': 'Buy',
             'qty': '0.001',
             'positionIdx': 1
         }
         response = await bybit_requester.send_signed_request(method='POST',
                                                          endpoint='/v5/order/create',
                                                          params=order_data)
     print(response)
    
     if __name__ == "__main__":
         bybit_requester = Bybit_requester("your_api_key", "your_api_secret")
         asyncio.run(place_order())