Market Module

Market functions

Functions:

get_last_price([symbol])

Returns all prices of symbols in a dict or if symbol specified, the float price of symbol.

get_prices_dic(decimal_mode)

Gets all symbols current prices into a dictionary.

get_bulk_klines(symbols, interval[, limit, ...])

Fetch klines for multiple symbols in parallel using panzer bulk_klines.

get_bulk_depth(symbols[, limit, max_workers])

Fetch order book depth for multiple symbols in parallel using panzer bulk_depth.

get_candles_by_time_stamps(symbol, tick_interval)

Calls API for a candles list using one or two timestamps, starting and ending.

get_historical_candles(symbol, ...[, ...])

Retrieve all kline data within the given time range considering the API limit.

parse_candles_to_dataframe(raw_response, ...)

Format a list of lists by changing the indicated time fields to string format.

basic_dataframe(data[, exceptions, actions_col])

Delete all columns except: Open, High, Low, Close, Volume, actions.

convert_to_numeric(data)

Converts to numeric all posible columns for a given Dataframe.

convert_dict_to_numeric(input_dict, ...)

Converts all values in a dictionary to numeric values if possible.

get_last_agg_trades(symbol[, limit])

Get just the last aggregated trades from API.

get_aggregated_trades(symbol[, fromId, ...])

Returns aggregated trades from id to limit or last trades if id not specified.

get_aggregated_trades_by_time(symbol, ...[, ...])

Returns aggregated trades using native startTime/endTime parameters of the API.

get_historical_agg_trades(symbol[, ...])

Returns aggregated trades between timestamps or trade IDs.

parse_agg_trades_to_dataframe(response, ...)

Parses the API response into a pandas dataframe.

get_last_atomic_trades(symbol[, limit])

Returns recent atomic (not aggregated) trades.

get_atomic_trades(symbol[, fromId, limit, ...])

Returns atomic (not aggregated) trades from id to limit or last trades if id not specified.

get_historical_atomic_trades(symbol[, ...])

Returns atomic (not aggregated) trades between timestamps or trade IDs.

parse_atomic_trades_to_dataframe(response, ...)

Parses the API response into a pandas dataframe.

get_order_book(symbol[, limit])

Returns a dictionary with timestamp, bids and asks.

get_orderbook_tickers([symbol, decimal_mode])

Symbol Order Book Ticker

intermediate_conversion(coin, decimal_mode)

Uses an intermediate symbol for conversion.

convert_coin(coin, decimal_mode[, ...])

Calculates a coin quantity value converted to other coin with current exchange prices.

get_last_price(symbol: str = None) dict | list[source]

Returns all prices of symbols in a dict or if symbol specified, the float price of symbol.

Parameters:

symbol (str) – A binance symbol.

Return dict or list:

get_prices_dic(decimal_mode: bool) dict[source]

Gets all symbols current prices into a dictionary. :decimal_mode bool: It flags to work in decimal mode. :return dict:

get_bulk_klines(symbols: list[str], interval: str, limit: int = 500, max_workers: int = 10) dict[str, list[list]][source]

Fetch klines for multiple symbols in parallel using panzer bulk_klines.

Parameters:
  • symbols (list) – List of binance symbols (e.g. [‘BTCUSDT’, ‘ETHUSDT’]).

  • interval (str) – A binance valid time interval for candlesticks.

  • limit (int) – Number of klines per symbol (max 1000).

  • max_workers (int) – Maximum number of parallel requests.

Return dict:

Dictionary mapping symbol -> list of kline lists.

Example:

from binpan.api.market import get_bulk_klines
data = get_bulk_klines(['BTCUSDT', 'ETHUSDT', 'LTCUSDT'], '15m', limit=100)
# data['BTCUSDT'] -> [[open_time, open, high, low, close, ...], ...]
get_bulk_depth(symbols: list[str], limit: int = 100, max_workers: int = 10) dict[str, dict][source]

Fetch order book depth for multiple symbols in parallel using panzer bulk_depth.

Parameters:
  • symbols (list) – List of binance symbols.

  • limit (int) – Depth levels (5, 10, 20, 50, 100, 500, 1000, 5000).

  • max_workers (int) – Maximum number of parallel requests.

Return dict:

Dictionary mapping symbol -> depth dict with ‘bids’ and ‘asks’.

get_candles_by_time_stamps(symbol: str, tick_interval: str, start_time: int = None, end_time: int = None, limit=1000, time_zone='Europe/Madrid') list[list][source]

Calls API for a candles list using one or two timestamps, starting and ending.

Delegates pagination to panzer’s klines_range method.

Parameters:
  • symbol (str) – A binance valid symbol.

  • tick_interval (str) – A binance valid time interval for candlesticks.

  • start_time (int) – A timestamp in milliseconds from epoch.

  • end_time (int) – A timestamp in milliseconds from epoch.

  • limit (int) – Count of candles to ask for.

  • time_zone (str) – Just used for logging.

Return list:

Returns a list from the Binance API.

get_historical_candles(symbol: str, tick_interval: str, start_time: int, end_time: int, tick_interval_ms: int, requests_limit: int = 1000, ignore_errors: bool = False) list[list][source]

Retrieve all kline data within the given time range considering the API limit.

Start time and end time are rounded down to the nearest open tick interval and are included both opens rounded.

Please, check last close timestamp in klines because it can be not closed yet.

Parameters:
  • symbol (str) – The trading pair symbol (e.g., “BTCUSDT”).

  • tick_interval (str) – Kline tick interval (e.g., “1m”, “3m”, “1h”).

  • start_time (int) – Start timestamp (milliseconds) of the time range.

  • end_time (int) – End timestamp (milliseconds) of the time range.

  • tick_interval_ms (int) – Kline tick interval in milliseconds.

  • requests_limit (int) – API limit for the number of klines in a single request (default: 1000).

  • ignore_errors (bool) – If tru, just throw a warning on error. Recommended for redis filler.

Returns:

A list of klines data within the given time range.

Example of binpan response:

[[1696786200000,
 '27890.28000000',
 '27892.47000000',
 '27890.27000000',
 '27890.45000000',
 '5.42396000',
 1696786259999,
 '151280.49524920',
 370,
 '1.99232000',
 '55567.81240580',
 '0']...]
parse_candles_to_dataframe(raw_response: list, symbol: str, tick_interval: str, columns: list = None, time_cols: list = None, time_zone: str | None = 'UTC') DataFrame[source]

Format a list of lists by changing the indicated time fields to string format.

Passing a time_zone, for example ‘Europe/Madrid’, will change the time from utc to the indicated zone.

It will automatically sort the DataFrame using the first column of the time_cols list.

The index of the DataFrame will be numeric correlative.

Parameters:
  • raw_response (list(lists)) – API klines response. List of lists.

  • symbol (str) – Symbol requested

  • tick_interval (str) – Tick interval between candles.

  • columns (list) – Column names. Default is BinPan dataframe columns.

  • time_cols (list) – Columns to take dates from.

  • time_zone (str or None) – Optional. Time zone to convert dates in index.

Returns:

Pandas DataFrame

basic_dataframe(data: DataFrame, exceptions: list = None, actions_col='actions') DataFrame[source]

Delete all columns except: Open, High, Low, Close, Volume, actions.

Some columns can be excepted.

Useful to drop messed technical indicators columns in one shot.

Parameters:
  • data (pd.DataFrame) – A BinPan DataFrame

  • exceptions (list) – A list of columns to avoid dropping.

  • actions_col (str) – A column with operative actions.

Return pd.DataFrame:

Pandas DataFrame

convert_to_numeric(data: DataFrame) DataFrame[source]

Converts to numeric all posible columns for a given Dataframe.

Parameters:

data (pd.DataFrame) – A dataframe with columns

Return pd.DataFrame:

A dataframe with numeric values in each column that can be numeric.

convert_dict_to_numeric(input_dict: dict, parse_datetime2int: bool) dict[source]

Converts all values in a dictionary to numeric values if possible.

Parameters:
  • input_dict – A dictionary.

  • parse_datetime2int – If True, parses datetime columns to int.

Returns:

Returns a dictionary with all values converted to numeric values if possible.

get_last_agg_trades(symbol: str, limit=1000) list[dict][source]

Get just the last aggregated trades from API.

GET /api/v3/aggTrades

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

Weight(IP): 1

Parameters:
  • symbol – A binance symbol.

  • limit – API max limit is 1000.

Return list:

Aggregated trades in a list.

Return example:

[
  {
    "a": 26129,         // Aggregate tradeId
    "p": "0.01633102",  // Price
    "q": "4.70443515",  // Quantity
    "f": 27781,         // First tradeId
    "l": 27781,         // Last tradeId
    "T": 1498793709153, // Timestamp
    "m": true,          // Was the buyer the maker?
    "M": true           // Was the trade the best price match?
  }
]
get_aggregated_trades(symbol: str, fromId: int = None, limit: int = None, decimal_mode: bool = False) list[dict][source]

Returns aggregated trades from id to limit or last trades if id not specified.

Limit applied in fromId mode defaults to 500. Maximum is 1000.

GET /api/v3/aggTrades

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

Weight(IP): 4

Parameters:
  • symbol (str) – A binance valid symbol.

  • fromId (int) – Trade id to fetch from. If not passed, gets most recent trades.

  • limit (int) – Count of trades to ask for.

  • decimal_mode (bool) – Enables decimal type for return.

Return list:

Returns a list from the Binance API.

Return example:

[
  {
    "a": 26129,         // Aggregate tradeId
    "p": "0.01633102",  // Price
    "q": "4.70443515",  // Quantity
    "f": 27781,         // First tradeId
    "l": 27781,         // Last tradeId
    "T": 1498793709153, // Timestamp
    "m": true,          // Was the buyer the maker?
    "M": true           // Was the trade the best price match?
  }
]
get_aggregated_trades_by_time(symbol: str, startTime: int, endTime: int, limit: int = 1000) list[dict][source]

Returns aggregated trades using native startTime/endTime parameters of the API.

The API limits each request to a maximum window of 1 hour and 1000 results.

GET /api/v3/aggTrades

Weight(IP): 4

Parameters:
  • symbol (str) – A binance valid symbol.

  • startTime (int) – A timestamp in milliseconds from epoch.

  • endTime (int) – A timestamp in milliseconds from epoch.

  • limit (int) – Max trades per request (API max 1000).

Return list[dict]:

Returns a list of aggregated trade dicts from the Binance API.

get_historical_agg_trades(symbol: str, startTime: int = None, endTime: int = None, start_trade_id: int = None, end_trade_id: int = None, limit_ids: int = 1000, limit_hours: float = 1) list[dict][source]

Returns aggregated trades between timestamps or trade IDs.

For timestamp mode, uses native startTime/endTime API parameters with 1-hour chunking. For ID mode, paginates forward with fromId.

Parameters:
  • symbol (str) – A binance valid symbol.

  • startTime (int) – A timestamp in milliseconds from epoch.

  • endTime (int) – A timestamp in milliseconds from epoch.

  • start_trade_id (int) – A trade id as first one (older).

  • end_trade_id (int) – A trade id as last one (newer).

  • limit_ids (int) – Count of trades to ask for if just start_trade_id or just end_trade_id passed. Ignored if startTime or endTime passed.

  • limit_hours (float) – Count of hours to ask for if just startTime or just endTime passed. Ignored if start_trade_id or end_trade_id passed.

Return list[dict]:

Returns a list from the Binance API in dicts.

[
  {
    "a": 26129,         // Aggregate tradeId
    "p": "0.01633102",  // Price
    "q": "4.70443515",  // Quantity
    "f": 27781,         // First tradeId
    "l": 27781,         // Last tradeId
    "T": 1498793709153, // Timestamp
    "m": true,          // Was the buyer the maker?
    "M": true           // Was the trade the best price match?
  }
]
parse_agg_trades_to_dataframe(response: list, columns: dict, symbol: str, time_zone: str = None, time_index: bool = None, drop_dupes: str = None) DataFrame[source]

Parses the API response into a pandas dataframe.

{'M': True,
 'T': 1656166914571,
 'a': 1218761712,
 'f': 1424997754,
 'l': 1424997754,
 'm': True,
 'p': '21185.05000000',
 'q': '0.03395000'}
Parameters:
  • response (list) – API raw response from trades.

  • columns – Column names.

  • symbol – The used symbol.

  • time_zone – Selected time zone.

  • time_index – Or integer index.

  • drop_dupes (str) – Drop duplicated by a column name.

Returns:

Pandas DataFrame

get_last_atomic_trades(symbol: str, limit=1000) list[dict][source]

Returns recent atomic (not aggregated) trades.

GET /api/v3/trades

Get recent trades.

Weight(IP): 25

Parameters:
  • symbol (str) – A binance valid symbol.

  • limit (int) – API max limit is 1000.

Return list:

Returns a list from the Binance API

Return example:

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590,
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]
get_atomic_trades(symbol: str, fromId: int = None, limit: int = None, decimal_mode: bool = False) list[dict][source]

Returns atomic (not aggregated) trades from id to limit or last trades if id not specified.

Limit applied in fromId mode defaults to 500. Maximum is 1000.

GET /api/v3/historicalTrades

Get older market trades.

Weight(IP): 25

Parameters:
  • fromId (int) – Trade id to fetch from. If not passed, gets most recent trades.

  • symbol (str) – A binance valid symbol.

  • limit (int) – Count of trades to ask for.

  • decimal_mode (bool) – Enables decimal type for return.

Return list:

Returns a list from the Binance API.

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590, // Trade executed timestamp, as same as `T` in the stream
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]
get_historical_atomic_trades(symbol: str, startTime: int = None, endTime: int = None, start_trade_id: int = None, end_trade_id: int = None, limit_ids: int = 1000, limit_hours: float = 1) list[dict][source]

Returns atomic (not aggregated) trades between timestamps or trade IDs.

For timestamp mode, uses aggTrades (weight 4) to discover the atomic trade ID range, then paginates with /api/v3/historicalTrades (weight 25) using fromId. This avoids the old adaptive search algorithm and is deterministic.

For ID mode, paginates forward with fromId directly.

Parameters:
  • symbol (str) – A binance valid symbol.

  • startTime (int) – A timestamp in milliseconds from epoch.

  • endTime (int) – A timestamp in milliseconds from epoch.

  • start_trade_id (int) – A trade id as first one (older).

  • end_trade_id (int) – A trade id as last one (newer).

  • limit_ids (int) – Count of trades to ask for if just start_trade_id or just end_trade_id passed. Ignored if startTime or endTime passed.

  • limit_hours (float) – Count of hours to ask for if just startTime or just endTime passed. Ignored if start_trade_id or end_trade_id passed.

Return list[dict]:

Returns a list from the Binance API in dicts.

[
    {'id': 86206215,
     'price': '0.00454100',
     'qty': '0.02400000',
     'quoteQty': '0.00010898',
     'time': 1669579405932,
     'isBuyerMaker': False,
     'isBestMatch': True}, ...
]
parse_atomic_trades_to_dataframe(response: list, columns: dict, symbol: str, time_zone: str = None, time_index: bool = None, drop_dupes: str = None) DataFrame[source]

Parses the API response into a pandas dataframe.

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590, // Trade executed timestamp, as same as `T` in the stream
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]

Redis response:

 {'e': 'trade',
  'E': 1669721069347,
  's': 'LTCBTC',
  't': 86293174,
  'p': '0.00466300',
  'q': '3.10900000',
  'b': 992385453,
  'a': 992385448,
  'T': 1669721069347,
  'm': False,
  'M': True},
 ...]
Parameters:
  • response (list) – API raw response from atomic trades.

  • columns – Column names.

  • symbol – The used symbol.

  • time_zone – Selected time zone.

  • time_index – Or integer index.

  • drop_dupes (str) – Drop duplicated by a column name.

Returns:

Pandas DataFrame

get_order_book(symbol: str, limit=5000) dict[source]

Returns a dictionary with timestamp, bids and asks. Bids and asks are a list of lists with strings representing price and quantity.

Parameters:
  • symbol (str) – A Binance valid symbol.

  • limit (int) – Max is 5000. Default 5000.

Return dict:

A dict with ask and bids

{
  "lastUpdateId": 1027024,
  "bids": [
    [
      "4.00000000",     // PRICE
      "431.00000000"    // QTY
    ]
  ],
  "asks": [
    [
      "4.00000200",
      "12.00000000"
    ]
  ]
}
get_orderbook_tickers(symbol: str = None, decimal_mode: bool = False) dict[source]

Symbol Order Book Ticker

GET /api/v3/ticker/bookTicker

Best price/qty on the order book for a symbol or symbols.

Weight(IP):

Parameter Symbols Provided Weight symbol 1 1 symbol parameter is omitted 2 symbols Any 2 Parameters:

Name Type Mandatory Description symbol STRING NO Parameter symbol and symbols cannot be used in combination.

If neither parameter is sent, bookTickers for all symbols will be returned in an array.

Examples of accepted format for the symbols parameter: [“BTCUSDT”,”BNBUSDT”]

Parameters:
  • symbol (str) – Optional. If not passed, all symbols returned.

  • decimal_mode (bool) – If selected, return decimal values.

Returns:

Api response is:

Response:

{
  "symbol": "LTCBTC",
  "bidPrice": "4.00000000",
  "bidQty": "431.00000000",
  "askPrice": "4.00000200",
  "askQty": "9.00000000"
}
OR

[
  {
    "symbol": "LTCBTC",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000"
  },
  {
    "symbol": "ETHBTC",
    "bidPrice": "0.07946700",
    "bidQty": "9.00000000",
    "askPrice": "100000.00000000",
    "askQty": "1000.00000000"
  }
]

intermediate_conversion(coin: str, decimal_mode: bool, prices: dict = None, try_coin: str = 'BTC', coin_qty: float = 1) float | None[source]

Uses an intermediate symbol for conversion. Uses stablecoin USDT versus other “try” coin.

Parameters:
  • coin (str) – A binance coin.

  • decimal_mode (bool) – It flags to work in decimal mode.

  • prices (dict) – BinPan prices dict.

  • try_coin (str) – Coin to try as intermediate in case of not existing pair. Default is BTC.

  • coin_qty (float) – Quantity to convert. Default is 1.

Return float:

converted value.

convert_coin(coin: str, decimal_mode: bool, convert_to: str = 'BUSD', coin_qty: float | Decimal = 1, prices: dict = None) float | None[source]

Calculates a coin quantity value converted to other coin with current exchange prices.

Parameters:
  • coin (str) – An existing coin string.

  • decimal_mode (bool) – It flags to work in decimal mode.

  • convert_to (str) – An existing coin string.

  • coin_qty (float) – How many coins to convert to.

  • prices (dict) – A dictionary with symbols and prices.

Return float:

Converted value for the quantity