AI strategy authoring reference
This is the compact, high-signal contract for generating compiled Roboquant
.rq strategies. It complements the complete Runtime Reference.
Definition of done
A generated strategy is complete only when all applicable gates pass:
- The full
.rq/.rsbundle compiles. - The compiler's parameter schema contains every user-tunable input.
- A backtest runs on an available symbol and the requested data mode.
- Entry, exit, sizing, session, and causality behavior match the request.
- If the strategy draws, the backtest's drawing kinds, counts, anchors, and lifetimes are plausible.
Compilation proves type and API correctness. It does not prove trading logic or chart semantics.
Authoring workflow
These steps apply to the in-app AI chat and to an external AI app connected through the Roboquant MCP server. The in-app chat names its tools in parentheses; MCP tools are named after the arrow.
New strategy
- Translate the request into a short acceptance contract: signals, filters, session/timezone, sizing, exits, parameters, drawings, and data mode.
- Load only the reference topics you need for feature-specific SDK
signatures (
get_rq_reference→docs_reference), then write one complete descriptivesnake_case.rqsource. - Compile the complete source (
compile_strategy→strategies_prepare). Repair only from compiler diagnostics until it compiles cleanly. The compile result returns the parameter schema,wants_ticksand warnings. - Save the exact source that compiled (
save_strategy→strategies_create, after the user approves the prepared summary). - Run and inspect a representative backtest (→
backtests_prepare,backtests_run, then pollbacktests_get). Check every requested drawing kind.
Existing strategy
- Read every source file that will change (
read_file→strategies_source). - Apply the changes (
edit_file→strategies_prepare_update, which merges the files you send and recompiles changed source). - Repair any compiler diagnostics until the strategy compiles clean.
- Save the clean build so the stored compiled artifact matches the visible
source (
save_strategy→strategies_update, after approval).
Never edit a strategy through shell commands. The source in Roboquant is the only copy that compiles and runs.
Minimal compiled strategy
use rq_sdk::prelude::*;
#[strategy(name = "EMA Crossover")]
pub struct EmaCrossover {
#[param(default = 12, min = 2, max = 100, title = "Fast EMA")]
fast_period: i64,
#[param(default = 26, min = 3, max = 200, title = "Slow EMA")]
slow_period: i64,
fast: Ind,
slow: Ind,
}
impl Strategy for EmaCrossover {
fn on_init(&mut self, init: &mut Init) {
self.fast = init.add(Ema::new(self.fast_period.max(2) as usize));
self.slow = init.add(Ema::new(self.slow_period.max(3) as usize));
}
fn on_bar(&mut self, ctx: &mut Ctx, _bar: Bar) {
let (Some(fast), Some(slow), Some(prev_fast), Some(prev_slow)) = (
ctx.val(self.fast),
ctx.val(self.slow),
ctx.val_back(self.fast, 1),
ctx.val_back(self.slow, 1),
) else { return };
let crossed_up = prev_fast <= prev_slow && fast > slow;
let crossed_down = prev_fast >= prev_slow && fast < slow;
if ctx.position() == 0 && crossed_up {
ctx.buy(1).send();
} else if ctx.position() > 0 && crossed_down {
ctx.close_position();
}
}
}
Patterns that prevent common failures
Sessions and timezones
Engine timestamps are UTC. Times the user gives are in the strategy's timezone (its Settings: ET, CT, UTC or Local; pinned on every run and bot), so session rules use the DST-aware strategy-timezone helpers — never a UTC-offset parameter:
let hhmm: u32 = bar.time.local_hhmm(); // u32
let session_date: u32 = bar.time.local_date_num(); // u32
let in_rth = (930..1600).contains(&hhmm);
// Params are i64 — cast at the comparison:
if hhmm >= self.flat_hhmm as u32 { /* ... */ }
For daily, weekly or monthly bars, or any logic keyed on the CME trading day, use the trading date, not the bar's open:
let day = ctx.trading_day(bar.time); // Time at 00:00 UTC of the trading date
if day.weekday() == Weekday::Mon { /* Monday's session (opened Sunday evening) */ }
let date: u32 = day.date_num(); // e.g. 20260914 for Monday's 1D bar
For a time the user names in New York explicitly, et_hhmm() /
et_date_num() are New York whatever the strategy timezone.
The time helpers (hhmm(), date_num(), local_hhmm(), et_hhmm(), …)
return u32; comparing them to an i64 #[param] without a cast is an E0308
compile error. There are no et_hour() or et_minute() methods. Use et_hhmm(), or call
let et = bar.time.et() and then et.hour() / et.minute().
Indicators and warmup
Register indicators in on_init, store their Ind handles, and guard every
read because warmup returns None. Use ctx.val_back(handle, 1) for previous
indicator values; do not approximate a crossover with only the current values.
When live warm-up is enabled, a live bot replays its past bars through
on_bar against a simulated account before it trades, and ctx.is_warmup()
is true during that replay. Prefer ctx.position() over a hand-kept
in_trade field; if the strategy keeps one, skip updating it while
ctx.is_warmup() is true.
Orders and risk
Every order builder must end in .send(). Futures fixed-dollar risk includes
the contract multiplier and may legitimately produce zero contracts:
let stop_distance = (bar.close - stop_price).abs();
let loss_per_contract = stop_distance * ctx.contract().multiplier;
let quantity = if loss_per_contract > 0.0 {
(self.risk_usd / loss_per_contract).floor() as i64
} else { 0 };
if quantity > 0 {
ctx.buy(quantity).sl(stop_price).tp(target_price).send();
}
Drawing lifecycles
DrawingId is not Default. Store optional active handles as
Option<DrawingId>. Drawing calls take &ctx, so reading ctx inside a
drawing builder chain is fine (.starting_at(ctx.time()) compiles); order
builder chains (ctx.buy/ctx.sell) still hold ctx mutably — hoist ctx
reads into locals before those.
pub struct OpeningRange {
// parameters omitted
range: Option<DrawingId>,
range_high: f64,
range_low: f64,
}
// while the range is forming
let now = ctx.time();
if let Some(id) = self.range {
ctx.update(id, self.range_high, self.range_low);
} else {
self.range = Some(
ctx.plot_zone(self.range_high, self.range_low)
.starting_at(now)
.label("Opening range")
.border("#FFD700")
.fill("rgba(255,215,0,0.16)")
.send(),
);
}
// when the range ends
if let Some(id) = self.range.take() {
ctx.freeze(id);
}
Use plot_text for a label, not plot_level. A bounded source line needs both
time anchors or an explicit freeze. Freeze or invalidate entry/stop/target
drawings in on_trade when txn.kind == TxnKind::PositionClosed.
Tick and multi-symbol strategies
on_tickreceives no events unlesswants_ticks() -> trueis implemented.- In tick/timer/trade hooks,
ctx.bar(0)is the forming bar; usebar(1)for the last completed bar. - Pairs and basket strategies implement
MultiStrategy::on_bars; do not mix a Python multi-symbol API into.rq.
Translation acceptance contract
Before converting Pine Script, MQL, prose, or a video transcript, explicitly account for each row:
| Concern | Required decision |
|---|---|
| Signals | Exact boolean entry and exit conditions, including cross/pivot history |
| Session | Start/end, timezone, DST behavior, and reset boundary |
| Orders | Market/limit/stop semantics, next-event fill timing, OCO behavior |
| Risk | Stop basis, target basis, multiplier, rounding, maximum size |
| State | Daily resets, one-shot setup flags, pending orders, active trade state |
| Parameters | Every tunable value and valid min/max/options |
| Drawings | Primitive, anchors, label, lifecycle, and expected count/duration |
| Data | Bars, ticks, L2, higher timeframe, or multiple symbols |
If the source is ambiguous, preserve its literal behavior and disclose the ambiguity instead of silently inventing a convention.
Verification checklist
- The source that compiled is exactly the revision being saved or tested.
- Each entry is a
.rqfile; helpers are sibling.rsmodules. - No generated
.rqcor.params.pyfile was edited manually. - Every
#[param]default satisfies its declared bounds/options. - All indicator reads have warmup guards.
- Crossover logic checks the previous and current values.
- Session comparisons use the intended timezone.
- Tick strategies opt in; closed-bar logic does not read a forming bar.
- Orders end in
.send()and sizing cannot submit zero/negative quantity. - Requested drawings use the right primitive and close at the intended event.
- The backtest and drawing verification pass; warnings are investigated rather than ignored.