Skip to content

quantpylib.wrappers.binance

Binance

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, standardize_schema=1, **kwargs) async

Subscribe to account fill updates.

Parameters:

Name Type Description Default
handler coroutine

A coroutine handler for fill events.

required
standardize_schema int

0 preserves the previous raw ORDER_TRADE_UPDATE passthrough; 1 emits normalized Fill objects for nonzero trade fills. Defaults to 1.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

account_fill_unsubscribe(**kwargs) async

Unsubscribe from account fill updates.

account_fills_get(start_ms=None, end_ms=None, **kwargs) async

Retrieve normalized fills over the half-open range [start_ms, end_ms).

bba_subscribe(ticker, handler, standardize_schema=1, **kwargs) async

Subscribe to best bid/ask updates.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
handler coroutine

Callback invoked for each best bid/ask update.

required
standardize_schema int

Payload schema mode. 0 passes the raw provider payload, 1 emits the legacy {ts,bid,ask,bid_sz,ask_sz} dictionary, and 2 emits quantpylib.standards.models.BBAUpdate. Defaults to 1.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

bba_subscribe_batch(tickers, handlers, standardize_schema=1, **kwargs) async

Subscribe to multiple best bid/ask streams as one websocket batch.

Parameters:

Name Type Description Default
tickers list[str]

Ticker symbols.

required
handlers coroutine or list

Shared callback or one callback per ticker.

required
standardize_schema int

Payload schema mode. 0 passes raw provider payloads, 1 emits legacy {ts,bid,ask,bid_sz,ask_sz} dictionaries, and 2 emits quantpylib.standards.models.BBAUpdate objects. Defaults to 1.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

bba_unsubscribe(ticker, **kwargs) async

Unsubscribe from best bid/ask updates.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
**kwargs

Exchange wrapper specific keyword arguments.

{}

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.

{}

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, **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
**kwargs

Exchange wrapper specific keyword arguments.

{}

cancel_wire(ticker, oid=None, cloid=None, **kwargs) async

Build an exchange-native cancel wire.

cleanup() async

Cleans up open sessions with Binance server

contract_specifications(contract_types=('PERPETUAL',), **kwargs) async

Retrieve the contract's trading rules from the exchange.

Parameters:

Name Type Description Default
contract_types tuple

Native exchange contractType strings to retrieve. Defaults to ("PERPETUAL",), preserving USDT-margined perpetual-only behavior. Pass ("PERPETUAL","TRADIFI_PERPETUAL") to also include TradFi perpetuals (e.g. CRWDUSDT, SOXLUSDT, XAUUSDT). A falsy value (None/()) disables the filter and returns every trading contract type, mirroring the bybit wrapper convention.

('PERPETUAL',)
**kwargs

Additional keyword arguments.

{}

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

get_all_marks(**kwargs) async

Retrieve the mark-price for all available tickers.

Parameters:

Name Type Description Default
**kwargs

Additional keyword arguments.

{}

Returns:

Name Type Description
dict

A dictionary with contract symbols as keys and their corresponding mark-prices (Decimal) as values.

get_all_mids(ticker=None, **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
**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_funding_info(ticker=None, contract_types=('PERPETUAL',), **kwargs) async

Retrieve the funding rate for a specific ticker or all active tickers.

Parameters:

Name Type Description Default
ticker str

The symbol of the specific contract for which to retrieve the funding rate.

None
contract_types tuple

Native exchange contractType strings to include.

('PERPETUAL',)

get_spot_price(ticker=None, **kwargs) async

Retrieve spot ticker prices.

Parameters:

Name Type Description Default
ticker str

The spot symbol to retrieve. If omitted, prices for all spot symbols are returned.

None

Returns:

Name Type Description
Decimal

The spot price for ticker when specified.

dict

A mapping of symbol to Decimal spot price when ticker is omitted.

get_spot_symbols(**kwargs) async

Retrieve currently trading Binance spot symbols.

Returns:

Name Type Description
list

Active spot symbols with status TRADING.

get_trade_bars(ticker, start, end, granularity, granularity_multiplier, kline_close=False, **kwargs) async

Retrieve trade bars data.

Parameters:

Name Type Description Default
ticker str

Ticker symbol for the asset.

required
start datetime

Start datetime for the data retrieval.

required
end datetime

End datetime for the data retrieval.

required
granularity Period

Granularity of the data.

required
granularity_multiplier int

Multiplier for the granularity.

required
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description
DataFrame

DataFrame containing the trade bars data.

init_client() async

Initializes the exchange client.

l2_book_get(ticker, depth=1000, standardize_schema=1, **kwargs) async

Retrieve an L2 order-book snapshot.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
depth int

Binance USD-M order-book depth limit. Defaults to 1000.

1000
standardize_schema int

Payload schema mode. 0 returns the raw provider payload, 1 returns the legacy {ts,b,a} dictionary, and 2 returns quantpylib.standards.models.BookUpdate. Defaults to 1.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

Returns:

Type Description
dict | BookUpdate

Raw provider payload, legacy normalized dictionary, or quantpylib.standards.models.BookUpdate depending on standardize_schema.

l2_book_mirror(ticker, depth=20, stream_depth=20, buffer_size=100, as_dict=True, on_update=None, refresh_sec=300, speed_ms=500, apply_shadow_depth=False, **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 order book data to retrieve. Defaults to 20.

20
stream_depth int

Binance USD-M depth stream selector. Defaults to 20.

20
buffer_size int

The size of the buffer to store order book history. Defaults to 100.

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 for the order book updates. Defaults to None.

None
refresh_sec int

The time interval in seconds to refresh the order book snapshot. Defaults to 300.

300
speed_ms int

Binance USD-M stream cadence. Allowed values are [None,100,500]. Defaults to 500.

500
apply_shadow_depth bool

Whether to maintain additional book levels inside the LOB. Defaults to False.

False
**kwargs

Exchange wrapper specific keyword arguments.

{}

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

Return the local L2 order-book mirror created by l2_book_mirror().

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
as_dict bool

If True, return the mirror as a {ts,b,a} dictionary; otherwise return the local LOB object. Defaults to True.

True
**kwargs

Exchange wrapper specific keyword arguments.

{}

Returns:

Type Description
dict | LOB

Current mirrored order-book state.

l2_book_subscribe(ticker, handler, depth=None, speed_ms=None, standardize_schema=1, **kwargs) async

Subscribe to L2 order-book updates.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
handler coroutine

Callback invoked for each order-book update.

required
depth Optional[int]

Binance USD-M depth stream selector. None uses the diff-depth stream; values 5, 10, or 20 request partial-depth streams.

None
speed_ms Optional[int]

Binance USD-M stream cadence. Allowed values are [None,100,500].

None
standardize_schema (int, 1)

Payload schema mode. 0 passes the raw provider payload, 1 emits the legacy {ts,b,a} dictionary, and 2 emits quantpylib.standards.models.BookUpdate.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

l2_book_subscribe_batch(tickers, handlers, depth=None, speed_ms=None, standardize_schema=1, **kwargs) async

Subscribe to multiple L2 order-book streams as one websocket batch.

Parameters:

Name Type Description Default
tickers list[str]

Ticker symbols.

required
handlers coroutine or list

Shared callback or one callback per ticker.

required
depth Optional[int]

Binance USD-M depth stream selector. None uses the diff-depth stream; values 5, 10, or 20 request partial-depth streams.

None
speed_ms Optional[int]

Binance USD-M stream cadence. Allowed values are [None,100,500].

None
standardize_schema (int, 1)

Payload schema mode. 0 passes raw provider payloads, 1 emits legacy {ts,b,a} dictionaries, and 2 emits quantpylib.standards.models.BookUpdate objects.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

l2_book_subscriptions(**kwargs)

Return active L2 order-book subscription identifiers.

Returns:

Type Description
set

Open wrapper-managed L2 subscription identifiers.

l2_book_unsubscribe(ticker, depth=None, speed_ms=None, **kwargs) async

Unsubscribe from L2 order-book updates.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
depth Optional[int]

Binance USD-M depth stream selector used for the subscription.

None
speed_ms Optional[int]

Binance USD-M stream cadence used for the subscription.

None
**kwargs

Exchange wrapper specific keyword arguments.

{}

limit_order(ticker, amount, price=None, price_rule=None, tif=markets.TIME_IN_FORCE_GTC, reduce_only=False, cloid=None, round_price=False, round_size=False, **kwargs) async

Submit limit order. If both price and price_rule are specified, then the price_rule is prioritized.

Parameters:

Name Type Description Default
ticker str

The coin symbol.

required
amount float or Decimal

The signed quantity of contracts to long/short.

required
price Optional[float]

The price at which to execute the order. Defaults to None.

None
price_rule Optional[str]

Exchange-side rule for deriving the order price. Defaults to None. Allowed values are [OPPONENT,OPPONENT_5,OPPONENT_10,OPPONENT_20,QUEUE,QUEUE_5,QUEUE_10]

None
tif str

The time in force. Defaults to "GTC". Allowed values are [GTC,IOC,FOK,GTX,GTD].

TIME_IN_FORCE_GTC
reduce_only bool

Whether the order should reduce an existing position only. 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 amount to a valid order specification. Defaults to False.

False

Returns:

Name Type Description
Any

The result of the order placement.

market_order(ticker, amount, reduce_only=False, cloid=None, **kwargs) async

Submit market order.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
amount float or Decimal

The positive/negative quantity of contracts to long/short.

required
reduce_only bool

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

False
cloid str

Client order ID for custom tracking. Defaults to None.

None
**kwargs

Exchange wrapper specific keyword arguments.

{}

Returns:

Name Type Description
Any

The result of the order placement.

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

Get order details using order ID.

Parameters:

Name Type Description Default
ticker str

The trading instrument ticker.

required
oid (str, int)

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 order updates.

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 updates.

Parameters:

Name Type Description Default
**kwargs

Exchange wrapper specific keyword arguments.

{}

orders_get(**kwargs) async

Get all open order details.

Parameters:

Name Type Description Default
**kwargs

Exchange wrapper specific keyword arguments.

{}

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

Get all open position details.

Parameters:

Name Type Description Default
**kwargs

Exchange wrapper specific keyword arguments.

required

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.

{}

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

Generate a random string (cloid) consisting of hexadecimal characters.

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 ''.

''
**kwargs

Additional keyword arguments.

{}

Returns:

Name Type Description
str

A random hexadecimal string with a total length of 32 characters, including the optional 'start' and 'end' strings.

trades_subscribe(ticker, handler, standardize_schema=1, **kwargs) async

Subscribe to public trade updates.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
handler coroutine

Callback invoked for each trade update.

required
standardize_schema (int, 1)

Payload schema mode. 0 passes the raw provider payload, 1 emits the legacy normalized (ts,price,sz,dir) tuple, and 2 emits quantpylib.standards.models.TradeUpdate.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

trades_subscribe_batch(tickers, handlers, standardize_schema=1, **kwargs) async

Subscribe to multiple public trade streams as one websocket batch.

Parameters:

Name Type Description Default
tickers list[str]

Ticker symbols.

required
handlers coroutine or list

Shared callback or one callback per ticker.

required
standardize_schema (int, 1)

Payload schema mode. 0 passes raw provider payloads, 1 emits legacy normalized (ts,price,sz,dir) tuples, and 2 emits quantpylib.standards.models.TradeUpdate objects.

1
**kwargs

Exchange wrapper specific keyword arguments.

{}

trades_unsubscribe(ticker, **kwargs) async

Unsubscribe from public trade updates.

Parameters:

Name Type Description Default
ticker str

Ticker symbol.

required
**kwargs

Exchange wrapper specific keyword arguments.

{}

BinanceWsManager

Bases: AsyncWsManager