question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Bybit - Ratelimiting on spot - create_order and cancel_order

See original GitHub issue

When trying to create and cancel more than 20 orders asynchronously with bybit (spot) in Python, I get a 403 error for some orders (which I assume is due to rate limits). Below you can find my example code and some example output. I don’t have this when running the same code for another exchange like Kucoin.

  • OS: MacOS Monterey (M1 chip)
  • Programming Language version: Python 3.9.10
  • CCXT version: 1.84.42
import asyncio
from typing import Dict, Type
import ccxt.async_support as ccxt


async def create_o(exchange, symbol, price, volume):
    try:
        o = await exchange.create_order(symbol, 'limit', 'buy', volume, price)
        print(f"created order {o['id']}")
    except ccxt.ExchangeError as e:
        print(f"Could not create order: {e}")
        o = {}
    return o

async def cancel_o(exchange, id, symbol):
    try:
        await exchange.cancel_order(id, symbol)
    except ccxt.ExchangeError as e:
        print(f"Could not cancel order {id}: {e}")
    else:
        print(f"cancelled order {id}")

async def main():
    exchange_name = "bybit"
    credentials = {"apiKey":"public_key", "secret":"private_key", "password":"pswd", "enableRateLimit":True}
    exchange_type: Type[ccxt.Exchange] = getattr(ccxt, exchange_name)
    exchange = exchange_type(credentials)
    exchange.options["defaultType"] = "spot"
    # exchange.rateLimit *= 10
    # exchange.verbose = True
    print("Rate limit: ", exchange.rateLimit)
    symbol = "BTC/USDT"
    limit = 50
    ob = await exchange.fetch_order_book(symbol)
    low_buy_price = ob['asks'][0][0] * .5
    loops = [
        create_o(exchange, symbol, low_buy_price, 0.00016) for _ in range(0, limit)
    ]
    orders = await asyncio.gather(*loops)
    open_orders = await exchange.fetch_open_orders(symbol, limit=500)
    cancel_loops = [
        cancel_o(exchange, order["id"], symbol) for order in open_orders
    ]
    await asyncio.gather(*cancel_loops)
    open_orders = await exchange.fetch_open_orders(symbol)
    print("start cancelling remaining: ")
    for remaining_order in open_orders:
        await cancel_o(exchange, remaining_order["id"], symbol)

    await exchange.close()



if __name__ == "__main__":
    asyncio.run(main())

Almost all orders succeeded except for one / two and also for cancelling the orders! The following verbose output contains a successful and failed order creating.

fetch Request: bybit POST https://api.bybit.com/spot/v1/order RequestHeaders: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept-Encoding': 'gzip, deflate'} RequestBody: symbol=BTCUSDT&side=Buy&type=LIMIT&timeInForce=GTC&qty=0.00016&price=15788.77&agentSource=CCXT&api_key=&recv_window=5000&timestamp=1654068951916&sign=

fetch Response: bybit POST https://api.bybit.com/spot/v1/order 200 ResponseHeaders: {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '351', 'Server': 'T-GATEWAY', 'Expires': 'Wed, 01 Jun 2022 07:35:51 GMT', 'Cache-Control': 'max-age=0, no-cache, no-store', 'Pragma': 'no-cache', 'Date': 'Wed, 01 Jun 2022 07:35:51 GMT', 'Connection': 'keep-alive'} ResponseBody: {"ret_code":0,"ret_msg":"","ext_code":null,"ext_info":null,"result":{"accountId":"23357420","symbol":"BTCUSDT","symbolName":"BTCUSDT","orderLinkId":"1654068951902541","orderId":"1168809515032897024","transactTime":"1654068951907","price":"15788.77","origQty":"0.00016","executedQty":"0","status":"NEW","timeInForce":"GTC","type":"LIMIT","side":"BUY"}}
created order 1168809515032897024

fetch Request: bybit POST https://api.bybit.com/spot/v1/order RequestHeaders: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept-Encoding': 'gzip, deflate'} RequestBody: symbol=BTCUSDT&side=Buy&type=LIMIT&timeInForce=GTC&qty=0.00016&price=15788.77&agentSource=CCXT&api_key=&recv_window=5000&timestamp=1654068951966&sign=

fetch Response: bybit POST https://api.bybit.com/spot/v1/order 403 ResponseHeaders: {'Content-Length': '234', 'Server': 'T-GATEWAY', 'Expires': 'Wed, 01 Jun 2022 07:35:52 GMT', 'Cache-Control': 'max-age=0, no-cache, no-store', 'Pragma': 'no-cache', 'Date': 'Wed, 01 Jun 2022 07:35:52 GMT', 'Connection': 'close'} ResponseBody: {"now":"1654068951952","message":"Access too fast","expression":"OPEN-UI-23357419-/spot/v1/order-post","limit":20,"rule":"OPEN-UI-any-any-any-20","code":"ACCESS_DENIED","req":"OPEN-REQ-23357419-/spot/v1/order-post-1","frequency":"21"}
Could not create order: bybit {"now":"1654068951952","message":"Access too fast","expression":"OPEN-UI-23357419-/spot/v1/order-post","limit":20,"rule":"OPEN-UI-any-any-any-20","code":"ACCESS_DENIED","req":"OPEN-REQ-23357419-/spot/v1/order-post-1","frequency":"21"}```

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
kroitorcommented, Jun 1, 2022

Thanks for reporting! This is a known issue, we are in the process of investigating and fixing it. Will post more updates here when it’s done.

1reaction
nathan-kaironcommented, Aug 26, 2022

@ttodua I checked again and the problem seems to be resolved indeed. Thank you for testing!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Market , Limit and Conditional Order - Bybit Official Help
Bybit provides three different order types, Limit orders/market orders/conditional orders to meet the trading needs of traders.
Read more >
Group And Resources – Bybit API Docs - GitHub Pages
Market price: A traditional market price order which will be filled at the best available price. price is not required for this type...
Read more >
API Keys : Bybit - Automated Trading at Alertatron
When this alert is triggered, your bot will place a limit order on the BTCUSD Perpetual market to buy $10 worth of contracts....
Read more >
Order entry for Bybit - Quantower Help
Order parameters - type, TIF, price, algorithmic settings · GTC (Good Until Cancelled) - Orders will work until they are cancelled by the...
Read more >
BYBIT - HOW TO PLACE CONDITIONAL ORDERS - YouTube
In this Bybit tutorial I show you how to place conditional orders. Conditional orders can be useful for break out trade ideas and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found