Method References
This page introduces the methods provided by DolphinDB backtesting engine. These methods allow you to create a backtesting engine for a user-defined strategy, run backtests, and obtain results such as daily positions, daily equity, return summaries, and trade details.
appendEndMarker
Syntax
Backtest::appendEndMarker(engine)
Details
Ends the backtest and triggers the event functions afterTrading and finalize. Equivalent to appending an END message via appendQuotationMsg.
Parameters
engine: The handle of the backtesting engine.
appendQuotationMsg
Syntax
Backtest::appendQuotationMsg(engine, msg)
Details
Inserts market data to execute the strategy backtest.
Parameters
engine: The handle of the backtesting engine.
msg: Market data input table. For the table schema, refer to Market Data Structure.
cancelOrder
Syntax
Backtest::cancelOrder(engine, [symbol=""], [orders], [label=""])
Details
Cancels orders.
-
If symbol is not empty and the other fields are empty, this method cancels all orders for that symbol.
-
If symbol is empty and orders is not empty, this method cancels the orders in orders.
-
If symbol and orders are both empty, this method cancels the orders specified by label.
-
If symbol, orders, and label are all empty, this method cancels all orders in engine.
Parameters
engine: The handle of the backtesting engine. In callback functions, it can be obtained via contextDict["engine"].
symbol (optional): A STRING scalar specifying the security symbol of the orders to cancel.
orders (optional): An INTEGRAL vector specifying the list of order IDs to cancel.
label (optional): A STRING scalar specifying the label or note of the orders to cancel.
createBacktestEngine
Note:
This method is the legacy version of createBacktester.
Syntax
Backtest::createBacktestEngine(name, config, [securityReference], initialize, beforeTrading, onTick/onBar, onSnapshot, onOrder, onTrade, afterTrading, finalize)
Details
Creates a backtesting engine and sets all callback functions. This method is the legacy version of createBacktester and applies to all assets.
Returns the handle of the created backtesting engine.
Parameters
name: A STRING scalar specifying the backtesting engine name.
config: A dictionary specifying the configuration items for the backtesting engine. The key is a STRING that represents the configuration item name, and the value is the specific configuration for that item.
securityReference: The security reference table. This parameter is optional only when the asset is a stock; it is required for all other asset types.
initialize: The initialization callback function, triggered when the backtest starts.
beforeTrading: The pre-market callback function, triggered once before the market opens each day.
onTick/onBar (optional): The tick-by-tick, minute-level or daily bar market data callback function. Triggered when subscribing to snapshot market data.
onSnapshot: The snapshot market data callback function, triggered when subscribing to snapshot market data.
onOrder: The order report notification function, triggered when an order is updated.
onTrade: The trade report notification function, triggered when an order is traded.
afterTrading: The post-market callback function, triggered at market close each day.
finalize: The strategy end callback function, triggered when the backtest ends.
Among the callback functions above, the trigger conditions for onTick, onBar, and onSnapshot are as follows. When using them, specify the corresponding callback functions in the config parameter; you do not need to specify all of them:
| Input Data Type | Frequency | Triggerable Functions |
|---|---|---|
| dataType=0 | frequency=0 | onTick |
| frequency>0 | onTick, onSnapshot |
|
| dataType=1 or 2 | frequency=0 | onSnapshot |
| frequency>0 | onSnapshot, onBar |
createBacktester
Syntax
Backtest::createBacktester(name, config, eventCallbacks, [jit=false], [securityReference])
Details
Creates a backtesting engine and sets all callback functions.
Returns the handle of the created backtesting engine.
Parameters
name: A STRING scalar specifying the backtesting engine name.
config: A dictionary specifying the configuration items for the backtesting engine. The dictionary key is a STRING that represents the configuration item name, and the value is the specific configuration for that item.
eventCallbacks: A dictionary specifying the strategy callback functions. The dictionary key is a STRING that represents the callback function, and the value is the definition of the corresponding function. The available values for key are:
-
"initialize": The strategy initialization callback function, triggered when the backtest starts.
-
"beforeTrading": The pre-market callback function, triggered before the market opens each day.
-
"onTick" (optional): The tick market data callback function. Triggered when subscribing to tick market data.
-
"onSnapshot": The snapshot market data callback function, triggered when subscribing to snapshot market data.
-
"onBar" (optional): The minute or daily bar market data callback function. Triggered when subscribing to snapshot market data.
-
"onOrder": The order report notification function, triggered when an order is updated.
-
"onTrade": The trade report notification function, triggered when an order is traded.
-
"afterTrading": The post-market callback function, triggered at market close each day.
-
"finalize": The strategy end callback function, triggered when the backtest ends.
- "onTimer": The timer callback function. The value is a dictionary:
-
When dataType=1, 2, 3, 5, or 6, the key is of SECOND type and represents the trigger time; its value is the timer callback function.
-
When dataType=4, the key is of STRING type and can have the following values:
- "dateList": The value is a DATE scalar or vector specifying the trigger date;
- "onTimeCallback": The value is the timer callback function.
-
Among the callback functions above, the trigger conditions for onTick, onBar, and onSnapshot are as follows. When using them, specify the corresponding callback functions in the config parameter; you do not need to specify all of them:
| Input Data Type | Frequency | Triggerable Functions |
|---|---|---|
| dataType=0 | frequency=0 | onTick |
| frequency>0 | onTick, onSnapshot |
|
| dataType=1 or 2 | frequency=0 | onSnapshot |
| frequency>0 | onSnapshot, onBar |
jit (optional): A BOOL scalar specifying whether to enable JIT optimization. The default value is false, meaning JIT optimization is not enabled. Currently, JIT optimization is not supported for cryptocurrency backtesting or for simulated trading mode (isBacktestMode=false).
securityReference: The basic information table for the contract. This parameter is optional only when the asset is a stock; it is required for all other assets.
dropBacktestEngine
Syntax
Backtest::dropBacktestEngine(engine)
Details
Deletes a backtesting engine. Only administrators and the engine creator can call this method.
Parameters
engine: The handle of the backtesting engine.
enableEnginePersistence
Syntax
Backtest::enableEnginePersistence(engine, snapshotDir, [freq], [udf])
Details
Enables engine persistence. Currently, snapshot, minute-frequency, and daily-frequency backtesting is supported for stocks and for margin trading and securities lending; the callback function onTimer and JIT mode are not yet supported.
Snapshots are saved at the following times:
-
Calling this method immediately saves a snapshot.
-
Whenever
appendQuotationMsgfinishes backtesting a batch of market data:-
If the order status changes, a snapshot is saved immediately;
-
If the order status has not changed, a snapshot is saved if the current market data time exceeds the market data time of the last snapshot by more than freq.
-
-
A snapshot is saved when
beforeTradingorafterTradingis triggered, and when backtesting ends.
Parameters
engine: The handle of the backtesting engine.
snapshotDir: A STRING scalar specifying the directory where snapshot files are stored.
freq (optional): An INT scalar that specifies the minimum interval, in seconds, for triggering persistence when the order status has not changed. The default value is 0, which means persistence is triggered automatically on every market data callback. If the value is less than 0, automatic persistence is not triggered.
udf (optional): A dictionary. If a callback function calls user-defined functions, they must be specified here to ensure normal use after recovery. The dictionary's keys are of STRING type that represent function names; its values are ANY values that represent the corresponding functions.
extractSnapshotInfo
Syntax
Backtest::extractSnapshotInfo(snapshotDir, engineName, [needContext=true])
Details
Extracts basic information about the backtesting engine saved in a snapshot file. Only the admin user and the engine creator can call this method.
Returns a dictionary with the following fields:
| Field Name | Description |
|---|---|
| engineName | Engine name |
| strategyGroup | Strategy type |
| dataType | Market data type |
| createdUser | Creator |
| createdTime | Snapshot creation time |
| pluginVersion | Plugin version |
| isBacktestMode | Whether in backtest mode |
| context | Context dictionary of the engine |
Parameters
snapshotDir: A STRING scalar specifying the directory where snapshot files are stored.
engineName: A STRING scalar specifying the name of the snapshot backtesting engine. It must match the name of the engine that created the snapshot.
needContext (optional): A BOOL value specifying whether to return the context dictionary. The default value is true, in which case the returned result includes the backtesting engine's context dictionary under the key "context". Note: The value of resource in the context dictionary context will not be retrieved.
forceTriggerEngineSnapshot
Syntax
Backtest::forceTriggerEngineSnapshot(engine, [force=false])
Details
Immediately triggers a snapshot save. The engine must already have persistence enabled by using enableEnginePersistence.
This method cannot be called inside a callback function.
Parameters
engine: The handle of the backtesting engine.
force (optional): A BOOL value specifying whether to force a snapshot save. The default value is false. In this case, a snapshot is triggered only if any of appendQuotationMsg, submitOrder, or cancelOrder has been called since the last persistence; otherwise, no snapshot is triggered.
getAvailableCash
Syntax
Backtest::getAvailableCash(engine)
Details
Retrieves the account's available cash.
Parameters
engine: The handle of the backtesting engine.
getBacktestEngineList
Syntax
Backtest::getBacktestEngineList()
Details
Retrieves all backtesting engines.
getBacktestEngineStat
Syntax
Backtest::getBacktestEngineStat(engine, [block=true])
Details
Retrieves the status of backtesting engines.
Returns a table with the following fields:
-
name: The name of the backtesting engine.
-
user: The creator of the backtesting engine.
- status: Backtesting engine status. Possible values are OK (available), END
(ended normally), and FATAL (unavailable). For engines in the FATAL state:
- If the FATAL state is caused by an invalid data format during data insertion, the engine can recover after data in the correct format is inserted.
- If the FATAL state is caused by an exception thrown from a callback
function, use
updateEventCallbacksto fix the callback function; the engine can then continue to be used normally.
-
lastErrMsg: The last error message.
-
numIndicators: The number of subscribed indicators.
-
snapshotTimestamp: The timestamp of the latest data processed by the backtesting engine.
-
isBacktestMode: Whether the current mode is backtesting or simulated trading.
Parameters
engine: The handle of the backtesting engine.
block (optional): A BOOL value specifying whether to block the current thread when another thread is using the backtesting engine. Defaults to true, meaning the method blocks until the status result is returned. If set to false, it throws an exception immediately.
getConfig
Syntax
Backtest::getConfig(engine)
Details
Retrieves the configuration of the backtesting engine.
Parameters
engine: The handle of the backtesting engine.
getContextDict
Syntax
Backtest::getContextDict(engine)
Parameters
engine: The handle of the backtesting engine.
Details
Returns the logical context.
getDailyPosition
Syntax
Backtest::getDailyPosition(engine, [symbol=""])
Parameters
engine: The handle of the backtesting engine.
symbol (optional): A STRING scalar specifying the target instrument to retrieve. Defaults to empty, in which case position data for all instruments is retrieved.
Details
Usually called at the end of a backtest; returns detailed daily post-close position data. Calling it during trading hours loses the current day's information and returns the previous day's position data.
For stocks, futures, and options, the position data detail table has the following schema:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| tradeDate | Trading day |
| lastDayLongPosition | The last day's long position |
| lastDayShortPosition | The last day's short position |
| longPosition | Long position quantity |
| longPositionAvgPrice | Average buy price |
| shortPosition | Short position quantity |
| shortPositionAvgPrice | Average sell price |
| todayBuyVolume | Current day's buy quantity |
| todayBuyValue | Current day's buy trading value |
| todaySellVolume | Current day's sell quantity |
| todaySellValue | Current day's sell trading value |
| closePrice | Daily closing price |
| strategyName | Strategy name, which is the name of this backtesting engine.This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. |
In margin trading and securities lending mode, the position data detail table has the following schema:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| tradeDate | Trading day |
| lastDayMarginSecuPosition | Last day's collateral purchase position quantity |
| lastDayMarginDebt | Last day's closing margin financing liability |
| lastDaySecuLendingDebt | Last day's closing securities lending liability |
| marginSecuPosition | Collateral purchase position quantity |
| marginSecuAvgPrice | Average long position price |
| marginBuyPosition | Margin purchase position quantity |
| marginBuyValue | Margin purchase amount |
| secuLendingPosition | Securities lending position quantity |
| secuLendingSellValue | Securities lending amount |
| closePrice | Closing price |
| longPositionConcentration | Long concentration |
| shortPositionConcentration | Short concentration |
| marginBuyProfit | Margin profit and loss |
| financialFee | Margin interest |
| secuLendingProfit | Securities lending profit and loss |
| secuLendingFee | Securities lending fee |
| strategyName | Strategy name, which is the name of this backtesting engine.This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. |
For bonds, the position data detail table has the following schema:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| lastDayLongPosition | Last day's long position quantity |
| lastDayShortPosition | Last day's short position quantity |
| longPosition | Long position quantity |
| shortPosition | Short position quantity |
| longPositionAvgPrice | Average buy price |
| shortPositionAvgPrice | Average sell price |
| todayBuyVolume | Current day's buy quantity |
| todaySellVolume | Current day's sell quantity |
| totalValue | Total position value |
| accruedInterest | Accrued interest |
| fullBondPrice | Bond full price |
| lastPrice | Bond clean price |
| yield | Yield |
| interestIncome | Interest income |
| floatingProfit | Floating profit and loss |
| realizedProfit | Realized profit and loss |
| totalProfit | Total profit and loss |
| duration | Duration |
| convexity | Convexity |
| DV01 | DV01 |
| closePrice | Daily closing price |
getDailyTotalPortfolios
Syntax
Backtest::getDailyTotalPortfolios(engine)
Parameters
engine: The handle of the backtesting engine.
Details
Usually called at the end of a backtest to retrieve the strategy's daily equity metrics table.The schema of the returned table varies depending on the asset type used in the backtest:
-
Stocks:
Field Name Description tradeDate Date cash Available funds totalMarketValue Total account market value totalEquity Total account equity netValue Account unit net value totalReturn Cumulative return as of the current day ratio Account daily return pnl Account daily profit and loss frozenFunds Frozen funds totalFee Total fees floatingPnl Floating profit and loss realizedPnl Realized profit and loss totalPnl Total profit and loss benchmarkClosePrice Benchmark daily closing price. Returned only when benchmark is set. benchmarkNetValue Benchmark daily net value. Returned only when benchmark is set. bottomNetValue Bottom position net value. Returned only when a bottom position is set. strategyName Strategy name, which is the name of this backtesting engine. This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. -
Margin Trading and Securities Lending:
Field Name Description tradeDate Date lineOfCredit Line of credit availableCash Available funds lastDayMarginDebt Last day's closing margin financing liability lastDaySecuLendingDebt Last day's closing securities lending liability marginSecuMarketValue Market value of collateral purchases marginDebt Margin debt secuLendingSellValue Securities lending sale amount (securities lending liability) marginBalance Margin trading and securities lending balance secuLendingDebt Securities lending liability financialFee Margin interest secuLendingFee Securities lending fee maintenanceMargin Maintenance margin ratio availableMarginBalance Available margin balance totalMarketValue Total account market value totalEquity Total account equity netValue Account unit net value totalReturn Cumulative return as of the current day yield Account daily return pnl Account daily profit and loss benchmarkClosePrice Benchmark daily closing price. Returned only when benchmark is set. benchmarkNetValue Benchmark daily net value. Returned only when benchmark is set. strategyName Strategy name, which is the name of this backtesting engine. This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. -
Futures/Options:
Field Name Description tradeDate Date margin Margin occupied floatingPnl Floating profit and loss realizedPnl Cumulative realized profit and loss totalPnl Cumulative profit and loss totalMarketValue Total market value (options only) cash Available funds totalEquity Total account equity marginRatio Margin occupied ratio pnl Account daily profit and loss netValue Account unit net value totalReturn Cumulative return as of the current day ratio Account daily return benchmarkClosePrice Benchmark daily closing price. Returned only when benchmark is set. benchmarkNetValue Benchmark daily net value. Returned only when benchmark is set. -
Bonds
Field Name Description cash Available funds totalMarketValue Total account market value totalEquity Total account equity netValue Account unit net value totalReturn Cumulative return as of the current day ratio Account daily return pnl Account daily profit and loss totalFee Total fees floatingPnl Floating profit and loss realizedPnl Realized profit and loss totalPnl Total profit and loss
getDailyTradingStatistics
Syntax
Backtest::getDailyTradingStatistics(engine, [symbol=""])
Parameters
engine: The handle of the backtesting engine.
symbol (optional): A STRING scalar specifying the contract to retrieve. Defaults to empty, in which case position data for all contracts is retrieved.
Details
Only stocks, options, and futures are supported. The method retrieves daily trading statistics.
When symbol is specified, returns a dictionary; otherwise, returns a table with the following fields:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| assetType | Asset type (included only in multi-asset backtests) |
| tradeDate | Trade date |
| todayBuyOpenTradeVolume | Current-day buy-to-open trading volume |
| todayBuyOpenTradeValue | Current day's buy-to-open trading amount |
| todayBuyOpenAvgPrice | Current day's buy-to-open average price |
| todaySellOpenTradeVolume | Current day's sell-to-open trading volume |
| todaySellOpenTradeValue | Current day's sell-to-open trading amount |
| todaySellOpenAvgPrice | Current day's sell-to-open average price |
| todaySellCloseTradeVolume | Current day's sell-to-close trading volume |
| todaySellCloseTradeValue | Current day's sell-to-close trading amount |
| todaySellCloseAvgPrice | Current day's sell-to-close average price |
| todayBuyCloseTradeVolume | Current day's buy-to-close trading volume |
| todayBuyCloseTradeValue | Current day's buy-to-close trading amount |
| todayBuyCloseAvgPrice | Current day's buy-to-close average price |
getEventCallbacks
Syntax
Backtest::getEventCallbacks(engine)
Details
Retrieves the strategy callback function used by the backtesting engine. Only the engine creator can call this method.
Returns a dictionary.
Parameters
engine: The handle of the backtesting engine.
getFuturesTotalPortfolios
Syntax
Backtest::getFuturesTotalPortfolios(engine)
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
Details
Queries daily futures profit and loss (P&L). The returned table schema is as follows:
| Field Name | Description |
|---|---|
| tradeDate | Date |
| margin | Margin occupied |
| floatingPnl | Floating profit and loss |
| realizedPnl | Cumulative realized profit and loss |
| totalPnl | Cumulative profit and loss |
| cash | Available funds |
| totalEquity | Total account equity |
| marginRatio | Margin occupied ratio |
| pnl | Account daily profit and loss |
| netValue | Account unit net value |
| totalReturn | Cumulative return as of the current day |
| ratio | Account daily return |
| totalFee | Total fees |
getIndicatorSchema
Syntax
Backtest::getIndicatorSchema(engine,[marketDataType])
Parameters
engine: The handle of the backtesting engine.
marketDataType (optional): A STRING scalar specifying the market data type of the subscribed indicators. If the engine subscribes to indicators of only one market data type, this parameter can be omitted; otherwise, it must be specified.
Details
Returns an empty table of strategy indicators. The table schema is as follows:
| Field Name | Data Type | Description |
|---|---|---|
| symbol | SYMBOL | Instrument symbol |
| timestamp | TIMESTAMP | Timestamp |
| Subscribed indicator name | DOUBLE | Subscribed indicator |
| ... | ... | ... |
getMarginSecuPosition
Syntax
Backtest::getMarginSecuPosition(engine,[symbolList])
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
symbolList (optional): A STRING vector specifying the list of stock symbols. When omitted, returns collateral buy position information for all stocks by default.
Details
Retrieves collateral buy position information.
If engine is created by createBacktester:
-
When the length of symbolList is 1, a dictionary is returned.
-
When the length of symbolList is not 1, an error is raised.
-
When symbolList is omitted, a table is returned.
If engine is created by createBacktestEngine , a table is returned.
The returned table schema is as follows:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| lastDayLongPosition | Collateral buy position quantity at last day's close |
| lastDayBuyValue | Collateral buy amount at last day's close |
| longPosition | Collateral purchase position quantity |
| buyValue | Collateral buy amount |
| todayBuyVolume | Daily collateral buy traded quantity |
| todayBuyValue | Daily collateral buy trading value |
| strategyName | Strategy name, which is the name of this backtesting engine.This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. |
getMarginTradingPosition
Syntax
Backtest::getMarginTradingPosition(engine,[symbolList])
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
symbolList (optional): A STRING vector specifying the list of stock symbols. When omitted, returns margin buy position information for all stocks by default.
Details
Retrieves margin purchase position information.
If engine is created by createBacktester:
-
When the length of symbolList is 1, a dictionary is returned.
-
When the length of symbolList is not 1, an error is raised.
-
When symbolList is omitted, a table is returned.
If engine is created by createBacktestEngine , a table is returned.
The returned table schema is as follows:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| lastDayLongPosition | Margin purchase position at last day's close |
| lastDayBuyValue | Margin purchase amount at last day's close |
| lastDayMarginDebt | Margin purchase liability at last day's close |
| longPosition | Margin purchase position quantity |
| buyValue | Margin purchase amount |
| todayBuyVolume | Intraday margin purchase filled quantity |
| todayBuyValue | Intraday margin purchase amount |
| marginBuyProfit | Margin profit and loss |
| financialFee | Margin interest |
| strategyName | Strategy name, which is the name of this backtesting engine.This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. |
getOpenOrders
Syntax
Backtest::getOpenOrders(engine, [symbol=""], [orders], [label=""], [outputQueuePosition=false])
Parameters
engine: The handle of the backtesting engine. In callback functions, it can be obtained via contextDict["engine"].
symbol (optional): A STRING scalar specifying the security symbols.
orders (optional): An INTEGRAL vector specifying a list of order IDs.
label (optional): A STRING scalar used as a note.
outputQueuePosition (optional): A BOOL scalar specifying whether to output detailed information, including openVolumeWithBetterPrice, openVolumeWithWorsePrice, openVolumeAtOrderPrice, priorOpenVolumeAtOrderPrice, and depthWithBetterPrice. The default is false, meaning no detailed information is output. Only stocks and futures support this parameter.
Details
Retrieves unfilled orders.
-
If symbol is not empty, retrieves unfilled orders for that security.
-
If symbol is empty and orders is not empty, retrieves unfilled orders in orders.
-
If symbol and orders are both empty, retrieves unfilled orders specified by label.
Retrieves unfilled order information. Returns a tuple in which every element is a dictionary or a table.
For assets other than bonds, the structure is as follows:
| Key Name | Value Type | Value Description |
|---|---|---|
| orderId | LONG | Order ID |
| timestamp | TIMESTAMP | Time |
| symbol | STRING | Instrument symbol |
| price | DOUBLE | Order price |
| totalQty | LONG | User order quantity |
| openQty | LONG | Remaining user order quantity |
| direction | INT | 1 (buy to open), 2 (sell to open), 3 (sell to close), 4 (buy to close) |
| isMatching | BOOL | Whether the order has reached the matching time |
| openVolumeWithBetterPrice | LONG | Total quantity of unfilled orders at prices better than the order price (returned only whenoutputQueuePosition=true ). |
| openVolumeWithWorsePrice | LONG | Total quantity of unfilled orders at prices worse than the order price (returned only whenoutputQueuePosition=true ). |
| openVolumeAtOrderPrice | LONG | Total quantity of unfilled orders at prices equal to the order price (returned only whenoutputQueuePosition=true ). |
| priorOpenVolumeAtOrderPrice | LONG | Total quantity of unfilled orders at the order price that have time priority over the current order (returned only whenoutputQueuePosition=true ). |
| depthVolumeWithBetterPrice | INT | Depth of unfilled price levels at prices better than the order price (returned only whenoutputQueuePosition=true ). |
| updateTime | TIMESTAMP | Last updated time |
For bonds, the structure is as follows:
| Key Name | Value Type | Description |
|---|---|---|
| orderId | LONG | Order ID |
| time | TIMESTAMP | Time |
| symbol | STRING | Underlying stock |
| bidPrice | DOUBLE | Bid price |
| bidTotalQty | LONG | User buy order quantity |
| bidRemainQty | LONG | Remaining user buy order quantity |
| askPrice | DOUBLE | Sell order price |
| askTotalQty | LONG | User sell order quantity |
| askRemainQty | LONG | Remaining user sell order quantity |
| direction | INT | 1: buy 2: sell 3: bilateral |
| label | STRING | Notes |
getOptionTotalPortfolios
Syntax
Backtest::getOptionTotalPortfolios(engine)
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
Details
Retrieves daily option profit and loss. The returned table schema is as follows:
| Field Name | Description |
|---|---|
| tradeDate | Date |
| margin | Margin occupied |
| floatingPnl | Floating profit and loss |
| realizedPnl | Cumulative realized profit and loss |
| totalPnl | Cumulative profit and loss |
| totalMarketValue | Total account market value |
| cash | Available funds |
| totalEquity | Total account equity |
| marginRatio | Margin occupied ratio |
| pnl | Account daily profit and loss |
| netValue | Account unit net value |
| totalReturn | Cumulative return as of the current day |
| ratio | Account daily return |
| totalFee | Total fees |
getPosition
Syntax
Backtest::getPosition(engine, [symbol=""])
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
symbol (optional): A STRING scalar specifying the security symbols.
Details
Retrieves position information.
-
If symbol is not specified, the method returns a table;
-
If symbol is specified, the method returns a dictionary;
- When JIT optimization is enabled, symbol must be specified.
The structure is as follows:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| lastDayLongPosition | Last day's long position quantity |
| lastDayShortPosition | Last day's short position quantity |
| longPosition | Long position quantity |
| shortPosition | Short position quantity |
| longPositionAvgPrice | Average buy price |
| shortPositionAvgPrice | Average sell price |
| todayBuyVolume | Current day's buy quantity |
| todaySellVolume | Current day's sell quantity |
| totalValue | Total position value |
| accruedInterest | Accrued interest |
| fullBondPrice | Bond full price |
| lastPrice | Bond clean price |
| yield | Yield |
| interestIncome | Interest income |
| floatingProfit | Floating profit and loss |
| realizedProfit | Realized profit and loss |
| totalProfit | Total profit and loss |
| duration | Duration |
| convexity | Convexity |
| DV01 | DV01 |
getReturnSummary
Syntax
Backtest::getReturnSummary(engine)
Parameters
engine: The handle of the backtesting engine.
Details
Calculates the strategy return summary at the end of the backtest and returns a return summary table. The return summary table schema is as follows:
- Stocks/Futures/Options/Bonds:
Field Name Description totalReturn Total return annualReturn Annualized return annualVolatility Annualized volatility annualSkew Return skewness annualKur Return kurtosis sharpeRatio Sharpe ratio maxDrawdown Maximum drawdown drawdownRatio Return-drawdown ratio beta Beta coefficient alpha Alpha coefficient benchmarkReturn Benchmark return annualExcessReturn Annualized excess return turnoverRate Turnover rate dailyWinningRate Daily winning rate maxMarginRatio Maximum strategy margin occupancy ratio (For futures and options only) strategyName Strategy name, which is the name of this backtesting engine. This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. -
In margin trading and securities lending mode, the returned return summary table includes the following fields in addition to the fields listed above:
Field Name Description totalFee Total commissions and fees financialFee Margin interest secuLendingFee Securities lending fee bottomRet Bottom position return bottomExcessRet Bottom position excess return
getSecuLendingPosition
Syntax
Backtest::getSecuLendingPosition(engine,[symbolList])
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
symbolList (optional): A STRING vector specifying the list of stock symbols. If omitted, returns securities lending information for all stocks by default.
Details
Retrieves securities lending information.
If engine is created by createBacktester:
-
When the length of symbolList is 1, a dictionary is returned.
-
When the length of symbolList is not 1, an error is raised.
-
When symbolList is omitted, a table is returned.
If engine is created by createBacktestEngine , a table is returned.
The returned table schema is as follows:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| lastDayShortPosition | Last day's securities lending position quantity |
| lastDayShortValue | Last day's securities lending amount |
| lastDaySecuLendingDebt | Securities lending liability at last day's close |
| shortPosition | Securities lending position quantity |
| shortValue | Securities lending amount |
| todayShortVolume | Current day's securities lending trading volume |
| todayShortValue | Current day's securities lending amount |
| secuLendingProfit | Securities lending profit and loss |
| secuLendingFee | Securities lending fee |
| strategyName | Strategy name, which is the name of this backtesting engine.This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. |
getStockTotalPortfolios
Syntax
Backtest::getStockTotalPortfolios(engine)
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
Details
Retrieves the current stock strategy equity metrics and returns a dictionary with the following structure:
| Key Name | Description |
|---|---|
| tradeDate | Date |
| cash | Available funds |
| floatingPnl | Floating profit and loss |
| realizedPnl | Realized profit and loss |
| totalPnl | Total profit and loss |
| totalMarketValue | Total account market value |
| totalEquity | Total account equity |
| netValue | Account unit net value |
| totalReturn | Cumulative return as of the current day |
| ratio | Account daily return |
| pnl | Account daily profit and loss |
| totalFee | Total fees |
| frozenFunds | Frozen funds |
getTodayPnl
Syntax
Backtest::getTodayPnl(engine, symbol)
Parameters
engine: The handle of the backtesting engine.
symbol: A STRING scalar specifying the stock.
Details
This method is available only for stocks and retrieves the account profit and loss.
Returns a dictionary with the following structure:
| Key Name | Description |
|---|---|
| symbol | Instrument symbol |
| pnl | Profit and loss of the underlying in the current account |
| todayPnl | Profit and loss of the underlying in the account for the current day |
getTodayTradingStatistics
Syntax
Backtest::getTodayTradingStatistics(engine, [symbol])
Parameters
engine: The handle of the backtesting engine.
symbol (optional): A STRING scalar specifying the contract to retrieve. Defaults to empty, in which case position data for all contracts is retrieved.
Details
This method supports only stocks, options, and futures, and retrieves the current day's trading statistics.
When symbol is specified, returns a dictionary; otherwise, returns a table with the following fields:
| Field Name | Description |
|---|---|
| symbol | Instrument symbol |
| assetType | Asset type (included only in multi-asset backtests) |
| tradeDate | Trade date |
| todayBuyOpenTradeVolume | Current-day buy-to-open trading volume |
| todayBuyOpenTradeValue | Current day's buy-to-open trading amount |
| todayBuyOpenAvgPrice | Current day's buy-to-open average price |
| todaySellOpenTradeVolume | Current day's sell-to-open trading volume |
| todaySellOpenTradeValue | Current day's sell-to-open trading amount |
| todaySellOpenAvgPrice | Current day's sell-to-open average price |
| todaySellCloseTradeVolume | Current day's sell-to-close trading volume |
| todaySellCloseTradeValue | Current day's sell-to-close trading amount |
| todaySellCloseAvgPrice | Current day's sell-to-close average price |
| todayBuyCloseTradeVolume | Current day's buy-to-close trading volume |
| todayBuyCloseTradeValue | Current day's buy-to-close trading amount |
| todayBuyCloseAvgPrice | Current day's buy-to-close average price |
getTotalPortfolios
Syntax
Backtest::getTotalPortfolios(engine)
Parameters
engine: The handle of the backtesting engine.
Details
Retrieves the current strategy equity metrics.
If engine was created using createBacktestEngine, a table is returned; if it was created using createBacktester, a dictionary is returned.The structure is as follows:
-
Stocks:
Field Name Description tradeDate Date cash Available funds totalMarketValue Total account market value totalEquity Total account equity netValue Account unit net value totalReturn Cumulative return as of the current day ratio Account daily return pnl Account daily profit and loss frozenFunds Frozen funds totalFee Total fees floatingPnl Floating profit and loss realizedPnl Realized profit and loss totalPnl Total profit and loss benchmarkClosePrice Benchmark daily closing price. Returned only when benchmark is set. benchmarkNetValue Benchmark daily net value. Returned only when benchmark is set. bottomNetValue Bottom position net value. Returned only when a bottom position is set. strategyName Strategy name, which is the name of this backtesting engine. This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. -
Margin Trading and Securities Lending:
Field Name Description tradeDate Date lineOfCredit Line of credit availableCash Available funds lastDayMarginDebt Last day's closing margin financing liability lastDaySecuLendingDebt Last day's closing securities lending liability marginSecuMarketValue Market value of collateral purchases marginDebt Margin debt secuLendingSellValue Securities lending sale amount (securities lending liability) marginBalance Margin trading and securities lending balance secuLendingDebt Securities lending liability financialFee Margin interest secuLendingFee Securities lending fee maintenanceMargin Maintenance margin ratio availableMarginBalance Available margin balance totalMarketValue Total account market value totalEquity Total account equity netValue Account unit net value totalReturn Cumulative return as of the current day yield Account daily return pnl Account daily profit and loss benchmarkClosePrice Benchmark daily closing price. Returned only when benchmark is set. benchmarkNetValue Benchmark daily net value. Returned only when benchmark is set. strategyName Strategy name, which is the name of this backtesting engine. This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. -
Futures/Options:
Field Name Description tradeDate Date margin Margin occupied floatingPnl Floating profit and loss realizedPnl Cumulative realized profit and loss totalPnl Cumulative profit and loss totalMarketValue Total market value (options only) cash Available funds totalEquity Total account equity marginRatio Margin occupied ratio pnl Account daily profit and loss netValue Account unit net value totalReturn Cumulative return as of the current day ratio Account daily return benchmarkClosePrice Benchmark daily closing price. Returned only when benchmark is set. benchmarkNetValue Benchmark daily net value. Returned only when benchmark is set. -
Bonds
Field Name Description cash Available funds totalMarketValue Total account market value totalEquity Total account equity netValue Account unit net value totalReturn Cumulative return as of the current day ratio Account daily return pnl Account daily profit and loss totalFee Total fees floatingPnl Floating profit and loss realizedPnl Realized profit and loss totalPnl Total profit and loss
getTradeDetails
Syntax
Backtest::getTradeDetails(engine)
Parameters
engine: The handle of the backtesting engine.
Details
Retrieves order transaction details. The table schema is as follows:
| Field Name | Description |
|---|---|
| orderId | Order ID |
| symbol | Security symbol |
| direction | Order side 1: buy to open; 2: sell to open; 3: sell to close; 4: buy to close |
| sendTime | Order time |
| orderPrice | Order price |
| orderQty | Order quantity |
| tradeTime | Fill time |
| tradePrice | Fill price |
| tradeQty | Trade quantity |
| orderStatus | Indicates the order status: 4: submitted 2: cancellation successful 1: filled 0: partially filled -1: approval rejected -2: cancellation rejected -3: unfilled order |
| label | Tag |
| outputOrderInfo | Risk control log. This column is included only when the engine configuration parameteroutputOrderInfo=true. |
| seqNum | Sequence number column. This column is included only when the engine configuration parameteroutputSeqNum=true. |
| strategyName | Strategy name, which is the name of this backtesting engine.This field is included only in the simulated trading modes for stocks and for margin trading and securities lending. |
restoreFromSnapshot
Syntax
Backtest::restoreFromSnapshot(snapshotDir, engineName, [output], [resource], [functions])
Details
Restores a backtesting engine from a snapshot file and return a backtesting engine handle. Only the admin user and the engine creator can call this method.
Note: If the backtesting engine has subscribed to market data indicators, the engine status will be FATAL after it is restored.
Parameters
snapshotDir: A STRING scalar specifying the directory where snapshot files are stored.
engineName: A STRING scalar specifying the name of the snapshot backtesting engine. It must match the name of the engine that created the snapshot.
output (optional): A dictionary that sets the real-time output tables for the engine, equivalent to calling setTradingOutput.
resource (optional): A dictionary (STRING, ANY) that will be used as the value for the resource key in the context dictionary of the restored engine.
functions (optional): A dictionary (STRING, ANY) that will be used as the value for the functions key in the context dictionary of the restored engine.
setPosition
Syntax
Backtest::setPosition(engine, symbol, qty, orderPrice, [lastPrice], [assetType])
Details
Sets the initial position. It must be called before market data is inserted through appendQuotationMsg. It is usually called in the callback function initialize. It is not currently supported for cryptocurrency backtesting.
Unlike the setLastDayPosition, the bottom position set by setLastDayPosition does not consume initial capital, whereas the initial position set by setPosition consumes initial capital based on its cost.
Parameters
engine: The handle of the backtesting engine.
symbol: A STRING scalar specifying the underlying symbol.
qty: A LONG scalar specifying the position quantity:
-
qty>0: Represents a buy to open position;
-
qty<0: Represents a sell to open position. Stocks and bonds do not support sell to open.
orderPrice: A DOUBLE scalar specifying the position cost price.
lastPrice (optional): A DOUBLE scalar specifying the latest price of the underlying, i.e., the previous closing price. If this parameter is omitted or set to 0, it defaults to orderPrice.
assetType (optional): A STRING scalar specifying the asset type. It needs to be specified only for multi-asset backtesting. Valid values are stocks, futures, options.
setSecurityReference
Syntax
Backtest::setSecurityReference(engine, securityReference)
Parameters
engine: The handle of the backtesting engine.
securityReference: The basic information table corresponding to the instrument.
Details
Sets the basic information table.
setStockDividend
Syntax
Backtest::setStockDividend(engine, stockDividend)
Details
Sets the dividend and ex-rights information table. This is equivalent to the stockDividend configuration item. Only stock and margin trading and securities lending instruments are supported.
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
stockDividend: The dividend and ex-rights basic information table. Its fields are the same as those in the stockDividend configuration item.
setTradingOutput
Syntax
Backtest::setTradingOutput(engine, output)
Details
Sets real-time output tables for the backtesting engine. Information is written to the corresponding tables in real time.
Parameters
engine: The handle of the backtesting engine.
output: A dictionary with each key-value pair represents an output table. Valid keys include:
- snapshot: The corresponding value is the output table for subscribed snapshot indicators. Its table structure can be obtained through
getIndicatorSchema. - tick: The corresponding value is the output table for subscribed tick indicators. Its table schema can be obtained through
getIndicatorSchema. - ohlc: The corresponding value is the output table for subscribed OHLC bar indicators. Its table structure can be obtained through
getIndicatorSchema. - transaction (or trade): The corresponding value is the output table for subscribed tick-by-tick trade indicators. Its table schema can be obtained through
getIndicatorSchema. - snapshot_ohlc: The corresponding value is the output table for OHLC bar indicators synthesized from subscribed snapshots. Its table schema can be obtained through
getIndicatorSchema. - position: The corresponding value is the table that updates position information in real time. Use
getPositionto obtain the corresponding engine indicator table schema. - totalPortfolios: The corresponding value is the table that retrieves account equity in real time. Use
getTotalPortfoliosto obtain the corresponding engine indicator table schema. - tradeDetails: The corresponding value is the table that updates trade details in real time. Use
getTradeDetailsto obtain the corresponding engine indicator table schema. - dailyPosition: The corresponding value is the table that retrieves daily positions. Use
getDailyPositionto obtain the corresponding engine indicator table schema. - dailyTotalPortfolios: The corresponding value is the table that updates the account's daily equity. Use
getDailyTotalPortfoliosto obtain the corresponding engine indicator table schema. - returnSummary: The corresponding value is the table that updates the account's real-time return summary. Use
getReturnSummaryto obtain the corresponding engine indicator table schema. Supports backtesting for stocks and margin trading and securities lending.
setTradingVolumeDist
Syntax
Backtest::setTradingVolumeDist(engine, volume)
Details
Sets the VWAP volume distribution table, which is used by VWAP algorithmic orders to calculate the theoretical order quantity for each interval.
Parameters
engine: The handle of the backtesting engine.
volume: A table that represents the volume distribution. It contains the following fields:
| Field Name | Data Type | Description |
|---|---|---|
| symbol | STRING/SYMBOL | Instrument symbol |
| time | SECOND | Time |
| value | INT/DOUBLE | Trading volume or weight |
setUniverse
Syntax
Backtest::setUniverse(engine, symbolList)
Details
Sets the symbol pool for the engine.
Parameters
engine: The handle of the backtesting engine.
symbolList: A STRING vector that specifies the underlying symbols.
stopBacktestEngine
Syntax
Backtest::stopBacktestEngine(engine)
Details
-
If the engine is currently running a backtest (that is,
appendQuotationMsgis being called), it is terminated immediately. A terminated engine cannot be run again. -
If the engine is not running, no action is taken, and a backtest can still be started later by calling
appendQuotationMsg.
Returns a status table for the engine with the following fields:
-
name: The name of the backtesting engine.
-
user: The creator of the backtesting engine.
- status: Backtesting engine status. Possible values are OK (available), END
(ended normally), and FATAL (unavailable). For engines in the FATAL state:
- If the FATAL state is caused by an invalid data format during data insertion, the engine can recover after data in the correct format is inserted.
- If the FATAL state is caused by an exception thrown from a callback
function, use
updateEventCallbacksto fix the callback function; the engine can then continue to be used normally.
-
lastErrMsg: The last error message.
-
numIndicators: The number of subscribed indicators.
-
snapshotTimestamp: The timestamp of the latest data processed by the backtesting engine.
-
isBacktestMode: Whether the current mode is backtesting or simulated trading.
Parameters
engine: The handle of the backtesting engine.
submitOrder
Syntax
Backtest::submitOrder(engine, msg, [label=""], [orderType=0], [accountType="stock"], [algoOrderParam])
Details
Call this method in a callback function to submit an order. It returns the order number.
Parameters
engine: The handle of the backtesting engine. In callback functions, it can be obtained via contextDict["engine"].
msg: A tuple or table that represents the order information.
- When orderType=0, the format is as follows:
Product Format Description Stocks (including stocks, convertible bonds, and funds) (stock code, order time, order type, order price, order quantity, buy/sell direction) Buy/sell direction: 1: Buy to open; 2: Sell to open; 3: Sell to close; 4: Buy to close
Order type:
Shanghai Stock Exchange:
0: Five best orders immediate or cancel (market order).
1: Five best orders with immediate execution and remaining quantity converted to a limit order (market order).
2: Same-side best price (market order).
3: Opposite-side best price (market order).
5: Limit order
Shenzhen Stock Exchange:
0: Five best orders immediate or cancel (market order).
1: Immediate or cancel (market order).
2: Same-side best price (market order).
3: Market order: opposite-side best price order
4: Fill or kill (market order).
5: Limit order
Futures/Options (underlying code, exchange code, time, order type, order price, stop-loss price/take-profit price, order quantity, buy/sell direction, order validity) Buy/sell direction:
1: Buy to open
2: Sell to open
3: Sell to close
4: Buy to close
5: Option exercise (only supported for option products in multi-asset backtesting mode, and the underlyingCode field in the basic information table must be configured)
6: Sell to close today's position (only supported for futures and options products, and the intradayClosingFee field in the basic information table must be configured)
7: Buy to close today's position (only supported for futures and options products, and the intradayClosingFee field in the basic information table must be configured)
Order type:
0: Market order, placed at the limit-up or limit-down price, following time priority
1: Market stop-loss order
2: Market take-profit order
3: Limit stop-loss order
4: Limit take-profit order
5: Limit order (default)
Order validity:
0: Valid for the day (default)
1: Fill or kill (FOK)
2: Fill and kill (FAK)
Stop-loss/take-profit prices are not currently supported and default to 0.
Margin Trading and Securities Lending (stock code, order time, order type, order price, order quantity, buy/sell flag) Order type:
0: Market order
5: Limit order
Buy/Sell Flag:
1: Collateral buy
2: Collateral sell
3: Margin buy
4: Short sell
5: Direct repayment
6: Sell securities to repay
7: Direct return of securities
8: Buy securities to return
Bonds (underlying code, order time, order type, settlement cycle, bid price, bid quantity, ask price, ask quantity, buy/sell direction, user-specified order ID, channel, price type) Buy/Sell Direction:
1: Buy to open
2: Sell to close
3: Two-sided quote
4: Buy borrowed securities (bondLendingRate must be set in the base information table)
5: Close out borrowed securities (bondLendingRate must be set in the base information table)
Order Type:
1: Limit order
3: Market order to cancel
4: Market order to limit
5: Flexible
7: FAK: Immediately match at the user-specified price; any unfilled portion is canceled immediately.
8: FOK: Immediately match the entire order at the user-specified price; if it cannot be fully filled, cancel the order.
Price Type:
1 or omitted: Clean price
2: Dirty price
3: Yield
Cryptocurrency/Multi-Asset (underlying code, exchange code, time, order type, order price, stop-loss price, take-profit price, order quantity, buy/sell direction, slippage, time in force, order expiration time) Buy/sell direction: 1: Buy to open; 2: Sell to open; 3: Sell to close; 4: Buy to close
Order type:
5: Limit order (default)
0: Market order, placed at the limit-up or limit-down price, following time priority
Order validity:
0: Valid for the day (default)
1: Fill or kill (FOK)
2: Fill and kill (FAK)
-
When orderType is 5 or 6, the format is
(futures code, exchange code, time, order type, order price, stop-loss price, take-profit price, order quantity, buy/sell direction, slippage, time in force, order expiration time). -
When orderType is 8, the format is as follows:
Product Format Description Futures/Options (futures/contract code, exchange code, time, order type, buy open/close flag, bid price, bid quantity, sell open/close flag, ask price, ask quantity, bidDifftolerance, askDifftolerance, quantityAllowed)
In this format, bidDifftolerance, askDifftolerance, and quantityAllowed are reserved fields.
Buy/Sell direction: 1: Buy to open; 2: Sell to open; 3: Sell to close; 4: Buy to close; 5: Option exercise (only supported for option products in multi-asset backtest mode, and the underlyingCode field in the base information table must be configured)
Order type:
0: Market order, placed at the limit-up or limit-down price, following time priority
1: Market stop-loss order
2: Market take-profit order
3: Limit stop-loss order
4: Limit take-profit order
5: Limit order (default)
Order validity:
0: Valid for the day (default)
1: Fill or kill (FOK)
2: Fill and kill (FAK)
Stop-loss/take-profit prices are not currently supported and default to 0.
-
When orderType is 9, the format is as follows:
Product Format Description Futures/Options (underlying code, exchange code, time, order type, order price, stop-loss price/take-profit price, order quantity, buy/sell direction, order validity) -
When the side is 1:
-
If the order quantity is greater than the current buy-to-open position (longPosition), submit a buy-to-open order.
-
If the order quantity is less than or equal to longPosition, submit a sell-to-close order (side 3).
-
-
When the side is 2:
-
If the order quantity is greater than the current sell-to-open position (shortPosition), submit a sell-to-open order.
-
If the order quantity is less than or equal to shortPosition, submit a buy-to-close order (side 4).
-
Order type:
0: Market order, placed at the limit-up or limit-down price, following time priority
1: Market stop-loss order
2: Market take-profit order
3: Limit stop-loss order
4: Limit take-profit order
5: Limit order (default)
Order validity:
0: Valid for the day (default)
1: Fill or kill (FOK)
2: Fill and kill (FAK)
Stop-loss/take-profit prices are not currently supported and default to 0.
-
-
When orderType is 10, the format is as follows:
Product Format Description Stock, margin trading and securities lending. (stock code, order time, order type, order price, order quantity, buy/sell direction) Buy/sell direction: 1: Buy to open; 2: Sell to open; 3: Sell to close; 4: Buy to close
Order type:
Shanghai Stock Exchange:
0: Five best orders immediate or cancel (market order).
1: Five best orders with immediate execution and remaining quantity converted to a limit order (market order).
2: Same-side best price (market order).
3: Opposite-side best price (market order).
5: Limit order
Shenzhen Stock Exchange:
0: Five best orders immediate or cancel (market order).
1: Immediate or cancel (market order).
2: Same-side best price (market order).
3: Opposite-side best price (market order).
4: Fill or kill (market order).
5: Limit order
-
When orderType is 11, the format is as follows:
Product Format Description Stock, margin trading and securities lending. (stock code, order time, order type, order price, order quantity, buy/sell direction) Buy/sell direction: 1: Buy to open; 2: Sell to open; 3: Sell to close; 4: Buy to close
Order type:
Shanghai Stock Exchange:
0: Five best orders immediate or cancel (market order).
1: Five best orders with immediate execution and remaining quantity converted to a limit order (market order).
2: Same-side best price (market order).
3: Opposite-side best price (market order).
5: Limit order
Shenzhen Stock Exchange:
0: Five best orders immediate or cancel (market order).
1: Immediate or cancel (market order).
2: Same-side best price (market order).
3: Opposite-side best price (market order).
4: Fill or kill (market order).
5: Limit order
-
When orderType=12, the format is as follows:
Product Format Description Stock (stock code, exchange code, time, order type, order price, stop-loss price, take-profit price, highest/lowest price pullback percentage, order quantity, buy/sell direction, slippage, order validity, order expiration time) Buy/sell direction:
1: buy to open;
2: sell to open
Order validity:
0: Valid for the day (default)
1: Fill or Kill (FOK): immediately fill the entire order or cancel
2: Fill and Kill (FAK): execute immediately and cancel the remaining quantity
label (optional): A STRING scalar that sets a label for the order and classifies it.
orderType (optional): An INT scalar. Valid values are as follows:
-
0: Default value, indicating a standard order
-
5: Limit take-profit/stop-loss order
-
6: Market take-profit/stop-loss order
-
8: Two-sided quote order (supported for futures and options only)
-
9: Automatic order placement; the buy/sell direction can only be set to 1 or 2
-
10: Time-Weighted Average Price (TWAP) algorithmic order, which splits a large order evenly into multiple smaller orders for execution at regular time intervals
-
11: Volume-Weighted Average Price (VWAP) algorithmic order, which splits a large order into multiple smaller orders according to the distribution of trading volume.
-
12: Trailing take-profit/stop-loss order
Among them, 5, 6, and 8 are algorithmic orders. 5 and 6 support only stocks, futures, and options; 8 supports only futures and options. They can be enabled through the enableAlgoOrder configuration item. 10 and 11 support only snapshot mode for stocks and margin trading products.
accountType (optional): It is used only for multi-asset backtesting and cryptocurrency backtesting.
algoOrderParam (optional): It is used only for TWAP and VWAP algorithmic orders. It is a dictionary that contains the following fields:
| Field Name | Data Type | Description |
|---|---|---|
| startTime | SECOND | Optional. The start time for order splitting. If not set, it defaults to the latest market time of the engine. If set, the start time isstartTime = max(startTime, second(the latest market time of the engine)). |
| endTime | SECOND | Required. End time, used to calculate the number of split orders.
|
| interval | INT | Optional. Splitting interval in seconds. The default is 20 seconds. |
| maxSingleOrderVolume | LONG | Optional. Maximum number of lots per order. |
| orderPriceType | INT | Optional. Order price type for the algorithmic order:
|
subscribeIndicator
Syntax
Backtest::subscribeIndicator(engine, marketDataType, metrics)
Details
Sets the market data indicators to subscribe to.
Parameters
engine: The handle of the backtesting engine.
marketDataType: A STRING scalar that specifies the market data type of the indicators to subscribe to. Valid values are:
-
"snapshot": snapshot data.
-
"entrust": tick-by-tick orders.
-
"ohlc": OHLC bars.
-
"trade" or "transaction": tick-by-tick trades.
-
"snapshot_ohlc": OHLC bars aggregated from snapshot data.
metrics: A dictionary whose keys are of type STRING and represent indicator names, while its values are calculation formulas expressed as metacode that define how the indicators are calculated. For instructions on writing stateful factors, refer to Reactive State Engine.
Example
d=dict(STRING,ANY)
d["mavg"]=<mavg(lastPrice,20)>
Backtest::subscribeIndicator(contextDict["engine"], "snapshot", d)
Backtest::subscribeIndicator(contextDict["engine"], "tick", d)
d=dict(STRING,ANY)
d["mavg"]=<mavg(trade,20)>
Backtest::subscribeIndicator(contextDict["engine"], "trade", d)
d=dict(STRING,ANY)
d["mavg"]=<mavg(close,20)>
Backtest::subscribeIndicator(contextDict["engine"], "kline", d)
subscribeQuote
Syntax
Backtest::subscribeQuote(engine, symbolList, [symbolSource=""], [quoteType='snapshot'])]
Details
Subscribes to market data. After subscription, only the specified market data triggers callbacks.
Currently supports snapshot mode for futures, bonds, and multi-asset products.
Parameters
engine: The handle of the backtesting engine.
symbolList: A STRING vector that specifies the symbols to subscribe to.
symbolSource (optional): A STRING scalar specifying the exchange to subscribe to (the value of the symbolSource field). The default value is empty, which means no exchange is specified. In this case, data from both the Shanghai Stock Exchange and the Shenzhen Stock Exchange is subscribed to.
quoteType (optional): A STRING scalar that specifies the type of market data to subscribe to. Valid values:
-
"snapshot" (default): snapshot market data.
-
"ohlc": minute-frequency or daily-frequency data.
triggerDailySettlement
Syntax
Backtest::triggerDailySettlement(engine)
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
Details
This method can only be called in simulation mode (isBacktestMode=false). It enables manual daily closing settlement, including calculating daily positions, calculating daily equity, resetting the order matching simulator, triggering the afterTrading callback, and other related processing logic.
- Before this method is called for the first time, the system completes settlement through the cross-day settlement mechanism, that is, settlement is triggered when the date of the received market data timestamp changes.
- After this method is called for the first time, the automatic cross-day settlement mechanism is disabled, and settlement is triggered only through this method.
unsubscribeQuote
Syntax
Backtest::unsubscribeQuote(engine, symbolList, [symbolSource=""], [quoteType='snapshot'])
Details
Cancels market data subscriptions made by the backtesting engine.
Parameters
engine: The handle of the backtesting engine.
symbolList: A STRING vector that specifies the symbols to subscribe to.
symbolSource (optional): A STRING scalar that specifies the exchange to unsubscribe from (the value of the symbolSource field). The default value is empty, meaning no exchange is specified. In this case, subscriptions for all exchanges are cancelled.
quoteType (optional): A STRING scalar that specifies the type of market data to subscribe to. Valid values:
-
"snapshot" (default): snapshot market data.
-
"ohlc": minute-frequency or daily-frequency data.
updateEventCallbacks
Syntax
Backtest::updateEventCallbacks(engine, callbacks)
Details
Updates callback functions. This method supports simulation mode (isBacktestMode=false) only for stocks and margin trading products.
Parameters
engine: The handle of the backtesting engine.
callbacks: A dictionary (STRING, ANY). Keys are the callback functions to modify, supporting "initialize", "beforeTrading", "onTick", "onBar", "onSnapshot", "onOrder", "onTrade", "afterTrading", and "finalize". Values are the modified functions.
updatePosition
Syntax
Backtest::updatePosition(engine, symbol, qty, [price])
Parameters
engine: The backtesting engine handle, which can be obtained in the callback function through the logical context context["engine"].
symbol: A STRING scalar specifying the symbol.
qty: An INT scalar. A positive value increases the position; a negative value decreases the position.
price (optional): A DOUBLE scalar specifying the transaction price. The default value is empty. When the parameter is 0 or empty, the latest market price is used.
Details
Updates the position and returns the order ID. This method can only be called in simulated trading mode.
Multi-Asset Methods
Multi-asset backtesting supports managing multiple stock, futures, and option accounts in a single engine simultaneously.
The multi-asset backtesting methods are basically the same as the single-instrument methods. You can still use these methods to create an engine, run backtests, and retrieve backtest results. Only the methods that have changed are described here.
Some methods have additional parameters:
contractType: A STRING scalar that specifies the type of market instrument to subscribe to. Valid values are "stock", "futures", "option", and "bonds".
assetType: A STRING scalar specifying the account type. Valid values are "stock", "futures", "option", and "bonds", representing stock, futures, option, and bond accounts, respectively. For getDailyPosition, getDailyTotalPortfolios, getReturnSummary, and getTradeDetails, this parameter defaults to empty, in which case the corresponding information for all accounts is returned (getDailyPosition returns information for all accounts except bonds). For other methods, the default value is "stock".
| Method | Description |
|---|---|
| subscribeIndicator | Subscribe to indicators:Backtest::subscribeIndicator(engine, marketDataType, metrics, [contractType]) |
| submitOrder | Order placement:Backtest::submitOrder(engine, msg,
[label=""], [orderType=0], [assetType=""])The format of msg is (underlying symbol, exchange code, time, order type, order price, stop-loss price, take-profit price, order quantity, buy/sell direction, slippage, order validity, order expiration time). Note: For bond
accounts, the msg format is the same as for
single-instrument bonds. |
| cancelOrder | Cancel orders:Backtest::cancelOrder(engine, [symbol=""], [orders], [label=""], [assetType=""]) |
| getAvailableCash | Retrieves available account funds:Backtest::getAvailableCash(engine, [assetType="stock"]) |
| getTodayPnl | Retrieves stock profit and loss:Backtest::getTodayPnl(engine, symbol, [assetType=""]) |
| getPosition | Retrieves current positions:Backtest::getPosition(engine, [symbol], [assetType="stock"]) |
| getDailyPosition | Retrieves daily positions:Backtest::getDailyPosition(engine, [symbol], [assetType]) |
| getDailyTotalPortfolios | Retrieves daily portfolio metrics:Backtest::getDailyTotalPortfolios(engine, [assetType])
|
| getTotalPortfolios | Retrieves portfolio metrics table:Backtest::getTotalPortfolios(engine, assetType="")In addition to "stock", "futures", and "option", assetType can be set to "strategy" to represent the equity table for the entire strategy. |
| getReturnSummary | Retrieves strategy return summary:Backtest::getReturnSummary(engine, [assetType]) |
| getTradeDetails | Retrieves order trade details:Backtest::getTradeDetails(engine, [assetType]) |
| getOpenOrders | Retrieves unfilled orders:Backtest::getOpenOrders(engine, [symbol=""], [orders], [label=""], [outputQueuePosition=false], [assetType="stock"]) |
| getIndicatorSchema | Retrieves strategy metrics table:Backtest::getIndicatorSchema(engine,marketDataType,assetType="stock")marketDataType can be "snapshot", "ohlc", "kline", "trade", or "transaction". |
| setTradingOutput | Sets real-time output table:Backtest::setTradingOutput(engine, output)output is a nested dictionary where the key is the account type and the value is a dictionary. In the sub-dictionary, the key is the output table name and the corresponding value is the table object. |
| setSecurityReference | Sets basic information table:Backtest::setSecurityReference(engine, securityReference, [assetType=""]) |
| getTodayTradingStatistics | Retrieves today's trading statistics:Backtest::getTodayTradingStatistics(engine, [symbol], assetType)assetType is a required parameter. Currently only "stock", "futures", and "option" are supported. |
| getDailyTradingStatistics | Retrieves daily trading statistics:Backtest::getDailyTradingStatistics(engine, [symbol], [assetType])assetType currently only "stock", "futures", and "option". By default, results for all product types are returned. |
Cryptocurrency Methods
The backtesting engine supports managing multiple spot and futures accounts within a single engine for cryptocurrency.The multi-asset design follows these principles:
- The market data can include different contract types. The
onBarcallback provides all data for all contract types within the specified period at once, making it easier to design strategies based on market conditions across different contracts. - Backtesting cryptocurrency supports an optional accountType parameter to specify the account to operate on. If accountType is not specified, the method used in the strategy (such as placing or canceling orders, getting unfilled orders, checking positions, etc.) defaults to the spot account. After backtesting, methods called (such as trade details, daily positions, etc.) will default to returning results for all accounts.
In cryptocurrency backtesting, most engine methods are the same as for other assets. You can still use these methods to create an engine, run backtests, and retrieve backtest results. Note that some methos have additional parameters:
contractType: A STRING scalar that specifies the type of market instrument to subscribe to. Valid values are "spot", "futures", and "option", representing spot, futures and perpetual futures, and options, respectively.
accountType: A STRING scalar specifying the account type. Valid values are "spot", "futures", and "option", representing spot accounts, futures and perpetual futures accounts, and option accounts, respectively.
The related methods are shown in the following table:
| Method | Description |
|---|---|
| subscribeIndicator | Subscribe to indicators: Backtest::subscribeIndicator(contextDict["engine"], "snapshot", d,contractType) |
| submitOrder | Order placement: Backtest::submitOrder(engine, msg,label="",orderType=0,accountType) |
| cancelOrder | Cancel orders:Backtest::cancelOrder(engine, symbol="", orders=NULL, label="", contractType) |
| getAvailableCash | Retrieves available account funds: Backtest::getAvailableCash(long(engine),accountType) |
| getTotalPortfolios | Retrieves current portfolio metrics for the strategy: Backtest::getTotalPortfolios(engine, accountType) |
| getPosition | Retrieves current positions: Backtest::getPosition(engine,symbol="",accountType) |
| getDailyPosition | Retrieves daily positions: Backtest::getDailyPosition(engine,accountType) |
| getDailyTotalPortfolios | Retrieves daily portfolio metrics: Backtest::getDailyTotalPortfolios(engine,accountType) |
| getReturnSummary | Retrieves strategy return summary: Backtest::getReturnSummary(engine,accountType) |
| getTradeDetails | Retrieves order trade details: Backtest::getTradeDetails(engine,accountType) |
| getOpenOrders | Retrieves unfilled orders: Backtest::getOpenOrders(engine, symbol=NULL, orders=NULL, label="", accountType) |
