StrategyTemplate#
- class swordfish.plugins.backtest.StrategyTemplate(engine)#
- Parameters:
engine (BacktesterBase)
- property accounts#
Get the corresponding account based on the account type, and perform operations or retrieve information using this account.
- final submit_order(msg, label='', order_type=0, account_type=AccountType.DEFAULT)#
This function can be called within callback functions to submit an order and returns the order ID.
- Parameters:
msg (_type_) – A tuple representing the order information. The format varies depending on the asset type. Please see details in “Order Format by Asset Type”
label (str, optional) – A STRING scalar, used to assign a label to the order for categorization.
order_type (int, optional) –
An INT scalar. Optional values:
0: Default, general order
5: Limit stop-loss/take-profit order
6: Market stop-loss/take-profit order
8: Two-sided quote order (supported only for futures and options)
Note: Types 5, 6, and 8 are algorithmic orders. Types 5 and 6 are supported for stocks, futures, and options. Type 8 is supported only for futures and options and can be enabled via the enableAlgoOrder configuration.
account_type (AccountType, optional) – A STRING scalar, indicating the account type. Optional values: “spot”, “futures”, “option”, representing spot, futures/perpetual, and option accounts, respectively. This parameter is applicable only for cryptocurrency strategies.
Order Format by Asset Type#
For orderType = 0, the format is:
Asset Type
Format
Description
Stock (including
convertible bonds, funds)
(Stock Code, Order Time, Order Type, Order Price, Order Quantity, Buy/Sell Direction)
Buy/Sell Direction:
1: Buy Open; 2: Sell Open; 3: Sell Close; 4: Buy Close
Order Type:
Shanghai Stock Exchange:
0: Market order - best 5 levels immediate or cancel
1: Market order - best 5 levels immediate and remaining as limit order
2: Market order - best price on own side
3: Market order - best price on opposite side
5: Limit order
6: Cancel order
Shenzhen Stock Exchange:
0: Market order - best 5 levels immediate or cancel
1: Market order - immediate or cancel remaining order
2: Market order - best price on own side
3: Market order - best price on opposite side
4: Market order - fill or kill order
5: Limit order
6: Cancel order
Futures / Options
(Symbol, Exchange Code, Time, Order Type, Order Price, Stop Loss/Take Profit Price, Order Quantity, Buy/Sell Direction,
Order Validity)
Buy/Sell Direction:
1: Buy Open; 2: Sell Open; 3: Sell Close; 4: Buy Close; 5: Option Exercise (only supported in multi-asset backtesting mode; underlyingCode must be configured in the instrument info table)
Order Type:
0: Market order - submitted at limit up/down price, 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)
6: Cancel order
9: Auto-trading mode (only Buy Open=1 or Sell Open=2 supported):
If Buy Open (1):
If order quantity > longPosition, submit a Buy Open order.
If order quantity ≤ longPosition, submit a Sell Close (3) order.
If Sell Open (2):
If order quantity > shortPosition, submit a Sell Open order.
If order quantity ≤ shortPosition, submit a Buy Close (4) order.
Order Validity:
0: Good for the day (default)
1: Fill or Kill (FOK)
2: Fill and Kill (FAK)
Stop loss/take profit prices are currently not supported and default to 0.
Margin Trading / 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 purchase
2: Collateral sale
3: Margin purchase
4: Short selling
5: Direct repayment
6: Sell-to-repay
7: Direct stock return
8: Buy-to-return
Bond
(Symbol, Order Time, Order Type, Clearing Speed, Bid Price, Bid Volume, Ask Price, Ask Volume, Buy/Sell Direction,
User Order ID, Channel)
Buy/Sell Flag:
1: Buy Open
2: Sell Close
3: Two-way quote
Order Type:
1: Limit order
3: Market-to-cancel order
4: Market-to-limit order
5: Elastic order
7: FAK - execute immediately, cancel unfilled portion
8: FOK - execute immediately in full, cancel otherwise
Cryptocurrency / Multi-Asset
(Symbol, Exchange Code, Time, Order Type, Order Price, Stop Loss Price, Take Profit Price, Order Quantity, Buy/Sell
Direction, Slippage, Order Validity, Expiration Time)
Buy/Sell Direction:
1: Buy Open; 2: Sell Open; 3: Sell Close; 4: Buy Close
Order Type:
5: Limit order (default)
0: Market order - submitted at limit up/down price, time priority
Order Validity:
0: Good for the day (default)
1: Fill or Kill (FOK)
2: Fill and Kill (FAK)
For orderType = 5 or 6, the tuple format is: (Symbol, Exchange Code, Time, Order Type, Order Price, Stop Loss Price, Take Profit Price, Order Quantity, Buy/Sell Direction, Slippage, Order Validity, Expiration Time).
For orderType = 8, the format is:
Asset Type
Format
Description
Futures / Options
(Contract Code, Exchange Code, Time, Order Type, Buy Open/Close Flag, Buy Price, Buy Quantity, Sell Open/Close Flag, Sell Price, Sell Quantity, bidDifftolerance, askDifftolerance, quantityAllowed)
Notes: The fields bidDifftolerance, askDifftolerance, and quantityAllowed are reserved.
Buy/Sell Direction:
1: Buy open
2: Sell open
3: Sell close
4: Buy close
5: Option exercise (only supported in multi-asset backtesting mode; the underlyingCode field in the basic information table must be configured)
Order Type:
0: Market order — submitted at 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)
6: Cancel order
Order Validity:
0: Good for the day (default)
1: Fill or kill (FOK) — execute fully immediately or cancel
2: Fill-and-kill (FAK) — execute immediately, cancel any unfilled portion
Stop-loss and take-profit prices are currently not supported (default value: 0).
- final cancel_order(*, symbol=None, orders=None, label=None)#
Cancel orders.
- Parameters:
symbol (_type_, optional) – A STRING scalar, indicating the security code of the orders to be canceled. The default value is None.
orders (_type_, optional) – An INTEGRAL vector, indicating the list of order IDs to be canceled. The default value is None.
label (_type_, optional) – A STRING scalar, indicating the label or remark associated with the orders to be canceled. The default value is None.
- final get_open_orders(symbol=None, orders=None, label=None, output_queue_position=False)#
Query the information of unfilled orders.
If symbol is specified, queries unfilled orders for that security.
If symbol is empty but orders is specified, queries unfilled orders in the provided orders list.
If both symbol and orders are empty, queries unfilled orders specified by label.
- Parameters:
symbol (_type_, optional) – A STRING scalar, indicating the security code. The default value is None.
orders (_type_, optional) – An INTEGRAL vector, indicating a list of order IDs. The default value is None.
label (_type_, optional) – A STRING scalar, indicating a remark or label. The default value is None.
output_queue_position (bool, optional) – A BOOL scalar, indicating whether to output detailed information, including openVolumeWithBetterPrice, openVolumeWithWorsePrice, openVolumeAtOrderPrice, priorOpenVolumeAtOrderPrice, and depthWithBetterPrice. Default is false, indicating no detailed output. This parameter is supported only for stocks and futures.
- Returns:
Returns a dictionary or table.
For all asset types except Shanghai Stock Exchange bonds, the table structure is as follows:
Key
Value Type
Description
orderId
LONG
Order ID
timestamp
TIMESTAMP
Time
symbol
STRING
Symbol code
price
DOUBLE
Order price
totalQty
LONG
Total quantity of the order
openQty
LONG
Remaining quantity of the order
direction
INT
1: Buy open; 2: Sell open; 3: Sell close; 4: Buy close
isMacthing
INT
Indicates whether the order has reached the matching time
openVolumeWithBetterPrice
LONG
Total quantity of unfilled orders with better prices (returned only when
outputQueuePosition = true)openVolumeWithWorsePrice
LONG
Total quantity of unfilled orders with worse prices (returned only when
outputQueuePosition = true)openVolumeAtOrderPrice
LONG
Total quantity of unfilled orders at the same price (returned only when
outputQueuePosition = true)priorOpenVolumeAtOrderPrice
LONG
Total quantity of unfilled orders at the same price placed earlier (returned only when
outputQueuePosition = true)depthVolumeWithBetterPrice
INT
Depth level of unfilled quotes with better prices (returned only when
outputQueuePosition = true)updateTime
TIMESTAMP
Last update time
For Shanghai Stock Exchange bonds, the table structure is as follows:
Name
Type
Description
orderId
LONG
Order ID
time
TIMESTAMP
Timestamp
symbol
STRING
Security code
bidPrice
DOUBLE
Bid price
bidTotalQty
LONG
Total bid quantity placed by the user
bidRemainQty
LONG
Remaining bid quantity of the user order
askPrice
DOUBLE
Ask price
askTotalQty
LONG
Total ask quantity placed by the user
askRemainQty
LONG
Remaining ask quantity of the user order
direction
INT
Trade direction:
1: Buy
2: Sell
3: Two-way
label
STRING
Remarks
- Return type:
- property universe#
Set the symbol pool for the engine.
- final subscribe_indicator(market_data_type, metrics, account_type=AccountType.DEFAULT)#
Set the market data indicators to subscribe.
- Parameters:
market_data_type (MarketDataType) –
The type of market data to subscribe to. Optional values:
SNAPSHOT: Snapshot
TICK: Tick-by-tick order data
KLINE / OHLC: K-line data
TRADE: Tick-by-tick trade details
SNAPSHOT_KLINE / SNAPSHOT_OHLC: Snapshot-based K-line data
metrics (_type_) – Metaprogramming object, can be generated using
sf.meta_code.account_type (AccountType, optional) – A STRING scalar, indicating the account type.