Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/nkaz001/hftbacktest/llms.txt

Use this file to discover all available pages before exploring further.

BacktestAsset

Configures a single asset for backtesting.
from hftbacktest import BacktestAsset

asset = BacktestAsset()

Methods

data
method
Sets the feed data for the asset.Parameters:
  • data (str | List[str] | NDArray | List[NDArray]): File paths to .npz files or NumPy arrays containing feed data
Returns: BacktestAsset (for method chaining)
asset.data('btcusdt_20240101.npz')
asset.data(['data1.npz', 'data2.npz'])
asset.data(numpy_array)
linear_asset
method
Configures the asset as a linear asset (standard futures/spot).Parameters:
  • contract_size (float): The contract size or multiplier
Returns: BacktestAsset
asset.linear_asset(1.0)  # For spot markets
inverse_asset
method
Configures the asset as an inverse asset (inverse perpetuals).Parameters:
  • contract_size (float): The contract size or multiplier
Returns: BacktestAsset
intp_order_latency
method
Uses interpolated order latency model based on historical latency data.Parameters:
  • data (str | NDArray | List[str]): Historical order latency data in .npz format or NumPy array
  • latency_offset (int, optional): Latency offset in nanoseconds. Default: 0
Returns: BacktestAsset
asset.intp_order_latency('order_latency.npz')
asset.intp_order_latency('latency.npz', latency_offset=100_000)
initial_snapshot
method
Sets the initial order book snapshot.Parameters:
  • data (str | NDArray): File path or NumPy array of the initial snapshot
Returns: BacktestAsset
asset.initial_snapshot('snapshot.npz')

HashMapMarketDepthBacktest

Backtester using hashmap-based market depth. Suitable for most use cases.
from hftbacktest import HashMapMarketDepthBacktest, BacktestAsset

assets = [BacktestAsset().data('data.npz').linear_asset(1.0)]
hbt = HashMapMarketDepthBacktest(assets)
Parameters:
  • assets (List[BacktestAsset]): List of configured backtest assets
Returns: A JIT-compiled backtester instance for use in @njit functions

Properties

current_timestamp
int64
Current timestamp in the backtest (nanoseconds by default).
ts = hbt.current_timestamp
num_assets
uint64
Total number of assets in the backtest.
n = hbt.num_assets

Methods

depth
method
Retrieves the market depth for a specific asset.Parameters:
  • asset_no (uint64): Asset number (0-indexed)
Returns: HashMapMarketDepth instance
depth = hbt.depth(0)
best_bid = depth.best_bid
best_ask = depth.best_ask
position
method
Returns the current position for an asset.Parameters:
  • asset_no (uint64): Asset number
Returns: float64 - Position quantity (positive for long, negative for short)
pos = hbt.position(0)
state_values
method
Retrieves state values including balance, fees, and trading statistics.Parameters:
  • asset_no (uint64): Asset number
Returns: StateValues instance
state = hbt.state_values(0)
balance = state.balance
fee = state.fee
orders
method
Returns the order dictionary for an asset.Parameters:
  • asset_no (uint64): Asset number
Returns: OrderDict - Dictionary of active orders
orders = hbt.orders(0)
if order_id in orders:
    order = orders.get(order_id)
submit_buy_order
method
Submits a buy order.Parameters:
  • asset_no (uint64): Asset number
  • order_id (uint64): Unique order ID
  • price (float64): Order price
  • qty (float64): Quantity to buy
  • time_in_force (uint8): GTC, GTX, FOK, or IOC
  • order_type (uint8): LIMIT or MARKET
  • wait (bool): If True, wait for order response
Returns: int64 - 0 on success, 1 if end of data reached, negative on error
from hftbacktest import GTX, LIMIT

result = hbt.submit_buy_order(
    asset_no=0,
    order_id=1,
    price=50000.0,
    qty=0.01,
    time_in_force=GTX,
    order_type=LIMIT,
    wait=False
)
submit_sell_order
method
Submits a sell order.Parameters:
  • asset_no (uint64): Asset number
  • order_id (uint64): Unique order ID
  • price (float64): Order price
  • qty (float64): Quantity to sell
  • time_in_force (uint8): GTC, GTX, FOK, or IOC
  • order_type (uint8): LIMIT or MARKET
  • wait (bool): If True, wait for order response
Returns: int64 - 0 on success, 1 if end of data reached, negative on error
from hftbacktest import GTX, LIMIT

result = hbt.submit_sell_order(
    asset_no=0,
    order_id=2,
    price=50100.0,
    qty=0.01,
    time_in_force=GTX,
    order_type=LIMIT,
    wait=False
)
cancel
method
Cancels an order.Parameters:
  • asset_no (uint64): Asset number
  • order_id (uint64): Order ID to cancel
  • wait (bool): If True, wait for cancel response
Returns: int64 - 0 on success, 1 if end of data reached, negative on error
hbt.cancel(asset_no=0, order_id=1, wait=True)
modify
method
Modifies an existing order.Parameters:
  • asset_no (uint64): Asset number
  • order_id (uint64): Order ID to modify
  • price (float64): New order price
  • qty (float64): New order quantity
  • wait (bool): If True, wait for modify response
Returns: int64 - 0 on success, 1 if end of data reached, negative on error
hbt.modify(asset_no=0, order_id=1, price=50050.0, qty=0.02, wait=True)
clear_inactive_orders
method
Clears inactive orders from the order dictionary.Parameters:
  • asset_no (uint64): Asset number, or ALL_ASSETS to clear all assets
from hftbacktest import ALL_ASSETS

hbt.clear_inactive_orders(0)  # Clear for asset 0
hbt.clear_inactive_orders(ALL_ASSETS)  # Clear all assets
elapse
method
Elapses time by the specified duration.Parameters:
  • duration (uint64): Duration to elapse (nanoseconds by default)
Returns: int64 - 0 on success, 1 if end of data reached, negative on error
# Elapse 10 milliseconds
if hbt.elapse(10_000_000) != 0:
    # End of data reached
    break
wait_order_response
method
Waits for an order response with timeout.Parameters:
  • asset_no (uint64): Asset number
  • order_id (uint64): Order ID to wait for
  • timeout (int64): Timeout in nanoseconds
Returns: int64 - 0 on response or timeout, 1 if end of data reached, negative on error
# Wait up to 5 seconds for order response
timeout = 5_000_000_000
hbt.wait_order_response(asset_no=0, order_id=1, timeout=timeout)
wait_next_feed
method
Waits for the next market feed.Parameters:
  • include_order_resp (bool): If True, also return on order responses
  • timeout (int64): Timeout in nanoseconds
Returns: int64 - 0 on timeout, 1 on end of data, 2 on feed, 3 on order response
result = hbt.wait_next_feed(include_order_resp=True, timeout=1_000_000_000)
last_trades
method
Retrieves recent market trades.Parameters:
  • asset_no (uint64): Asset number
Returns: NumPy array of trade events
trades = hbt.last_trades(0)
for i in range(len(trades)):
    price = trades[i].px
    qty = trades[i].qty
clear_last_trades
method
Clears the last trades buffer.Parameters:
  • asset_no (uint64): Asset number, or ALL_ASSETS to clear all
hbt.clear_last_trades(0)
close
method
Closes the backtester.Returns: int64 - 0 on success, negative on error
hbt.close()

ROIVectorMarketDepthBacktest

Backtester using vector-based market depth with a defined range of interest (ROI). More efficient for strategies focusing on specific price ranges.
from hftbacktest import ROIVectorMarketDepthBacktest, BacktestAsset

assets = [BacktestAsset().data('data.npz').linear_asset(1.0)]
hbt = ROIVectorMarketDepthBacktest(assets)
Parameters:
  • assets (List[BacktestAsset]): List of configured backtest assets
Returns: A JIT-compiled backtester instance Provides the same interface as HashMapMarketDepthBacktest, but returns ROIVectorMarketDepth instead of HashMapMarketDepth.

HashMapMarketDepth

Market depth interface using hashmap storage.

Properties

best_bid
float64
Best bid price.
depth = hbt.depth(0)
bid = depth.best_bid
best_ask
float64
Best ask price.
best_bid_tick
int64
Best bid price in ticks.
best_ask_tick
int64
Best ask price in ticks.
best_bid_qty
float64
Quantity at the best bid.
best_ask_qty
float64
Quantity at the best ask.
tick_size
float64
Minimum price increment.
lot_size
float64
Minimum quantity increment.

Methods

bid_qty_at_tick
method
Returns the bid quantity at a specific price level.Parameters:
  • price_tick (int64): Price in ticks
Returns: float64 - Quantity at the specified price
price_tick = int(50000.0 / depth.tick_size)
qty = depth.bid_qty_at_tick(price_tick)
ask_qty_at_tick
method
Returns the ask quantity at a specific price level.Parameters:
  • price_tick (int64): Price in ticks
Returns: float64 - Quantity at the specified price
price_tick = int(50100.0 / depth.tick_size)
qty = depth.ask_qty_at_tick(price_tick)

ROIVectorMarketDepth

Market depth interface using vector storage within a range of interest. Provides the same properties and methods as HashMapMarketDepth, plus:

Additional Properties

bid_depth
NDArray[float64]
Array of bid quantities indexed by price tick within the ROI.
depth = hbt.depth(0)
bid_array = depth.bid_depth
# Access quantity at price: (index + roi_lb_tick) * tick_size
ask_depth
NDArray[float64]
Array of ask quantities indexed by price tick within the ROI.
roi_lb_tick
int64
Lower bound of the range of interest in ticks.
roi_ub_tick
int64
Upper bound of the range of interest in ticks.

Order

Represents an order in the system.

Properties

order_id
uint64
Unique order identifier.
price
float64
Order price.
price_tick
int64
Order price in ticks.
qty
float64
Order quantity.
leaves_qty
float64
Remaining unfilled quantity.
side
int8
Order side: BUY (1) or SELL (-1).
status
uint8
Order status: NONE, NEW, FILLED, CANCELED, EXPIRED, PARTIALLY_FILLED.
order_type
uint8
Order type: LIMIT or MARKET.
time_in_force
uint8
Time-in-force: GTC, GTX, FOK, or IOC.
exec_price
float64
Execution price (valid when status is FILLED or PARTIALLY_FILLED).
exec_qty
float64
Executed quantity.
cancellable
bool
Whether the order can be cancelled.
exch_timestamp
int64
Exchange timestamp when order was processed.
local_timestamp
int64
Local timestamp when order was submitted.

StateValues

Contains state information for an asset.

Properties

position
float64
Current open position.
balance
float64
Cash balance.
fee
float64
Accumulated trading fees.
num_trades
int64
Total number of trades executed.
trading_volume
float64
Total trading volume (quantity).
trading_value
float64
Total trading value (notional).

OrderDict

Dictionary of active orders.

Methods

get
method
Retrieves an order by ID.Parameters:
  • order_id (uint64): Order ID
Returns: Order instance or None
order = orders.get(order_id)
if order is not None:
    print(order.price)
values
method
Returns an iterator over order values.Returns: Values iterator
# Method 1: Using has_next() and get()
values = orders.values()
while values.has_next():
    order = values.get()
    # Process order

# Method 2: Using next()
values = orders.values()
while True:
    order = values.next()
    if order is None:
        break
    # Process order
__contains__
method
Checks if an order exists.Parameters:
  • order_id (uint64): Order ID
Returns: bool
if order_id in orders:
    order = orders.get(order_id)
__len__
method
Returns the number of active orders.Returns: uint64
num_orders = len(orders)