Strategy Guide¶
This document aims to help strategy developers quickly master how to write strategies in AKQuant.
1. Core Concepts (Glossary)¶
For those new to quantitative trading, here are some basic terms:
- Bar (Candlestick): Contains market data for a specific time period (e.g., 1 minute, 1 day), primarily including 5 data points:
- Open: Opening price
- High: Highest price
- Low: Lowest price
- Close: Closing price
- Volume: Trading volume
- Strategy: Your trading robot. Its core job is to continuously watch the market (
on_bar) and then decide whether tobuyorsell. - Context: The robot's "notebook" and "toolbox". It records how much cash and how many positions are currently held, and provides tools for placing orders.
- Position: The quantity of stocks or futures you currently hold. A positive number indicates a long position (buying to hold), and a negative number indicates a short position (selling borrowed securities).
- Backtest: Historical simulation. Testing your strategy using past data to see how much money it would have made if executed in the past.
2. Strategy Lifecycle¶
A strategy goes through the following stages from start to finish:
__init__: Python object initialization. It is not a parameter entry point — declare tunable parameters as inline class fields (see Parameter Declaration), and put context-dependent setup inon_start. You may override__init__to set up your own state and it does not need to accept**kwargs: the engine only passes__init__the arguments its signature can accept, while strategy parameters are always declared in the class body and read throughself.params.on_start: Called when the strategy starts. This is where you typically callself.subscribe()to subscribe to data, and you can also register indicators here. On a warm start, be careful not to overwrite already-restored state. In a backtest, whensymbolsis not passed, symbols subscribed viasubscribe()are folded into the backtest's symbol set; whensymbolsis passed, you may only subscribe to symbols already inside it — subscribing to one outside that set raisesValueError(passingsymbolsmeans "run only these symbols"; see thesymbolsparameter ofrun_backtest). In live trading, subscriptions are forwarded to the market gateway (a warning is logged instead if the broker has no market gateway).on_bar: Triggered when each Bar closes (core trading logic).on_tick: Triggered when each Tick arrives (high-frequency/order book strategies).on_order: Triggered when order status changes (e.g., Submitted, Filled, Cancelled).on_trade: Triggered when a trade execution report is received.on_reject: Triggered when an order entersRejectedstatus.on_before_trading/on_after_trading: Daily trading hooks.on_pre_open: The last valid decision point before the open, for "pre-open signal, current open fill" workflows.on_portfolio_update: Triggered when portfolio snapshot changes.on_error: Triggered when user callback raises an exception, then exception is re-raised by default.on_timer: Called when a timer triggers (needs manual registration). > Recommended: Useself.schedule_daily("14:55:00", "payload").on_stop: Called when the strategy stops, suitable for resource cleanup or result statistics (refer to Backtraderstop/ Nautiluson_stop).on_train_signal: Triggered for rolling training signals (only in ML mode).
2.0 Callback Cheat Sheet¶
| Callback | Trigger timing | Typical usage | Example |
|---|---|---|---|
on_start |
After strategy instance is started | Subscribe symbols, register indicators, initialize runtime state | examples/textbook/ch05_strategy.py |
on_resume |
On warm-start restore, before on_start |
Restore connections, inspect restored state, continue from snapshot | examples/21_warm_start_demo.py |
on_bar |
When each bar closes | Main trading logic, indicator updates, signal generation | examples/01_quickstart.py |
on_tick |
When each tick arrives | High-frequency reactions, tick-level monitoring | examples/51_class_tick_callbacks_demo.py |
on_order |
When order status changes | Track lifecycle, reset state, order-linked orchestration | examples/08_event_callbacks.py |
on_trade |
When a trade report arrives | Execution logging, post-trade risk handling, aggregation | examples/08_event_callbacks.py |
on_reject |
First time an order becomes Rejected |
Log reject reasons, alerting, graceful degradation | examples/50_framework_hooks_demo.py |
on_before_trading |
1ns after the trading day's earliest continuous-auction segment starts (A-shares 09:30; for futures with a night session the trading day starts with the previous trading day's night session, so Monday's trading day fires on Friday at 21:00) | Pre-market checks, trading-date level signal preparation | examples/50_framework_hooks_demo.py |
on_pre_open |
1ns before the trading day's first session segment starts (A-shares before the 09:15 opening call auction; futures with a night session before the previous trading day's 20:55 night auction), never earlier than the previous trading day's end-of-day settlement; same timing in backtest and live | Auction/pre-open signal generation; default NextOpen() orders join the opening call-auction match, which is not the same as broker counter support for auction-specific order types |
examples/52_pre_open_demo.py |
on_bars |
After all bars of a time slice have arrived (backtest: when the slice ends; live: complete or deadline) | Score and rebalance all symbols on every bar | examples/strategies/06_stock_momentum_rotation_bucket.py |
on_cross_section |
After the first complete cross-symbol bar slice of the trading day | Cross-sectional same-cycle rebalance using current-day bars/account state | examples/strategies/09_stock_momentum_rotation_after_bar.py |
on_after_trading |
After end-of-day settlement completes (backtest: at the close; live: close + day_close_delay) |
End-of-day summaries, post-close cleanup, archiving | examples/50_framework_hooks_demo.py |
on_portfolio_update |
Incrementally when portfolio snapshot changes | Monitor cash/equity changes, push UI or alerts | examples/50_framework_hooks_demo.py |
on_error |
When any user callback raises | Record callback source and choose continue vs fail-fast | examples/22_strategy_runtime_config_demo.py |
on_timer |
When a registered timer fires | Scheduled rebalance, pre-market tasks, cadence checks | examples/strategies/07_stock_momentum_rotation_on_timer.py |
on_stop |
When strategy stops | Final summary, resource cleanup, reporting | examples/textbook/ch05_strategy.py |
on_expiry |
After expiry settlement/removal is actually executed | Roll contracts, record settlement, clear expired instruments | examples/49_on_expiry_demo.py |
on_train_signal |
When ML rolling training window is triggered | Train models and swap pending model versions | examples/10_ml_walk_forward.py |
For framework-level hooks such as on_before_trading, on_after_trading, on_portfolio_update, and on_reject, start with examples/50_framework_hooks_demo.py to observe trigger order and logs in one place.
If your use case is "decide before the open, but still fill on this session's open", start with examples/52_pre_open_demo.py instead of trying to emulate it with a generic on_timer.
If you want a single "most common callbacks" script first, start with examples/08_event_callbacks.py; it bundles on_start/on_bar/on_order/on_trade/on_reject/on_timer/on_portfolio_update/on_stop in one place.
For class-style Tick strategies, start with examples/51_class_tick_callbacks_demo.py; if you prefer function-style callbacks, then continue with examples/24_functional_tick_simulation_demo.py.
2.1 Callback Dispatch Contract¶
For each bar/tick/timer event, AKQuant dispatches callbacks in this order:
on_order/on_trade(pluson_rejectwhen status isRejected)- Framework hooks (
on_before_trading/on_after_trading,on_portfolio_update) - User event callback (
on_bar/on_tick/on_timer)
Notes:
on_rejectis emitted once per order id when the order first becomesRejected.- The three trading-day hooks are fired by the engine's trading-day lifecycle timers at fixed times; the timing does not depend on market events and is the same in backtest and live. A backtest chains trading days by the trading day of the next market event: a calendar trading day without any market data fires none of the three hooks, and nothing more is scheduled once data is exhausted. Live sessions fire them for every day in the trading calendar (even days without market data).
on_pre_openfires 1ns before the trading day's first session segment starts (A-shares: before the 09:15 opening call auction, i.e. 09:14:59.999…; futures with a night session: before the previous trading day's 20:55 night auction), and never earlier than the previous trading day's end-of-day settlement. DefaultNextOpen()orders submitted there join the opening call-auction match: matching happens when continuous trading starts, the fill price is the auction price, and the fill time is the first continuous-trading event (the 09:31 bar for A-share minute bars).on_before_tradingfires 1ns after the trading day's earliest continuous-auction segment starts (just after 09:30:00 for A-shares); for night-session symbols the trading day starts with the previous trading day's night session, so Monday's trading day fires on Friday at 21:00. A trading day without a continuous-auction segment does not fire it.on_before_tradingalways use a "previous trading day / previous snapshot only" visibility model; inside these callbacks,get_history(),get_account(), andequitymust not expose the current day's new bar or the current day's updated account view.on_cross_sectionruns after the framework has seen the first complete cross-symbol slice for the trading day; inside this callback, current-day history and the current account snapshot are visible.- Live sessions (including
broker="replay") do not know the day's data in advance, soon_cross_sectionis decided by arrival: it fires after the first dispatched time slice in which every previously seen symbol has had a bar that day (immediately when complete, otherwise afterbars_deadline_seconds, default 5 s). A symbol that has not appeared yet and is outside its trading session (e.g. a product without a night session) is waited for; one that is in session but has no bar is treated as suspended and not waited for. On the first trading day of a session it fires after the first slice reaches its deadline. on_after_tradingis an end/wind-down hook intended for end-of-day statistics, cleanup, and archiving. It fires after end-of-day settlement completes: T+1 positions are already unlocked, the day's unfilled Day orders have expired, and orders submitted inside it belong to the next trading day. Backtest settlement runs at the close; live (run_live) at close +day_close_delay(default 60 seconds). If backtest data ends intraday and the day is never settled, it does not fire. It is a dedicated event at the day's close (after settlement, before the next bar), so aNextOpen()order submitted inside it fills on the next bar rather than one bar later (#324). If your intent is "decide at close, execute at the next open", the clearer place to order ison_bar(next-open) oron_pre_open.TimeInForce.Dayand next-open expiry semantics: end-of-day settlement marks any Day order still unfilled that day asExpired. For aNextOpen()Day order submitted on or after the day's last market event (e.g.on_cross_sectionon daily data), its only matchable slice is the next day's open, which comes after settlement — so the framework spares such an order once, letting it get that next-open fill chance; it only expires at the closing settlement of the trading day it belongs to if it is still unfilled then (e.g. the symbol is suspended, #334). A same-cycleCurrentClose()Day order had its matchable slice on its creation day and so expires at that day's close. Orders submitted at or after the close in a non-continuous session (e.g. on the 15:00 minute bar that ends the closing auction, inon_after_trading, or within the live post-close grace window) belong to the next trading day and do not expire that day, whatever the fill mode. If you want a "decide at close, fill next day" order that is not subject to same-day expiry, just use the defaultGTC.- To branch on the trading session (e.g. futures day/night, call auction vs continuous trading), the framework provides no
on_session_*callbacks; readself.ctx.session(aTradingSessionenum with 7 values:Closed,OpeningAuction,AuctionHold,Continuous,Break,ClosingAuction,PostClose), or useself.is_market_open(),self.session_of(symbol)andself.trading_daydirectly; see 2.2 Trading Sessions and Trading Days. - Inside
on_pre_open, plainbuy/sell/order_target_*calls automatically resolve toNextOpen()semantics unless an explicitfill_modeis provided. on_portfolio_updateis incremental: emitted once at initialization, then only on order/trade or position-relevant price changes.- Use
self.portfolio_update_epsto filter tiny equity/cash changes (default0.0). - Stopping does not flush
on_after_trading: if the day has not completed end-of-day settlement it does not fire (e.g. backtest data ending intraday). - Live (
run_live) vs. backtest teardown: live sessions skip the backtest-only data coverage checks (symbols with no fills all session, warmup never reached, tick-only sessions are all normal in live trading and would produce false warnings). - In live sessions
on_stopfires before the signal source and broker dispatcher are torn down, so it can cancel or close positions; on the error-abort path the broker channel may already be unusable, and delivery of such teardown orders is not guaranteed. on_errorreceives(error, source, payload). Preferself.error_mode = "raise" | "continue"(defaultraise).self.re_raise_on_errorremains as fallback for compatibility.- Prefer
self.runtime_config = StrategyRuntimeConfig(...)as a unified runtime switch entry. - Legacy alias fields and
runtime_configstay synchronized automatically.
2.1.1 Regular Event Dispatch Sequence¶
sequenceDiagram
participant Feed as Market/Timer Event
participant FW as Framework Dispatcher
participant Strategy as User Strategy
Note over Feed,Strategy: Trading-day hooks are fired independently by lifecycle timers:<br/>on_pre_open → on_before_trading → market data → end-of-day settlement → on_after_trading
Feed->>FW: bar / tick / timer arrives
FW->>Strategy: on_order(...)
FW->>Strategy: on_trade(...)
alt order first becomes Rejected
FW->>Strategy: on_reject(...)
end
FW->>Strategy: on_before_trading / on_after_trading
FW->>Strategy: on_cross_section
FW->>Strategy: on_cross_section
FW->>Strategy: on_portfolio_update
alt current event is Bar
FW->>Strategy: on_bar(bar)
else current event is Tick
FW->>Strategy: on_tick(tick)
else current event is Timer
FW->>Strategy: on_timer(payload)
end
2.1.2 Stop-Phase Sequence¶
sequenceDiagram
participant Engine as Engine Stop Phase
participant FW as Framework Dispatcher
participant Strategy as User Strategy
alt backtest
Engine->>FW: _on_stop_internal()
else live
Engine->>FW: _on_stop_live_internal()
end
FW->>Strategy: on_stop()
2.1.3 When To Use on_pre_open¶
Use on_pre_open when:
- You produce signals from auction data, pre-open scans, or final checks right before the open.
- You want default order semantics to mean "fill on this session's open" without exposing a generic
open + 0mode. - You want a semantic callback that clearly communicates intent to other strategy authors.
Do not use a generic on_timer as a substitute when:
- The strategy meaning is specifically "pre-open signal, current open fill".
- You want the framework to preserve this execution intent explicitly.
Roles of nearby hooks:
on_before_trading: trading-day semantic hook, focused on "the day has started".on_pre_open: execution semantic hook, focused on "last chance before the open".on_timer: generic scheduler for cadence tasks, not a dedicated open-fill abstraction.
Recommended template:
class AuctionSignalStrategy(Strategy):
def __init__(self) -> None:
self.pending_dates = set()
def on_start(self) -> None:
self.subscribe("000001")
def on_pre_open(self, event: dict[str, object]) -> None:
trading_date = event["trading_date"]
if trading_date in self.pending_dates:
return
self.pending_dates.add(trading_date)
signal = self.compute_pre_open_signal()
if signal > 0:
# Without an explicit fill_mode, this defaults to NextOpen() semantics.
self.buy("000001", quantity=100)
elif signal < 0:
self.sell("000001", quantity=100)
Practical tips:
- Keep
on_pre_openfocused on the final decision and order submission. - You can prepare scans, candidate lists, and risk checks earlier, but leave the final open-fill decision to
on_pre_open. - If you pass an explicit
fill_mode, the explicit mode wins.
Timing note:
- Within one trading day,
on_pre_open(A-shares 09:14:59.999…) always runs beforeon_before_trading(1ns after 09:30:00), soon_before_tradingcannot prepare for the same day'son_pre_open. - For a true two-stage pattern, prepare in a later callback from the previous trading day and execute in the next trading day's
on_pre_open, for example via a previous-dayon_timeroron_after_trading. - See
examples/53_timer_to_pre_open_demo.py. - The
expected_open_atfield of theon_pre_openevent dict is the trigger time of this call (09:14:59.999… for A-shares), not the opening time.
2.2 Trading Sessions and Trading Days¶
The engine maps each symbol to a session table and uses it to decide which trading session a moment falls in and which trading day it belongs to. Matching, end-of-day settlement, T+1, Day-order expiry and the trading-day hooks all follow this mapping.
Reading it from a strategy
| Expression | Meaning |
|---|---|
self.ctx.session |
Session of the current event (TradingSession enum) |
self.session_of(symbol=None) |
Session of the symbol at this moment, consistent with matching; without symbol it equals ctx.session |
self.is_market_open(symbol=None, include_auction=False) |
Whether the symbol is in continuous trading right now; with include_auction=True the opening call auction, the post-auction hold and the closing call auction also count as open |
self.trading_day |
Trading day of the current moment (datetime.date); None when there is no context yet (e.g. in on_start) |
TradingSession has 7 values: Closed, OpeningAuction (opening call auction), AuctionHold (after the auction, waiting for the open, e.g. A-shares 09:25–09:30), Continuous (continuous trading), Break (lunch break and other pauses), ClosingAuction (closing call auction) and PostClose (a post-close segment in a custom session table).
Trading-day rules:
- Intraday events belong to the current trading day; night sessions belong to the next trading day (Friday 21:30 belongs to the following Monday).
- From the close until the next trading day's open (e.g. a 15:30 timer) the time belongs to the next trading day, consistent with daily risk budgets such as daily loss limits.
- Live post-close grace: in live trading (including replay), market data arriving within
day_close_delayseconds after the close and before the next trading day's first session segment still belongs to the current day. The grace never crosses the next trading day's open, so session tables such asALWAYS_OPEN, where the close is immediately followed by the next open, effectively have no grace unless an explicit calendar leaves a gap;day_close_delay=0also disables it. During the grace windowctx.trading_dayis the current day and the session isClosed(PostCloseif the custom table has a post-close segment); nothing is matched, no equity point is produced, and the next trading day is not opened early. Day orders submitted in the grace window still belong to the next trading day. Backtests are unaffected.
from akquant import Strategy
class SessionAwareStrategy(Strategy):
def on_bar(self, bar):
if not self.is_market_open(bar.symbol):
return # Do not chase during call auctions, breaks or when closed
self.log(f"{self.trading_day} {self.ctx.session} {bar.close}")
Session tables and trading calendar (sessions= / trading_calendar=)
Both run_backtest and run_live accept these two parameters:
sessions: symbol prefix → session template name or custom session table;"default"is the global default. When omitted, China time zones use per-asset defaults (stocks/fundsCN_STOCK, futuresCN_FUTURES_DAY, optionsCN_OPTION, other assetsALWAYS_OPEN); other time zones trade continuously all day (ALWAYS_OPEN). List the templates withaq.SessionResolver.templates(); futures with a night session must be set explicitly, e.g.sessions={"rb": "CN_FUTURES_NIGHT_23"}. For the custom table format see the API Reference.trading_calendar: list of trading days (date/ string /Timestamp); usually not needed. When omitted: China time zones use the built-in exchange calendar (the holiday schedule of the Chinese stock and futures exchanges, updated with each release; seeSessionResolver.builtin_calendar_range()for its coverage), so holidays are not trading days; backtests additionally treat every date that has data as a trading day. For dates beyond the built-in coverage, and for custom session tables outside China time zones, backtests follow the data (a weekday on which no symbol has data is not a trading day), while live mode infers trading days from weekdays and warns once.ALWAYS_OPENcounts every day.
import akquant as aq
result = aq.run_backtest(
data=df,
strategy=MyStrategy,
sessions={"rb": "CN_FUTURES_NIGHT_23"},
# Exchange trading days; must cover the data range
trading_calendar=["2024-01-02", "2024-01-03", "2024-01-04"],
)
Live notes:
- Session-aware order queueing only happens in the simulated matching of paper/replay: orders submitted while closed, on break, or during a call auction are queued and not filled as continuous trading. Under
broker_liveorders go straight to the broker counter without session queueing; the session table only determinesctx.session,is_market_open(), the trading-day split, and the timing of end-of-day settlement and the trading-day hooks. - Futures without
sessionsuse theCN_FUTURES_DAYday-session table, so night-session data is classified as closed (under paper, orders are queued until the day session); symbols with a night session must passsessions=. - Live sessions without
trading_calendar=use the built-in exchange calendar, so holidays are neither opened nor settled. The built-in calendar is updated with each release; if it expires within 30 days (or has expired) a warning is logged once at startup — upgrade AKQuant or passtrading_calendar=. Custom session tables outside China time zones have no built-in calendar: long-running sessions must pass one, otherwise trading days are inferred from weekdays and holidays are opened and settled (a warning is logged once at startup). Since live_server 0.12.0, klinedata sessions also fetch the SSE/SZSE trading calendar from the market-data service and pass it in automatically. run_live(timezone=)must match the exchange; the end-of-day settlement time and the default session tables are computed in it.
3. Utilities¶
AKQuant provides a set of utilities to simplify strategy development.
3.1 Logging¶
Use self.log() to output logs with the current backtest timestamp, which is useful for debugging.
def on_bar(self, bar):
# Automatically adds timestamp, e.g., [2023-01-01 09:30:00] Signal: Buy
self.log("Signal: Buy")
# Support logging level
import logging
self.log("Insufficient funds", level=logging.WARNING)
When log handlers are configured through akquant.configure_logging(...) or akquant.register_logger(...), self.log() also carries structured context that is useful in live profile output and file logs:
phase: current stage such asstrategy,order, ortradestrategy_id/slot: strategy identity in multi-strategy runssymbol: current instrumentevent_time: strategy event timeorder_id/client_order_id: auto-filled insideon_order/on_trade/on_reject
The simplest option remains the compatibility helper:
For clearer research / optimize / live separation, prefer the structured config API:
import akquant
akquant.configure_logging(
akquant.LogConfig(
profile="live",
level="INFO",
console=True,
filename="logs/strategy.log",
file_level="DEBUG",
file_json=True,
file_max_bytes=10_000_000,
file_backup_count=5,
)
)
If you want to ship logs into a log pipeline or collector, you can enable JSON output per handler:
console_json=True: console emits JSON linesfile_json=True: file emits JSON lines
Practical guidance:
- Use
self.log()for human-readable strategy debugging - Use
run_backtest(..., on_event=...)when you need a machine-consumableorder/trade/progress/riskevent stream - Inside
on_order,on_trade, andon_reject, you usually do not need to manually concatenate order ids into the message - Once an
akquantlogger handler is enabled, Rust execution-path warnings also flow through the same pipeline. That includes insufficient-margin rejects, session-close expiry, unknown cancel requests, and same-slicesame-cycledeferrals, typically withphase=executionplus fields such assymbol,order_id,strategy_id,slot, andevent_time_isowhen available;event_time_isois always emitted as UTC ISO 8601
Log level semantics¶
AKQuant standardizes level semantics so you can filter and alert consistently:
| Level | Meaning | Trading example |
|---|---|---|
DEBUG |
Fine-grained diagnostics, enabled only while troubleshooting | Cleanup/inference fallbacks |
INFO |
Key operational milestones | Order submit/fill/cancel audit, training progress, snapshot saved |
WARNING |
Recoverable degradation, unexpected but not fatal | Insufficient-margin reject, ignored non-cancellable order, invalid data field falling back to default |
ERROR |
An operation failed and cannot recover | A custom matcher raised so the order was not executed; Parquet stream read/parse failure (samples truncated) |
CRITICAL |
System-level fatal, needs immediate human attention | Live trading front disconnected (cannot place orders); the live runner stops on an uncaught exception |
CRITICALis reserved for "the framework can no longer safely perform its core job". In production, routeCRITICALto a dedicated alert channel (SMS/phone), separate from ordinary logs.
Order auditing & sensitive data¶
- Order-lifecycle auditing: under
broker_live, every order's submit / update / fill / cancel / reject is logged as a structured INFO record under theakquant.audit.ordernamespace (withclient_order_id,order_id,event,price,quantity, …). SetLogConfig(order_audit_file="logs/orders_audit.log")to also persist a dedicated audit JSON stream for reconciliation and post-mortem — the full order lifecycle can be reconstructed from that file alone, even after the process stops. - Sensitive masking: logs mask credential-class fields (
password/token/api_key, …) fully and account-class fields (user_id/account, …) keeping the last 4 chars, by default. This is a handler-layer backstop; disable withLogConfig(mask_sensitive=False).
In the console, audit messages are self-contained (e.g. fill Buy 100 600000.SH @10.55 [C1->B1 T1]) and skip the redundant structured suffix; the full structured fields still go to the JSON audit file for machine consumption.
Log language (english by default, optional zh console)¶
Logs follow industry practice (cf. nautilus_trader / structlog): messages are english by default — a searchable, collaboration-friendly contract consumable by alerting/log systems; structured fields stay english too (event=order_fill, side, price, …), unaffected by the switch. If you prefer a Chinese console, set language="zh":
It only re-renders the console order-audit line from the structured fields; files and JSON audit streams stay english, so grep/reconciliation/alerting never fork by language. Free-text diagnostic logs (connect/login/settlement, …) stay english regardless.
Recommended live logging config¶
For a high-frequency live strategy the per-order audit (submit/update/fill) at INFO would flood the console. Raise the console to WARNING (only human-relevant events) and send the full INFO audit to order_audit_file:
import akquant
akquant.configure_logging(
akquant.LogConfig(
profile="live",
console=True,
console_level="WARNING", # console only keeps human-relevant events
filename="logs/live.log", # main log (incl. INFO) to file
file_level="INFO",
order_audit_file="logs/orders_audit.log", # dedicated order-audit JSON stream
order_audit_level="INFO",
# language="zh", # optional: Chinese console audit lines (files stay english)
)
)
3.2 Data Access (Syntactic Sugar)¶
The Strategy class provides properties for quick access to current Bar/Tick data:
| Property | Description | Original Code |
|---|---|---|
self.symbol |
Current symbol | bar.symbol / tick.symbol |
self.close |
Current price | bar.close / tick.price |
self.open |
Current open price | bar.open (0 in Tick mode) |
self.high |
Current high price | bar.high (0 in Tick mode) |
self.low |
Current low price | bar.low (0 in Tick mode) |
self.volume |
Current volume | bar.volume / tick.volume |
Example:
def on_bar(self, bar):
# Old way
if bar.close > bar.open: ...
# New way (Cleaner)
if self.close > self.open:
self.buy(self.symbol, 100)
3.3 Timer¶
In addition to the low-level schedule method, AKQuant provides more convenient ways to register timers:
schedule_daily(time_str, payload): Triggers at a specified time on every trading day of the trading calendar (not on non-trading days; in a backtest also on trading days without data inside the data range).- Same semantics in backtest and live: Backtests pre-generate all triggers over the calendar trading days covered by the data; live mode registers only the next trigger and reschedules it along the trading calendar.
- Default calendar without
trading_calendar: China time zones use the built-in exchange calendar (no triggers on holidays); in backtests every date that has data also counts as a trading day, and dates beyond the built-in coverage or custom session tables outside China time zones follow the data.ALWAYS_OPEN(the default outside China time zones) counts every day: backtests only use days that have data (no weekend triggers when weekends have no bars), while live mode fires on weekends too and warns once; passtrading_calendarfor markets closed on weekends such as US equities. - First-day rule: In backtests, tasks registered in
on_starttake effect from the first market-data event; earlier times on the first day do not fire. In live mode they are also registered on lifecycle events such as pre-open, provided the strategy overrides one ofon_pre_open/on_before_trading/on_after_trading; otherwise lifecycle events are not dispatched to the strategy and tasks are registered on the first market-data event.
schedule_weekly(time_str, payload)/schedule_monthly(time_str, payload): Trigger on the first trading day of each week/month (per the trading calendar, rolling over holidays), in both backtest and live; live mode reschedules to the first trading day of the next week/month.schedule(trigger_time, payload): Triggers once at a specified datetime.
def on_start(self):
# Daily check at 14:55:00
self.schedule_daily("14:55:00", "daily_check")
# Specific event
self.schedule("2023-01-01 09:30:00", "special_event")
def on_timer(self, payload):
if payload == "daily_check":
self.log("Running daily check...")
3.4 Recommended Cross-Section Pattern¶
AKQuant triggers on_bar in single-event flow. For cross-sectional tasks such as rotation, ranking, and scoring across symbols, place decision logic in on_timer.
Recommended flow:
- Define the
universeinon_startand register a daily timer. - Compute cross-sectional scores in
on_timer. - Rebalance in
on_timerso each decision timestamp runs once.
class CrossSectionStrategy(Strategy):
lookback = IntParam(20, ge=1, le=500, title="Lookback window")
def on_start(self):
self.universe = ["sh600519", "sz000858", "sh601318"]
self.warmup_period = self.params.lookback + 1
self.schedule_daily("14:55:00", "rebalance")
def on_timer(self, payload):
if payload != "rebalance":
return
scores = {}
for symbol in self.universe:
closes = self.get_history(count=self.params.lookback, symbol=symbol, field="close")
if len(closes) < self.params.lookback:
return
scores[symbol] = (closes[-1] - closes[0]) / closes[0]
best = max(scores, key=scores.get)
self.order_target_percent(target_percent=0.95, symbol=best)
Full runnable samples: examples/strategies/05_stock_momentum_rotation_timer.py for on_before_trading, examples/strategies/09_stock_momentum_rotation_after_bar.py for on_cross_section, or examples/strategies/07_stock_momentum_rotation_on_timer.py for a fixed-time on_timer variant.
3.5 Cross-Section Plan B: Once Per Time Slice (on_bars)¶
When every bar (daily or minute) needs one pass over all symbols, override on_bars(batch): the framework calls it once after all bars sharing a timestamp have arrived. (Experimental; the interface may change.)
from akquant import BarBatch
class CrossSectionBarsStrategy(Strategy):
lookback = IntParam(20, ge=1, le=500, title="Lookback window")
def on_start(self):
self.warmup_period = self.params.lookback + 1
def on_bars(self, batch: BarBatch):
scores = {}
for bar in batch: # only symbols with a bar in this slice, sorted by symbol
closes = self.get_history(count=self.params.lookback, symbol=bar.symbol, field="close")
scores[bar.symbol] = (closes[-1] - closes[0]) / closes[0]
best = max(scores, key=lambda s: scores[s])
self.order_target_percent(target_percent=0.95, symbol=best)
| Member | Meaning |
|---|---|
batch.timestamp |
Slice time in nanoseconds (the timestamp of every bar in it) |
batch.bars / for bar in batch |
Bars of the slice, sorted by symbol |
batch["600000"] / batch.get("600000") / "600000" in batch |
Lookup by symbol; the first raises KeyError when absent, get returns None |
batch.symbols |
Symbols that have a bar in this slice |
batch.missing |
Symbols seen earlier that have no usable bar in this slice (suspended, no trades, late, or still in warmup); symbols never seen are not listed |
batch.flush_reason |
"boundary" / "complete" / "watermark" / "deadline" |
When it fires:
- Backtest (and
broker="replay"): when the slice ends, before the next one starts ("boundary"). Slices with missing bars still fire, and so does the last slice. Orders placed in it fill like orders placed in the laston_barof the slice: at the open of the next bar by default, at the close of this slice withCurrentClose(). - Live: as soon as every previously seen symbol has arrived (
"complete"); otherwise at slice time +bars_deadline_seconds("deadline"); a bar of a later slice arriving before the deadline also fires it ("watermark"; history already includes that later bar). The first slice has no earlier symbol set to compare against, so it waits for the deadline. bars_deadline_secondsis a strategy class attribute, default 5 seconds. It must exceed the flush delay of the data source: gateways that build bars locally from quotes (e.g. klinedata) emit the bar of a symbol with no further quotes 2–3 seconds after the bar ends. With a suspended symbol, every live slice waits the full deadline.- Bars arriving after the deadline only trigger
on_bar; they are not added to the batch already dispatched (one warning per symbol). The last undispatched slice is dropped when a live session stops.
Notes:
- When
on_baris also overridden,on_barruns for each bar first, thenon_bars. - Base-frequency bars only; window bars from
subscribe_barsare not included. Bars still in warmup are left out (the symbol is listed inbatch.missing); slices whose bars are all in warmup do not fire. - The callback belongs to no single symbol:
self.current_barisNone; read multi-symbol indicators withind.of(symbol)[0]. - Function style:
run_backtest(..., on_bars=fn)/run_live(..., on_bars=fn)withfn(ctx, batch).
Do not count bars yourself in on_bar
Buffering by timestamp in on_bar and running once all symbols are collected silently skips every slice in which one symbol is suspended or has no bar. Processing the previous slice when the next timestamp shows up is wrong too: the first bar of the next slice is already in history by then, so you read future data, and the last slice never fires.
Full runnable sample: examples/strategies/06_stock_momentum_rotation_bucket.py.
3.6 Decision Matrix (A vs B)¶
| Dimension | Plan A: day-boundary hooks / on_timer |
Plan B: on_bars |
|---|---|---|
| Trigger | Once per trading day, or a fixed time (e.g., 14:55) | Once per time slice |
| Symbols without a bar | Do not affect the trigger | Do not affect the trigger; listed in batch.missing |
| Complexity | Low | Low |
| Best for | Daily/timed rebalances | Cross-symbol work on every bar (intraday rotation, cross-sectional factors) |
| Common risk | Timer time not aligned with data frequency | Live deadline shorter than the flush delay of the data source, so batches always miss symbols |
Recommendation: use Plan A for daily or fixed-time rebalances; use Plan B when every bar needs processing.
3.7 Cross-Section Pitfall Checklist¶
- Suspensions / missing bars:
on_barsstill fires when some symbols have no bar; they are listed inbatch.missing. Decide before scoring whether to skip them or carry the previous value. - Universe drift: If constituents change but your universe list is stale, weights and ranks diverge from target; refresh periodically and track effective date.
- Rebalance time vs fill mode mismatch: With
fill_policy=NextOpen(), close-time signals are filled on the next bar; useCurrentClose(timer_fill_timing=...)to make timer fill timing explicit. - Insufficient history windows: Newly listed or recently resumed symbols may fail window requirements; check
len(closes)and skip invalid samples. - Position convergence lag: Multi-asset sell-then-buy cycles can leave partial allocations in one event; use target-position APIs and converge again on next cycle.
For full pre-live checks, see: Cross-Section Strategy Playbook Checklist.
4. Choosing a Strategy Style¶
AKQuant provides two styles of strategy development interfaces:
For style selection guidance, see Strategy Style Decision Guide.
| Feature | Class-based Style (Recommended) | Function-based Style |
|---|---|---|
| Definition | Inherit from akquant.Strategy |
Define initialize + on_bar (required), optional on_start / on_stop / on_tick / on_order / on_trade / on_timer |
| Scenarios | Complex strategies, need to maintain internal state, production | Rapid prototyping, migrating Zipline/Backtrader strategies |
| Structure | Object-oriented, good logic encapsulation | Script-like, simple and intuitive |
| API Call | self.buy(), self.ctx |
ctx.buy(), pass ctx as parameter |
4.1 Function-style Callback Trigger Conditions¶
| Callback | Trigger Condition | Notes |
|---|---|---|
on_bar(ctx, bar) |
Backtest feed emits Bar events | Required entry callback for function-style strategies |
on_start(ctx) |
Backtest starts | Aligns with class-style on_start lifecycle |
on_stop(ctx) |
Backtest ends | Aligns with class-style on_stop lifecycle |
on_tick(ctx, tick) |
Backtest feed emits Tick events | Tick callbacks are not triggered in bar-only datasets |
on_order(ctx, order) |
Order state changes are observed in strategy context | Triggered before event callback in each event loop |
on_trade(ctx, trade) |
Trade reports appear in recent_trades |
Trade dedupe applies to avoid repeated callbacks |
on_pre_open(ctx, event) |
1ns before the trading day's first session segment starts, fired by the trading-day lifecycle timer (A-shares 09:14:59.999…) | Suits function-style "pre-open decision, current open fill" workflows |
on_timer(ctx, payload) |
A timer is scheduled and fired | Includes both one-shot and daily timer payloads |
4.2 Class vs Function Callback Mapping¶
| Class-based | Function-style | Notes | Recommended Example |
|---|---|---|---|
on_start(self) |
on_start(ctx) |
Lifecycle entry point, supported by both styles | examples/08_event_callbacks.py, examples/23_functional_callbacks_demo.py |
on_stop(self) |
on_stop(ctx) |
Lifecycle exit point, supported by both styles | examples/textbook/ch05_strategy.py |
on_bar(self, bar) |
on_bar(ctx, bar) |
Primary strategy entry, supported by both styles | examples/01_quickstart.py, examples/23_functional_callbacks_demo.py |
on_tick(self, tick) |
on_tick(ctx, tick) |
Tick entry, supported by both styles | examples/51_class_tick_callbacks_demo.py, examples/24_functional_tick_simulation_demo.py |
on_order(self, order) |
on_order(ctx, order) |
Order state callback, supported by both styles | examples/08_event_callbacks.py |
on_trade(self, trade) |
on_trade(ctx, trade) |
Trade report callback, supported by both styles | examples/08_event_callbacks.py |
on_expiry(self, event) |
on_expiry(ctx, event) |
Expiry settlement callback, supported by both styles | examples/49_on_expiry_demo.py |
on_timer(self, payload) |
on_timer(ctx, payload) |
Timer callback, supported by both styles | examples/08_event_callbacks.py, examples/23_functional_callbacks_demo.py |
on_resume(self) |
Not supported | Warm-start restore hook, currently class-style only | examples/21_warm_start_demo.py |
on_reject(self, order) |
Not supported | Reject callback, currently class-style only | examples/08_event_callbacks.py, examples/50_framework_hooks_demo.py |
on_before_trading(self, trading_date, timestamp) |
on_before_trading(ctx, trading_date, timestamp) |
Trading-day boundary hook, supported by both styles | examples/50_framework_hooks_demo.py |
on_after_trading(self, trading_date, timestamp) |
on_after_trading(ctx, trading_date, timestamp) |
Trading-day boundary hook, supported by both styles | examples/50_framework_hooks_demo.py |
on_bars(self, batch) |
on_bars(ctx, batch) |
Batch callback fired once per time slice, supported by both styles | examples/strategies/06_stock_momentum_rotation_bucket.py |
on_cross_section(self, trading_date, timestamp) |
on_cross_section(ctx, trading_date, timestamp) |
Current-day-aware cross-sectional rebalance hook, supported by both styles | examples/strategies/09_stock_momentum_rotation_after_bar.py |
on_portfolio_update(self, snapshot) |
on_portfolio_update(ctx, snapshot) |
Portfolio snapshot callback, supported by both styles | examples/50_framework_hooks_demo.py |
on_error(self, error, source, payload) |
on_error(ctx, error, source, payload) |
User exception callback, supported by both styles | examples/22_strategy_runtime_config_demo.py |
on_train_signal(self, context) |
on_train_signal(ctx) |
ML rolling-train hook, supported by both styles | examples/10_ml_walk_forward.py |
Recommendations:
- Choose class-based style when you want the most discoverable place to organize many framework hooks in one strategy object.
- Choose function-style when you prefer lightweight scripting; it also supports framework hooks such as
on_before_trading,on_after_trading,on_cross_section,on_portfolio_update, andon_error.
4.3 Related Examples¶
- Function-style callback baseline:
examples/23_functional_callbacks_demo.py - Function-style tick callback simulation:
examples/24_functional_tick_simulation_demo.py - run_live supports function-style entry and multi-slot orchestration:
run_live(strategy_cls=on_bar, strategy_id="alpha", strategies_by_slot={"beta": OtherStrategy}, initialize=..., on_tick=..., on_order=..., on_trade=..., on_timer=...) - For backtest multi-slot and strategy-level risk mapping, prefer centralized
BacktestConfig(strategy_config=StrategyConfig(...)):docs/en/advanced/multi_strategy_guide.md - broker_live function-style submit example:
examples/39_live_broker_submit_order_demo.py - Function-style multi-slot + risk example:
examples/40_functional_multi_slot_risk_demo.py - run_live multi-slot orchestration example:
examples/41_live_multi_slot_orchestration_demo.py - Output markers:
done_functional_callbacks_demodone_functional_tick_simulation_demo
4. Writing Class-based Strategies¶
This is the recommended way to write strategies in AKQuant, offering a clear structure and easy extensibility.
from akquant import Strategy, Bar, IntParam
import numpy as np
class MyStrategy(Strategy):
# Tunable params are declared as inline class fields; the constructor
# signature is NOT a parameter entry point since 0.3.x
ma_window = IntParam(20, ge=2, le=500, title="MA window")
def on_start(self):
# Explicitly subscribe to data
self.subscribe("600000")
def on_bar(self, bar: Bar):
# 1. Get historical data (Online mode)
# Get the last N closing prices
history = self.get_history(count=self.params.ma_window, symbol=bar.symbol, field="close")
# Check if data is sufficient
if len(history) < self.params.ma_window:
return
# Calculate Moving Average
ma_value = np.mean(history)
# 2. Trading Logic
# Get current position
pos = self.get_position(bar.symbol)
if bar.close > ma_value and pos == 0:
self.buy(symbol=bar.symbol, quantity=100)
elif bar.close < ma_value and pos > 0:
self.sell(symbol=bar.symbol, quantity=100)
Retained length (how many bars of history the framework keeps per symbol): in a backtest it is the largest of history_depth, warmup_period and the warmup inferred from your indicators. In a live session (run_live) it follows history_depth; warmup_period does not set the history depth directly. With auto-preload on (the feed offers a history_provider, as klinedata does by default), it only feeds into the preload count (the largest of 3 × the inferred warmup, 500, warmup_period and history_depth, capped), and once the preload is done history is enabled at the number of bars actually preloaded. Without a preload, get_history raises "History tracking is not enabled" until set_history_depth is called. Live strategies that read history should call self.set_history_depth(N) explicitly.
Set the history depth in __init__ / on_start: if set_history_depth(N) is first called mid-run (after the session has started), the bars before the call are not backfilled; the window becomes complete only after another N bars.
When count exceeds the retained length, the history grows automatically and warns once: the first time get_history / get_history_df asks for a larger count, the framework grows the retained length to count and logs a warning with the value to set; data dropped before the growth cannot be recovered, so the window is complete only from count bars later. Call self.set_history_depth(N) in on_start as the warning suggests (this takes effect in both backtests and live sessions). NaN padding during warmup (not enough data yet) is normal and does not warn. Automatic growth is capped at the larger of 10000 and the history_depth / warmup_period you declared explicitly: beyond the cap it no longer grows, warns once on its own, and pads with NaN as before, so a count that keeps increasing (such as get_history(self.bars_held)) cannot grow the buffer without bound in a live session.
5. Orders & Execution¶
4.1 Order Lifecycle¶
In AKQuant, order status transitions are as follows:
- New: Order object is created.
- Submitted: Order has been sent to the exchange/simulation matching engine.
- Accepted: (Live mode) Exchange confirms receipt of the order.
- Filled: Order is fully filled.
- PartiallyFilled: Partially filled (
filled_quantity < quantity).
- PartiallyFilled: Partially filled (
- Cancelled: Order has been cancelled.
- Rejected: Order rejected by risk control or exchange (e.g., insufficient funds, exceeding price limits).
5.2 Common Trading Commands¶
- Market Order:
- Limit Order: Executes at a specified price, only when the market price is at or better than the specified price.
- Stop Order:
Converts to a market order when the market price touches the trigger price (
trigger_price). -
Target Orders: Automatically calculates buy/sell quantities to adjust the position to a target value.
The delta is computed against the projected position — the settled position plus the expected effect of all in-flight orders from the same bar. This is what makes repeated calls within one bar converge: after
close_position()has queued a full exit, a followingorder_target_*()sees a projected position of zero rather than the stale settled one (computing against the settled position would add a second same-direction order on top of the exit, selling more than held).Rebalance multiple symbols with a single target-weight call:# Adjust position to 50% of total assets self.order_target_percent(target_percent=0.5, symbol="AAPL", price=None) # Adjust holding to 1000 shares (Buy 1000 if 0, Sell 1000 if 2000) self.order_target_value(target_value=1000 * price, symbol="AAPL") # Note: API does not support target_share directly yet, simulate with valueBy default the sum of weights must beself.rebalance_weights( target_weights={"AAPL": 0.4, "MSFT": 0.3, "GOOGL": 0.2}, liquidate_unmentioned=True, rebalance_tolerance=0.01, )<= 1.0; setallow_leverage=Trueto allow higher aggregate exposure. Orders are submitted sell-first and then buy-second to reduce cash-lock conflicts during rotation. * Cancel Order:self.cancel_order(order_id) # Cancel specific order self.cancel_group(receipt) # Cancel every leg of one logical order self.cancel_all_orders() # Cancel all open orderscancel_orderaccepts an order id, theOrderReceiptreturned when the order was placed, or an order object such as the ones returned byget_open_orders(); any other type raisesTypeError.cancel_groupaccepts agroup_idor anOrderReceipt.
OrderReceipt: the return value of an order call¶
buy() / sell() / submit_order() all return an OrderReceipt (the same type in
backtest and in broker_live trading; it is no longer a bare str order id):
receipt.primary: the order id of the first leg. In most cases this is "the order id of this call", equivalent to thestrolder versions returned.receipt.order_ids: the order ids of all legs. A singleside + position_effect="auto"call made while holding the opposite position is split into acloseleg and anopenleg (orclose_today/close_yesterdayfor futures), soorder_idscan hold more than one id andprimaryis only one of them.str(receipt): thegroup_idof the logical order, which ties the split legs together as one call. It lives in a different id space fromreceipt.primary; do not mix the two.- When matching fills, prefer
trade.group_idover comparing individual order ids, so that fills aggregate correctly whether or not the order was split.
A reversal across close + open (both legs are sent by one buy() / sell() call):
def on_bar(self, bar):
# Holding a short position; buying 300 splits into "cover 200" + "open long 100"
receipt = self.buy(bar.symbol, quantity=300) # position_effect defaults to "auto"
print(receipt.primary) # order id of the first (closing) leg
print(receipt.order_ids) # (closing leg id, opening leg id)
print(str(receipt)) # group_id of this logical order
# Cancel the whole order (both legs):
self.cancel_group(receipt) # same as self.cancel_group(str(receipt))
def on_trade(self, trade):
# Aggregate the fills of one logical order by group_id, not by single order id
if trade.group_id == self._entry_group_id:
...
Position effect (open vs close)¶
An order carries side + position_effect, not just side:
buy()/sell()default toposition_effect="auto"and split intoclose + openlegs before execution, sized against the closable position — the settled position minus what in-flight close/reduce orders from the same bar already claim. This is what makes a flip split correctly: afterclose_position()claims the closable quantity, a followingbuy()is classified asopenrather than a secondclose.short()isside="Sell", position_effect="open";cover()isside="Buy", position_effect="close".- Explicit control:
self.submit_order(..., position_effect="open" | "close" | "close_today" | "close_yesterday"). Underbroker_live + CTPthese map to the counter's offset flags.
In-flight open orders are deliberately not projected here: they may never fill, and
ignoring them biases the split toward open, i.e. toward reserving more margin. Note the
contrast with target orders above, which project all in-flight orders — the two answer
different questions ("how much can still be closed" vs "where will the position end up").
The resulting legs are visible in orders_df.position_effect (at submission) and
executions_df.position_effect (after the fill).
5.3 Execution Policy (Fill Mode)¶
Pass a FillMode object via run_backtest(..., fill_policy=...), or at order level via fill_mode=. The five named modes are:
NextOpen(): fill at the next bar's open (default; no look-ahead).NextClose(): fill at the next bar's close.NextAverage(): fill at the next bar's OHLC4 average.NextHighLowMid(): fill at the next bar's HL2 midpoint.CurrentClose(): fill at the current bar's close. UseCurrentClose(timer_fill_timing="deferred")to defer timer-triggered fills to the next event (default"immediate").
At the engine level, set it via engine.set_fill_mode(mode, timer_timing), where mode is an akquant.ExecutionMode value and timer_timing is "same_cycle" or "next_event".
5.4 Event Callbacks¶
AKQuant provides a callback mechanism similar to Backtrader for tracking order status and trade records.
5.4.1 Order Status Callback (on_order)¶
Triggered when order status changes (e.g., from New to Submitted, or to Filled).
In broker_live with CTP, the default execution semantics is strict: terminal states are confirmed by OnRtnOrder. For example, a cancel request does not imply Cancelled until OnRtnOrder(Cancelled) arrives.
from akquant import OrderStatus
def on_order(self, order):
if order.status == OrderStatus.Filled:
print(f"Order Filled: {order.symbol} Side: {order.side} Qty: {order.filled_quantity}")
elif order.status == OrderStatus.Cancelled:
print(f"Order Cancelled: {order.id}")
5.4.2 Trade Execution Callback (on_trade)¶
Triggered when a real trade occurs. Unlike on_order, on_trade contains specific execution price, quantity, and commission information.
def on_trade(self, trade):
print(f"Trade Execution: {trade.symbol} Price: {trade.price} Qty: {trade.quantity} Comm: {trade.commission}")
5.4.3 Expiry Settlement Callback (on_expiry)¶
Triggered only after the engine actually executes an expiry_date driven settlement/removal. The callback receives an event dict, and portfolio state is already updated when it runs.
Settlement happens in the end-of-day settlement at the close of the expiry day, using the expiry-day close, and on_expiry is delivered at that day's on_after_trading time. cash_flow is gross; fee is the option exercise fee, so the account receives cash_flow - fee (for margin-account futures, cash_flow is the realized close-out P&L instead). When backtest data ends intraday on the expiry day, the catch-up settlement at the end of the backtest also fires this callback (and the streaming expiry event), including across checkpoint-split runs. Expiry closes are also recorded as a synthetic trade in trades_df (order_tag="__expiry__"), but do not appear in orders_df.
Runnable example: examples/49_on_expiry_demo.py.
def on_expiry(self, event):
print(
"Expiry:",
event["symbol"],
event["expiry_date"],
event["quantity_closed"],
event["cash_flow"],
event["fee"],
event.get("settlement_type"),
)
5.5 Account & Position Query¶
In addition to get_position, you can query more account information:
self.equity: Current account equity (Cash + Market Value of Positions).self.get_trades(): Get all historical closed trades.self.get_open_orders(): Get current open orders.self.get_available_position(symbol): Get available position (considering T+1 rule).self.position.entry_price: Get the current symbol's average entry price from thePositionhelper.self.position.avg_price: Alias ofentry_price.self.ctx.get_position_entry_price(symbol): Get average entry price for a specific symbol.
self.get_position(symbol) still returns a numeric quantity. If you need average entry price, use the Position helper or self.ctx.get_position_entry_price(symbol).
def on_bar(self, bar):
pos = self.position
if pos.size > 0 and pos.entry_price > 0:
pnl_pct = (bar.close - pos.entry_price) / pos.entry_price
5.6 Instrument Static Metadata Query (Recommended)¶
When strategy logic needs static fields like strike, expiry, multiplier, option type, or underlying symbol, prefer Strategy APIs instead of bar.extra.
Available APIs:
self.get_instrument(symbol): ReturnsInstrumentSnapshot.self.get_instrument_field(symbol, field): Returns one field value.self.get_instrument_config(symbol, fields=None): Compatibility API for single or batch field access.self.get_instruments(symbols=None): Returns snapshot dict for multiple symbols.
These APIs are available in on_start: backtest injects snapshots from InstrumentConfig, live (run_live) injects them from the Instrument list you pass in.
Field coverage differs between the two. The live entry point only accepts Instrument objects, and option_type / strike_price / expiry_date / underlying_symbol / settlement_* exist there only as constructor arguments — they cannot be read back — so those fields are None in live snapshots. The expiry_date / strike_price reads in the example below work in backtest; live strategies must pass them in via strategy params or context. See InstrumentSnapshot for the field list.
from akquant import Bar, Strategy
class MetaAwareStrategy(Strategy):
def on_start(self):
self.subscribe("OPTION_A")
expiry = self.get_instrument_field("OPTION_A", "expiry_date")
strike = self.get_instrument_field("OPTION_A", "strike_price")
print("meta:", expiry, strike)
def on_bar(self, bar: Bar):
meta = self.get_instrument_config(
bar.symbol, fields=["asset_type", "option_type", "multiplier"]
)
if meta["asset_type"] == "OPTION" and meta["option_type"] == "CALL":
pass
6. Risk Management¶
AKQuant has a built-in Rust-level risk manager that can simulate exchange or broker risk control rules during backtesting.
from akquant import RiskConfig
# Set after Engine initialization
risk_config = RiskConfig()
risk_config.active = True
risk_config.max_order_value = 1_000_000.0 # Max 1 million per order
risk_config.max_position_size = 5000 # Max 5000 shares per symbol
risk_config.restricted_list = ["ST_STOCK"] # Blacklist (Symbol)
risk_config.max_account_drawdown = 0.20 # Reject new orders after 20% drawdown
risk_config.max_daily_loss = 0.05 # Reject new orders after 5% daily loss
risk_config.stop_loss_threshold = 0.80 # Reject new orders if equity < 80% baseline
engine.risk_manager.config = risk_config # Apply config
If an order violates risk rules, functions like self.buy() will return None or the generated order status will be directly Rejected, and the reason will be recorded in the logs.
You can also pass account-level rules directly in run_backtest:
from akquant import run_backtest
from akquant.config import RiskConfig
result = run_backtest(
data=data,
strategy=MyStrategy,
risk_config=RiskConfig(
max_account_drawdown=0.20,
max_daily_loss=0.05,
stop_loss_threshold=0.80,
),
)
Suggested account-level presets (starting points):
| Profile | max_account_drawdown |
max_daily_loss |
stop_loss_threshold |
|---|---|---|---|
| Conservative | 0.10 |
0.02 |
0.90 |
| Balanced | 0.20 |
0.05 |
0.80 |
| Aggressive | 0.30 |
0.08 |
0.70 |
Start from the balanced preset, then tighten or loosen values based on observed volatility and turnover.
6.1 Margin Account Backtest (Financing / Short Sell)¶
If your strategy needs financing long or stock short selling in backtests, switch the account mode to margin in RiskConfig:
from akquant.config import RiskConfig
risk_config = RiskConfig(
account_mode="margin",
enable_short_sell=True,
initial_margin_ratio=0.5,
maintenance_margin_ratio=0.3,
financing_rate_annual=0.08,
borrow_rate_annual=0.10,
allow_force_liquidation=True,
liquidation_priority="short_first",
)
Key fields:
account_mode:"cash"or"margin".enable_short_sell: allows opening stock short positions.initial_margin_ratio: initial margin ratio used for stock/fund sizing checks.maintenance_margin_ratio: maintenance threshold.allow_force_liquidation: force close when maintenance is breached.liquidation_priority:"short_first"or"long_first".
You can read extended margin fields via get_account() inside strategy callbacks:
snap = self.get_account()
print(
snap["account_mode"],
snap["borrowed_cash"],
snap["short_market_value"],
snap["maintenance_ratio"],
snap["accrued_interest"],
snap["daily_interest"],
)
If the strategy is running with futures margin semantics, these fields become especially important:
snap["equity"]: current account equity.snap["used_margin"]/snap["margin"]: current margin in use.snap["free_margin"]: available margin (equity - used_margin), i.e. the amount usable to open new positions; theAvailablevalue in the rejection log refers to this field, so do not compare it againstcash.snap["notional_value"]: current futures notional exposure.snap["unrealized_pnl"]: current floating PnL.
Notes:
- Opening a futures position does not deduct full notional from cash the way a spot buy does.
- For futures, use
equityfor net account value,used_marginfor margin usage, andnotional_valuefor leverage exposure. - If you only need one "current total equity" number, prefer
equity, which is aligned withget_account()["equity"].
6. Using High-Performance Indicators¶
AKQuant includes commonly used technical indicators built into the Rust layer. They use Incremental Calculation to avoid repeated full recalculations, resulting in extremely high performance.
Supported Indicators: SMA, EMA, MACD, RSI, BollingerBands, ATR.
7.1 Registration and Usage¶
Indicators have a single declaration entry point, self.I(...). AKQuant dispatches on the object you pass: anything with an update() method takes the incremental path, while a PrecomputedIndicator(name, fn) instance takes the vectorized precompute path. Both kinds can coexist in one strategy.
Declaring once gets you three things: the framework advances the indicator on every bar, ind[0] / ind[1] series lookback works, and plot points are reported on demand.
from akquant import Bar, PrecomputedIndicator, Strategy
class PrecomputeIndicatorStrategy(Strategy):
def on_start(self):
# Passing a PrecomputedIndicator instance -> vectorized precompute
self.mom10 = self.I(
PrecomputedIndicator("mom10", lambda df: df["close"] - df["close"].shift(10)),
name="mom10",
)
self.subscribe("AAPL")
def on_bar(self, bar: Bar):
val = self.mom10[0]
if val is not None and val > 0:
self.buy(bar.symbol, 100)
from akquant import Bar, SMA, Strategy
class IncrementalIndicatorStrategy(Strategy):
def on_start(self):
# Passing an object with update() -> incremental
self.sma20 = self.I(SMA(20), name="sma20", source="close", symbols=["AAPL"])
def on_bar(self, bar: Bar):
if bar.symbol != "AAPL":
return
val = self.sma20[0]
if val is None:
return
if bar.close > val:
self.buy(bar.symbol, 100)
The incremental path offers two recommended capabilities:
factory: creates an isolated indicator instance persymbol, which is the recommended pattern for multi-symbol strategies.warmup_bars: bootstraps incremental indicators with bars beforestart_timebefore the live event stream begins.
from akquant import Bar, SMA, Strategy
class MultiSymbolIncrementalStrategy(Strategy):
def on_start(self):
self.sma20 = self.I(
factory=lambda: SMA(20),
name="sma20",
source="close",
symbols=["AAPL", "MSFT"],
warmup_bars=20,
)
def on_bar(self, bar: Bar):
val = self.sma20[0]
if val is None:
return
if bar.close > val:
self.buy(bar.symbol, 100)
Notes:
ind[0]is the current bar's value (.valueis an alias) andind[1]is the previous bar. Out-of-range lookback returnsNoneinstead of raising, so a singleif val is Nonecheck covers the warmup period. Asking forind[n]withnbeyondlookback(default 128) grows the buffer automatically and logs a warning once; sizelookbackas the warning suggests.- If one shared instance is reused across multiple symbols, AKQuant raises an explicit error and points users to
factory=. - In
on_bar/on_tick,ind[0]reads the current symbol; in callbacks that do not belong to a symbol (on_timer,on_cross_section, ...) read a multi-symbol indicator withind.of(symbol)[0]— a bare read raises. See the Custom Indicator Guide. warmup_barsonly consumes history before the active start boundary and does not double-consume the first active bar.- Inside a strategy, plot points are reported automatically only with
plot=True; nothing is reported by default, and plotting arguments (pane/color/label, ...) no longer implyplot=True. A draw-only unit can be written as anaq.Indicatorscript, which plots by default. - If you need to build private indicators instead of only using built-ins such as
SMAorEMA, continue with the Custom Indicator Guide.
7. Strategy Cookbook¶
7.1 Trailing Stop¶
class TrailingStopStrategy(Strategy):
def __init__(self):
self.highest_price = 0.0
self.trailing_percent = 0.05 # 5% trailing stop
def on_bar(self, bar):
pos = self.get_position(bar.symbol)
if pos > 0:
# Update highest price
self.highest_price = max(self.highest_price, bar.high)
# Check drawdown
drawdown = (self.highest_price - bar.close) / self.highest_price
if drawdown > self.trailing_percent:
print(f"Trailing Stop Triggered: High {self.highest_price}, Current {bar.close}")
self.close_position(bar.symbol)
self.highest_price = 0.0 # Reset
else:
# Entry logic (Example)
if bar.close > 100:
self.buy(bar.symbol, 100)
self.highest_price = bar.close # Initialize highest price
7.2 Intraday Exit¶
class IntradayStrategy(Strategy):
def on_bar(self, bar):
# Assuming bar.timestamp is nanosecond timestamp
# Convert to datetime (requires import datetime)
dt = datetime.fromtimestamp(bar.timestamp / 1e9)
# Force exit at 14:55 daily
if dt.hour == 14 and dt.minute >= 55:
if self.get_position(bar.symbol) != 0:
self.close_position(bar.symbol)
return
# Other trading logic...
7.3 OCO and Bracket Helpers¶
AKQuant provides helper APIs for linked order management:
self.place_oco(first_order_id, second_order_id, group_id=None)- Binds two orders as OCO (One-Cancels-the-Other).
- Once either order is filled, the peer order is canceled automatically.
self.place_bracket(symbol, quantity, entry_price=None, stop_trigger_price=None, take_profit_price=None, ...)- Submits a bracket structure in one call.
- After entry fill, stop-loss and take-profit exits are submitted automatically; when both exits exist, they are linked as OCO.
from akquant import OrderStatus, Strategy
class BracketHelperStrategy(Strategy):
def __init__(self):
self.entry_order_id = ""
def on_bar(self, bar):
if self.get_position(bar.symbol) > 0 or self.entry_order_id:
return
self.entry_order_id = self.place_bracket(
symbol=bar.symbol,
quantity=100,
stop_trigger_price=bar.close * 0.98,
take_profit_price=bar.close * 1.04,
entry_tag="entry",
stop_tag="stop",
take_profit_tag="take",
)
def on_order(self, order):
if order.id == self.entry_order_id and order.status in (
OrderStatus.Cancelled,
OrderStatus.Rejected,
):
self.entry_order_id = ""
7.4 Trailing Stop Helpers¶
If you want to express a moving stop line directly in strategy logic, use these helpers:
self.place_trailing_stop(symbol, quantity, trail_offset, side="Sell", trail_reference_price=None, ...)- Executes as market order after trigger (
StopTrail -> Market).
- Executes as market order after trigger (
self.place_trailing_stop_limit(symbol, quantity, price, trail_offset, side="Sell", trail_reference_price=None, ...)- Executes as limit order after trigger (
StopTrailLimit -> Limit).
- Executes as limit order after trigger (
from akquant import Strategy
class TrailingHelperStrategy(Strategy):
def __init__(self):
self.trailing_order_id = ""
def on_bar(self, bar):
if self.get_position(bar.symbol) == 0:
self.buy(bar.symbol, 100)
self.trailing_order_id = self.place_trailing_stop(
symbol=bar.symbol,
quantity=100,
trail_offset=1.5,
side="Sell",
trail_reference_price=bar.close,
tag="trail-stop",
)
For a full runnable script, see examples/36_trailing_orders.py.
7.5 Multi-Asset Rotation¶
class RotationStrategy(Strategy):
def on_bar(self, bar):
# Note: on_bar is triggered for each symbol
# If cross-sectional comparison is needed, it is recommended to process in on_timer or after collecting all bars
# This shows simple independent processing
pass
def on_timer(self, payload):
# Assume a daily timer is registered
# Get current prices of all subscribed symbols
scores = {}
# Actually should iterate over watchlist or subscribed symbols
# Note: self.ctx.positions contains current positions, but we might want to check all watched symbols
for symbol in self.ctx.positions.keys():
hist = self.get_history(20, symbol)
scores[symbol] = hist[-1] / hist[0] # 20-day momentum
# Sort and rebalance...
8. Mixed Asset Backtesting Configuration¶
AKQuant supports mixed trading of multiple assets such as stocks, futures, and options within the same strategy. Different assets usually have different attributes (e.g., contract multiplier, margin ratio, tick size).
Using InstrumentConfig allows you to conveniently configure these attributes for each instrument.
8.1 Configuration Steps¶
- Prepare Data: Prepare data (DataFrame or CSV) for each instrument.
- Create Config: Use
InstrumentConfigto define parameters for non-stock assets. - Run Backtest: Pass the configuration to the
instruments_configparameter ofrun_backtest.
8.2 Configuration Example¶
Suppose we want to backtest a portfolio containing "Stock A" and "Stock Index Futures IF":
from akquant import BacktestConfig, InstrumentConfig, StrategyConfig, run_backtest
# 1. Define Futures Configuration
future_config = InstrumentConfig(
symbol="IF2301", # Instrument Symbol
asset_type="FUTURES", # Asset Type: STOCK, FUTURES, OPTION
multiplier=300.0, # Contract Multiplier (300 per point)
margin_ratio=0.1, # Margin Ratio (10%)
tick_size=0.2 # Tick Size
)
# 2. Run Backtest
# Note: Unconfigured instruments (e.g., STOCK_A) will use default parameters (Stock, Multiplier 1, Margin 100%)
config = BacktestConfig(
strategy_config=StrategyConfig(),
instruments_config=[future_config],
)
run_backtest(
data=data_dict,
strategy=MyStrategy,
config=config, # Pass config object
# ...
)
For detailed code, please refer to the Mixed Asset Backtest Example.