Skip to content

quantpylib.wrappers.bybit

Bybit

__init__(key='', secret='', key_self_generated=False, **kwargs)

Initializes the Bybit instance.

Parameters:

Name Type Description Default
key str

API key for authentication. Defaults to empty string.

''
secret str

API secret for authentication. Defaults to empty string.

''
key_self_generated bool

Flag to indicate if RSA authentication is used. Defaults to False.

False

account_balance(**kwargs) async

Retrieve balance details of the user, such as equity, margin (total, maintenance) and pnl.

Returns:

Type Description
dict

Balance details.

account_fill_subscribe(handler, **kwargs) async

Subscribe to account fill updates - in Bybit, this just calls the order_updates_subscribe method.

account_fill_unsubscribe(**kwargs) async

Unsubscribe to account fill updates - in Bybit, this just calls the order_updates_unsubscribe method.

account_info() async

Retrieves general account information.

Returns:

Name Type Description
dict

The account information from the exchange.

all_mids_subscribe(handler, **kwargs) async

Not supported by Bybit.

all_mids_unsubscribe(**kwargs) async

Not supported by Bybit.

batch_orders_cancel(category='linear', cancel_wires=[]) async

Cancels multiple orders in a single batch request.

Parameters:

Name Type Description Default
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to 'linear'.

'linear'
cancel_wires list

A list of cancel wire dictionaries to be canceled.

[]

Returns:

Name Type Description
dict

The response from the exchange for the batch order cancellation.

batch_orders_create(category='linear', order_wires=[]) async

Creates multiple orders in a single batch request.

Parameters:

Name Type Description Default
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to 'linear'.

'linear'
order_wires list

A list of order wire dictionaries to be created.

[]

Returns:

Name Type Description
dict

The response from the exchange for the batch order creation.

cancel_open_orders(ticker=None, **kwargs) async

Cancel open orders on the exchange.

Parameters:

Name Type Description Default
ticker str

The coin symbol. Defaults to None, which means cancel all open orders.

None
**kwargs

Additional keyword arguments for further customization.

{}

Returns:

Name Type Description
Any

The result of the cancellation request. Returns None if no open orders are found or no orders are canceled.

cancel_order(ticker, oid=None, cloid=None, submit=True, **kwargs) async

Cancel an order.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
oid int

Order ID to cancel.

None
cloid str

Client Order ID to cancel.

None
submit bool

If True, submits the cancel to the exchange, else returns the cancel order wire. Defaults to True.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

cleanup() async

Cleans up the client sessions.

contract_specifications(include_prelists=False, contract_type='LinearPerpetual', **kwargs) async

Retrieve the contract's trading rules from the exchange.

Parameters:

Name Type Description Default
include_prelists bool

Specifies whether to include prelistings.

False
contract_type str

Type of contracts to retrieve. Defaults to LinearPerpetual.

'LinearPerpetual'
**kwargs

Additional keyword arguments specific to the exchange wrapper.

{}

Returns:

Name Type Description
dict

A dictionary containing contract specifications for each asset with key-values: - SYMBOL_PRICE_PRECISION. - SYMBOL_QUANTITY_PRECISION. - SYMBOL_MIN_NOTIONAL - SYMBOL_BASE_ASSET - SYMBOL_QUOTE_ASSET

funding_history(ticker, category='linear', startTime=None, endTime=None, limit=None) async

Retrieves the funding rate history for a given ticker.

Parameters:

Name Type Description Default
ticker str

The trading ticker symbol (e.g., 'BTCUSDT').

required
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'
startTime int

The start time for the funding history in UNIX timestamp format. Defaults to None.

None
endTime int

The end time for the funding history in UNIX timestamp format. Defaults to None.

None
limit int

The number of records to retrieve. Defaults to None.

None

Returns:

Name Type Description
dict

The funding rate history data from the exchange.

get_all_mids(ticker=None, category='linear', **kwargs) async

Retrieve the mid-price for a specific ticker or all available tickers.

Parameters:

Name Type Description Default
ticker str

The symbol of the specific contract for which to retrieve the mid-price. If not provided, mid-prices for all contracts will be returned. Defaults to None.

None
category str

The category of the contract. Defaults to 'linear'.

'linear'
**kwargs

Additional keyword arguments.

{}

Returns:

Name Type Description
Decimal

The mid-price of the specified ticker if ticker is provided.

dict

A dictionary with contract symbols as keys and their corresponding mid-prices (Decimal) as values if ticker is not provided.

get_lot_precision(ticker)

Retrieves the lot size precision for a specified ticker.

Parameters:

Name Type Description Default
ticker str

The ticker symbol.

required

Returns:

Name Type Description
int

The number of decimal places for lot size precision.

get_order_wire(symbol, amount, orderType, price=None, timeInForce='GTC', reduceOnly=False, orderLinkId=None, **kwargs)

Creates the wire for placing an order.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
amount float

The quantity of the asset to trade.

required
orderType str

The type of order (e.g., 'Limit', 'Market').

required
price float

The price for the order. Defaults to None.

None
timeInForce str

The time-in-force for the order (e.g., 'GTC', 'FOK'). Defaults to "GTC".

'GTC'
reduceOnly bool

Whether the order is reduce-only. Defaults to False.

False
orderLinkId str

The client order ID. Defaults to None.

None
**kwargs

Additional keyword arguments for the order.

{}

Returns:

Name Type Description
dict

The order wire data.

get_perps_data(in_decimal=True, **kwargs) async

Retrieve perpetuals data.

Returns:

Type Description
dict

A dictionary containing symbol to perp data with the following perp data structure:

  • "baseAsset" str : The base asset symbol.
  • "fr" float : Funding rate. #
  • "frint" int, Funding rate interval.
  • "markPrice" float, The mark price. #
  • "min_notional" float, The minimum notional value.
  • "next_funding" int, Unix timestamp of the next funding, milliseconds. #
  • "pricePrecision" Decimal, The price precision.
  • "quantityPrecision" Decimal, The quantity precision.
  • "quoteAsset" str, The quote asset symbol.
  • "stepSize" Decimal, The step size.
  • "symbol" str, The symbol.
  • "timestamp" int, Unix timestamp of the data retrieval, milliseconds.
  • "exchange" str The exchange code , "bybit"

get_price_precision(ticker)

Retrieves the price precision for a specified ticker.

Parameters:

Name Type Description Default
ticker str

The ticker symbol.

required

Returns:

Name Type Description
int

The number of decimal places for price precision.

index_kline(symbol, start=None, end=None, limit=None, interval='D', category='linear') async

Retrieves index price kline data for a given symbol.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
start int

The start time for the kline data in UNIX timestamp format. Defaults to None.

None
end int

The end time for the kline data in UNIX timestamp format. Defaults to None.

None
limit int

The number of klines to retrieve. Defaults to None.

None
interval str

The interval for the kline data (e.g., '1m', '1h'). Defaults to "D".

'D'
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'

Returns:

Name Type Description
dict

The index price kline data from the exchange.

init_client() async

Initializes the client by fetching contract specifications and setting up precision mappings.

instruments_info(category='linear', status='Trading', basecoin=None, symbol=None, limit=1000, cursor='') async

Retrieves information about trading instruments.

Parameters:

Name Type Description Default
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'
status str

The status of the instrument (e.g., 'Trading'). Defaults to "Trading".

'Trading'
basecoin str

The base coin (e.g., 'BTC'). Defaults to None.

None
symbol str

The trading symbol (e.g., 'BTCUSDT'). Defaults to None.

None
limit int

The maximum number of instruments to retrieve. Defaults to 1000.

1000
cursor str

The cursor for pagination. Defaults to "".

''

Returns:

Name Type Description
dict

Information about trading instruments from the exchange.

kline(symbol, start=None, end=None, limit=None, interval='D', category='linear') async

Retrieves kline (candlestick) data for a given symbol.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
start int

The start time for the kline data in UNIX timestamp format. Defaults to None.

None
end int

The end time for the kline data in UNIX timestamp format. Defaults to None.

None
limit int

The number of klines to retrieve. Defaults to None.

None
interval str

The interval for the kline data (e.g., 'D', 'M'). Defaults to "D".

'D'
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'

Returns:

Name Type Description
dict

The kline data from the exchange.

l2_book_get(ticker, depth=25, category='linear', standardize_schema=True, **kwargs) async

Retrieve the L2 Order Book for a specific ticker.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
depth int

Depth of the order book. Defaults to 25.

25
category str

Category of the contract. Defaults to 'linear'.

'linear'
standardize_schema bool

If True, returns the order book in a standardized schema. Defaults to True.

True
**kwargs

Additional keyword arguments specific to the exchange wrapper.

{}

l2_book_mirror(ticker, depth=50, stream_depth=50, buffer_size=100, as_dict=True, on_update=None, **kwargs) async

Keep a live, internal L2 Order Book representation using a l2-book subscription.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
depth int

Depth of the order-book representation, if as_dict is False

50
stream_depth int

Depth of the l2 stream used to maintain internal order book.

50
buffer_size int

Size of the order-book buffer, if as_dict is False

100
as_dict (bool, True)

If True, pass state as dictionary, otherwise as a quantpylib.hft.lob.LOB object into handlers.

True
on_update coroutine

A coroutine handler when order book state is updated.

None
**kwargs

Exchange wrapper specific keyword arguments.

{}

l2_book_peek(ticker, as_dict=True, **kwargs)

Retrieve the mirrored, local internal L2 Order Book representation.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
as_dict (bool, True)

If True, return state as dictionary, otherwise as a quantpylib.hft.lob.LOB object.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

l2_book_subscribe(ticker, handler, depth=200, standardize_schema=True, **kwargs) async

Subscribe to L2 Order Book stream.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
handler coroutine

A coroutine handler for the message received.

required
depth int

Depth of the l2 stream updates. Defaults to 200.

200
standardize_schema (bool, True)

Processes the incoming message to {ts,b,a}

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

l2_book_subscriptions(**kwargs)

Retrieve the list of open l2 book subscriptions.

l2_book_unsubscribe(ticker, depth=200, **kwargs) async

Unsubscribe from L2 Order Book.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
depth int

Depth of the l2 stream update subscribed. Defaults to 200.

200
**kwargs

Exchange wrapper specific keyword arguments.

{}

limit_order(ticker, amount, price, tif='GTC', reduce_only=False, cloid=None, round_price=False, round_size=False, category='linear', submit=True, **kwargs) async

Submit a limit order.

Parameters:

Name Type Description Default
ticker str

The coin symbol.

required
amount float or Decimal

The signed quantity of contracts to long or short.

required
price float

The price at which to execute the order.

required
tif str

The time in force for the order. Defaults to "Gtc". Allowed values are: - "Gtc" (Good 'til canceled) - "Alo" (Add liquidity only) - "Ioc" (Immediate or cancel)

'GTC'
reduce_only bool

Whether the order should only reduce an existing position. Defaults to False.

False
cloid str

Client order ID for order tracking. Defaults to None.

None
round_price bool

Whether to round the price to a valid order specification. Defaults to False.

False
round_size bool

Whether to round the price to a valid order specification. Defaults to False.

False
category str

Contract categroy. Defaults to linear.

'linear'
submit bool

If True, submits the order to the exchange, else returns the order wire. Defaults to True.

True
**kwargs

Additional keyword arguments for order customization.

{}

Returns:

Name Type Description
Any

The result of the order placement.

mark_kline(symbol, start=None, end=None, limit=None, interval='D', category='linear') async

Retrieves mark price kline data for a given symbol.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
start int

The start time for the kline data in UNIX timestamp format. Defaults to None.

None
end int

The end time for the kline data in UNIX timestamp format. Defaults to None.

None
limit int

The number of klines to retrieve. Defaults to None.

None
interval str

The interval for the kline data (e.g., '1m', '1h'). Defaults to "D".

'D'
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'

Returns:

Name Type Description
dict

The mark price kline data from the exchange.

market_order(ticker, amount, tif='GTC', reduce_only=False, cloid=None, round_size=False, category='linear', submit=True, **kwargs) async

Submit a market order.

Parameters:

Name Type Description Default
ticker str

The ticker symbol for the asset.

required
amount float or Decimal

The signed quantity of contracts to long or short.

required
tif str

Time in force. Defaults to GTC. Valid values are GTC, IOC, FOK.

'GTC'
reduce_only bool

Whether the order should only reduce an existing position. Defaults to False.

False
cloid str

Client order ID for custom tracking. Defaults to None.

None
round_size bool

Whether to round the price to a valid order specification. Defaults to False.

False
category str

Contract categroy. Defaults to linear.

'linear'
submit bool

If True, submits the order to the exchange, else returns the order wire. Defaults to True.

True
**kwargs

Additional keyword arguments specific to the exchange wrapper.

{}

Returns:

Name Type Description
Any

The result of the order placement. This typically includes a confirmation of the placed order, or an error message if the order could not be placed.

order_cancel(symbol, orderId=None, orderLinkId=None, category='linear', orderFilter=None, submit=True) async

Cancels an existing order.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
orderId str

The order ID to cancel. Defaults to None.

None
orderLinkId str

The client order ID to cancel. Defaults to None.

None
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'
orderFilter str

The order filter to apply. Defaults to None.

None
submit bool

If True, submits the cancellation to the exchange. Defaults to True.

True

Returns:

Name Type Description
dict

The response from the exchange if submit is True, otherwise the cancellation payload.

order_create(symbol, amount, orderType, price=None, timeInForce='GTC', reduceOnly=False, category='linear', orderLinkId=None, submit=True, **kwargs) async

Creates a new order.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
amount float

The quantity of the asset to trade.

required
orderType str

The type of order (e.g., 'Limit', 'Market').

required
price float

The price for the order. Defaults to None.

None
timeInForce str

The time-in-force for the order (e.g., 'GTC', 'FOK'). Defaults to "GTC".

'GTC'
reduceOnly bool

Whether the order is reduce-only. Defaults to False.

False
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to 'linear'.

'linear'
orderLinkId str

The client order ID. Defaults to None.

None
submit bool

If True, submits the order to the exchange, else returns the order wire. Defaults to True.

True
**kwargs

Additional keyword arguments for the order.

{}

Returns:

Name Type Description
dict

The response from the exchange if submit is True, otherwise the order wire.

order_history(category='linear', symbol=None, **kwargs) async

Retrieves the order history for a given symbol.

Parameters:

Name Type Description Default
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to 'linear'.

'linear'
symbol str

The trading symbol (e.g., 'BTCUSDT'). Defaults to None.

None
**kwargs

Additional keyword arguments for the request.

{}

Returns:

Name Type Description
dict

The order history from the exchange.

order_query(oid=None, cloid=None, as_dict=True, **kwargs) async

Get order details using order ID.

Parameters:

Name Type Description Default
oid str

Order ID in exchange

None
cloid str

Client Order ID

None
as_dict bool

If True, return the order details as a dictionary. Defaults to True.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

order_updates_subscribe(handler, **kwargs) async

Subscribe to creation, updation and deletion of account's orders.

Parameters:

Name Type Description Default
handler coroutine

A coroutine handler for the message received.

required
**kwargs

Exchange wrapper specific keyword arguments.

{}

order_updates_unsubscribe(**kwargs) async

Unsubscribe from order events.

orderbook_depth(symbol, category='linear', limit=25) async

Retrieves the order book depth for a given symbol.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'
limit int

The number of order book levels to retrieve. Defaults to None.

25

Returns:

Name Type Description
dict

The order book depth data from the exchange.

orders_cancel_all(category='linear', symbol=None, **kwargs) async

Cancels all open orders for a given symbol.

Parameters:

Name Type Description Default
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to 'linear'.

'linear'
symbol str

The trading symbol (e.g., 'BTCUSDT'). Defaults to None.

None
**kwargs

Additional keyword arguments for the request.

{}

Returns:

Name Type Description
dict

The response from the exchange for the cancellation request.

orders_get(ticker=None, **kwargs) async

Get open order details.

Parameters:

Name Type Description Default
ticker optional

Retrieve orders for ticker only.

None
**kwargs

Additional keyword arguments specific to the exchange wrapper.

{}

Returns:

Name Type Description
dict

A dictionary containing details of the open orders.

orders_get_realtime(category='linear', symbol=None, **kwargs) async

Retrieves real-time information about orders.

Parameters:

Name Type Description Default
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'
symbol str

The trading symbol (e.g., 'BTCUSDT'). Defaults to None.

None
**kwargs

Additional keyword arguments for the request.

{}

Returns:

Name Type Description
dict

The real-time order information from the exchange.

orders_mirror(on_update=None, as_list=True, **kwargs) async

Keeps a local mirror copy of the account open orders.

Parameters:

Name Type Description Default
on_update coroutine

A coroutine handler for orders dictionary on order event.

None
as_list bool

If True, pass state as list, otherwise as quantpylib.standards.Orders object into handlers.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

orders_peek(as_dict=True, **kwargs)

Retrieves the local mirror copy of the account open orders.

Parameters:

Name Type Description Default
as_dict bool

If True, pass state as dictionary, otherwise as quantpylib.standards.Orders object.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

positions_get(ticker=None, **kwargs) async

Get open position details.

Parameters:

Name Type Description Default
ticker optional

Retrieve position for ticker only.

None
**kwargs

Additional keyword arguments specific to the exchange wrapper.

{}

Returns:

Name Type Description
dict

A dictionary containing details of the open positions.

positions_info(category='linear', symbol=None, **kwargs) async

Retrieves information about open positions.

Parameters:

Name Type Description Default
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to 'linear'.

'linear'
symbol str

The trading symbol (e.g., 'BTCUSDT'). Defaults to None.

None
**kwargs

Additional keyword arguments for the request.

{}

Returns:

Name Type Description
dict

The position information from the exchange.

positions_mirror(on_update=None, as_dict=True, **kwargs) async

Keeps a local mirror copy of the account open orders.

Parameters:

Name Type Description Default
on_update coroutine

A coroutine handler for positions dictionary on fill.

None
as_dict bool

If True, the method returns positions as a dictionary, otherwise as a quantpylib.standards.Positions object. Defaults to True.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

positions_peek(as_dict=True, **kwargs)

Retrieves the local mirror copy of the account open positions.

Parameters:

Name Type Description Default
as_dict bool

If True, the method returns positions as a dictionary, otherwise as a quantpylib.standards.Positions object. Defaults to True.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

premium_index_kline(symbol, start=None, end=None, limit=None, interval='D', category='linear') async

Retrieves premium index price kline data for a given symbol.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT').

required
start int

The start time for the kline data in UNIX timestamp format. Defaults to None.

None
end int

The end time for the kline data in UNIX timestamp format. Defaults to None.

None
limit int

The number of klines to retrieve. Defaults to None.

None
interval str

The interval for the kline data (e.g., '1m', '1h'). Defaults to "D".

'D'
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'

Returns:

Name Type Description
dict

The premium index price kline data from the exchange.

rand_cloid(start='', end='', **kwargs)

Generates a random client order ID (CLOID).

Parameters:

Name Type Description Default
start str

A string to prepend to the generated random string. Defaults to ''.

''
end str

A string to append to the generated random string. Defaults to ''.

''

Returns:

Name Type Description
str

A randomly generated CLOID.

server_time() async

Retrieves the current server time from the exchange.

Returns:

Name Type Description
dict

The server time data from the exchange.

signed_payload(payload=None, params=None, recv_window=5000)

Signs the payload or query parameters for an authenticated request.

Parameters:

Name Type Description Default
payload dict

The payload to be signed. Defaults to None.

None
params dict

The query parameters to be signed. Defaults to None.

None
recv_window int

The receive window for the request. Defaults to 5000.

5000

Returns:

Name Type Description
tuple

A tuple containing the request headers and the signed payload as a JSON string.

ticker_subscribe(ticker, handler, **kwargs) async

Subscribe to Ticker stream. Args: ticker (str): Ticker symbol. handler (coroutine): A coroutine handler for the message received. **kwargs: Exchange wrapper specific keyword arguments.

tickers_summary(symbol=None, category='linear', baseCoin=None, expDate=None) async

Retrieves a summary of tickers for a given symbol or base coin.

Parameters:

Name Type Description Default
symbol str

The trading symbol (e.g., 'BTCUSDT'). Defaults to None.

None
category str

The category of the market (e.g., 'linear', 'inverse'). Defaults to "linear".

'linear'
baseCoin str

The base coin (e.g., 'BTC'). Defaults to None.

None
expDate str

The expiration date for futures contracts. Defaults to None.

None

Returns:

Name Type Description
dict

The ticker summary data from the exchange.

trades_unsubscribe(ticker, **kwargs) async

Unsubscribe from the trade stream.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
**kwargs

Exchange wrapper specific keyword arguments.

{}

typed_payload(payload)

Converts the payload's parameters to their correct data types.

Parameters:

Name Type Description Default
payload dict

The payload containing the request parameters.

required

Returns:

Name Type Description
dict

The payload with corrected data types.

wallet_balance(accountType='UNIFIED', coin=None) async

Retrieves the wallet balance for the specified account type.

Parameters:

Name Type Description Default
accountType str

The account type (e.g., 'UNIFIED'). Defaults to 'UNIFIED'.

'UNIFIED'
coin str

The specific coin to retrieve the balance for (e.g., 'BTC'). Defaults to None.

None

Returns:

Name Type Description
dict

The wallet balance information from the exchange.

generate_signature(is_rsa, secret, param_str)

Generates a cryptographic signature using either HMAC or RSA based on the provided parameters.

Parameters:

Name Type Description Default
is_rsa bool

If True, uses RSA for signature generation. If False, uses HMAC for signature generation.

required
secret str

The secret key used for generating the signature. For HMAC, this is a shared secret key. For RSA, this is the private RSA key in PEM format.

required
param_str str

The string of parameters to be signed.

required

Returns:

Name Type Description
str

The generated signature in hexadecimal format (for HMAC) or Base64-encoded string (for RSA).