Documentation

Account Model

Every QuantCraft strategy runs against a built-in paper trading account. The account is what tracks your cash, holds your open positions, books realized profit and loss when you close trades, and computes performance metrics at the end of a backtest.

You don't construct it yourself in normal use — the backtest engine creates it from the Run backtest modal Simulation tab (starting balance, commission / slippage) and assigns it to quantcraft.backtest.runtime.account (legacy ide.backtest.runtime.account is equivalent) before on_init() runs. Optional default SL/TP and risk-based sizing can be wired via config / .qcs keys when present; the modal does not currently expose SL/TP / risk inputs. Callbacks receive market data as described in Strategy lifecycle and OHLCV and bar data; metrics show up in Test results.


Quick start

from quantcraft.backtest.runtime import account def on_init(): pass def on_bar(bar_index, bar, fundamentals=None, symbol=None): px = float(bar["close"]) snap = account.open_trade("AAPL", "long", 10, px) if snap["open_positions"]: pid = snap["open_positions"][0]["id"] account.close_trade(pid, px + 1.0) def on_finish(bars, symbol=None, bars_by_symbol=None): last_px = float(bars[-1]["close"]) metrics = account.refresh_metrics({"AAPL": last_px})

That's the full pattern: open a trade, store the position id, close it later, and (optionally) refresh metrics at the end.


What PaperAccount does

The account simulates a simple cash trading account:

  • Tracks starting balance, cash, balance, and equity.
  • Holds long and short positions in the same account.
  • Books realized P/L when you close a trade and tracks unrealized P/L for open positions.
  • Maintains an equity history that is appended on every price update.
  • Optionally computes a full set of performance metrics (Sharpe, Sortino, drawdown, CAGR, etc.).

What it does not model: margin, dividends, borrow cost, or automatic SL/TP execution. Stored SL/TP values are just numbers — your strategy code is responsible for checking prices and calling close_trade when a stop or target is hit. Commission and slippage apply when models are configured on the Simulation tab — see below.

Commission and slippage are configured in the Run backtest modal Simulation tab. When enabled, fills are adjusted automatically; you do not set these in Python. Default commission is per share with cost often 0 until you set a non-zero cost. Default slippage is volume share.


Configuring the account

You configure the account on the Simulation tab of Run backtest:

SettingWhat it does
starting_balanceCash the account starts with.
Commission / slippage modelsHow fills are adjusted — see below.

Optional default SL/TP and risk sizing (sl_pct / sl_dollars, tp_pct / tp_dollars, risk_pct_per_trade / risk_fixed_per_trade) can still be applied from .qcs / config helpers when present, but the Run backtest modal does not currently expose those inputs. When they are set:

  • Percent fields accept either whole-percent values like 2 or fractions like 0.02 — both mean the same thing.
  • For longs, the stop is below entry and the target is above entry. Shorts invert that.
  • Defaults apply to every new trade unless you override them per call.

For notebooks or tests only (outside the IDE backtest flow), you can construct an account manually:

account = PaperAccount( 100_000, sl_pct=2, tp_pct=4, risk_pct_per_trade=1, slippage_model=None, # optional; IDE engine wires from Simulation tab commission_model=None, # optional; IDE engine wires from Simulation tab )

Commission and slippage (Simulation tab)

The Simulation tab in the Run backtest modal configures how fills are adjusted for trading costs. Settings apply automatically to runtime.account — you do not configure them in Python. See Backtests and Run presets (.qcs) for saving these options.

Commission models

ModelParametersBehaviour
Per share (default)Cost per share ($), minimum per trade ($)max(qty × cost, min) when minimum > 0
Per tradeFlat cost per order ($)Same fee regardless of quantity
ZeroNo commission — useful for testing pure alpha

Slippage models

ModelParametersBehaviour
Volume share (default)Volume limit (default 0.025), price impact (default 0.1)Impact scales with (qty / bar_volume)²; buys fill higher, sells fill lower. volume_limit also caps fill qty to volume_limit × bar_volume before the fill. Zero / missing bar volume → no impact.
Fixed spreadTotal spread per share ($)Half-spread applied on each fill leg
ZeroFill at exact requested price

Closed trade records include commission, slippage_cost, raw_entry_price, and raw_exit_price. Stored entry_price / exit_price are fill prices after slippage. account.refresh_metrics() exposes total_commission and total_slippage_cost.


Positions

A position represents one open trade in a single symbol. You don't construct positions directly — they are created by open_trade(...) and removed by close_trade(...).

Opening a trade

snap = account.open_trade( symbol, # "AAPL" side, # "long" or "short" qty, # integer or float quantity entry_price, # float, the requested price (slippage/commission applied) sl_price=None, # optional stop price (overrides default sl_pct/sl_dollars) tp_price=None, # optional target price (overrides default tp_pct/tp_dollars) position_id=None, )

The call returns a snapshot of the account (see below). The newly opened position appears in snap["open_positions"] — grab its id if you want to close it later by id. The stored entry_price is the fill after slippage; the requested price is kept as raw_entry_price.

Sizing by risk

If you want the account to size the trade based on your risk budget (one of risk_pct_per_trade or risk_fixed_per_trade) and a stop distance, use:

qty = account.position_size_for_risk(entry_price, stop_price)

This requires that exactly one risk mode is configured and that the stop distance isn't zero. By default, risk_pct_per_trade uses a percent of cash; pass equity_for_risk=... to size against equity instead.

Closing a trade

account.close_trade(position_id, exit_price)

open_trade / close_trade take a requested price, then apply the run’s slippage and commission models. Stored exit_price is the fill; the requested price is kept as raw_exit_price. A common backtest simulation pattern: request the bar's closing synthetic tick from on_tick:

def on_tick(bar_index, tick_in_bar, price, bar, fundamentals=None, symbol=None): if tick_in_bar == 3: account.close_trade(pid, price)

On forward runs, use the live price from each broker quote in on_tick instead of checking tick_in_bar.

You can also close in bulk by symbol. symbol= is required in multi-symbol runs so you do not accidentally close positions on every ticker at once:

account.close_all_longs(exit_price, symbol="AAPL") account.close_all_shorts(exit_price, symbol="AAPL")

Exit price vs indicators: Pass the price you intend to target (e.g. float(bar["close"]) from on_bar); the engine still applies slippage/commission. It does not rewrite your request to an SMA or other indicator. In backtest, tick_in_bar == 3 in on_tick is a synthetic closing tick (bar OHLC simulation, not real tick data). On forward runs, close using the live price from on_tick on each broker update.


Cash, balance, equity, and PnL

These are the core money-tracking fields available on the account and on every snapshot:

FieldMeaning
starting_balanceThe cash the account started with.
cash / balanceSettled cash after opens/closes. Long opens debit qty × fill_price + commission; shorts credit qty × fill_price − commission. Stored entry_price / exit_price are fill prices after slippage.
equityMark-to-market total: cash + Σ(long qty × mark) − Σ(short qty × mark).
unrealized_pnlSum of P/L on open positions, valued at the current marks.
realized_pnlCumulative profit/loss from closed trades.

How marks are updated:

  • The engine calls tick(prices, time=...) on the account on every simulated price step, so equity, unrealized_pnl, and the equity history stay current automatically.
  • If a symbol's mark price is missing from the prices map, that position is valued at its entry price — unrealized P/L for that leg is 0 until you pass a real quote.
  • After close_trade, the snapshot's tick_prices may be empty ({}). If you call refresh_metrics() without passing prices and the last snapshot had empty marks, open legs may be valued at entry.

Inside on_bar and on_tick, you do not need to call account.tick(...) yourself — the engine already does it for you. Prefer passing explicit last_prices to refresh_metrics({symbol: last_px}) in on_finish when anything might still be open.

Short trades and cash

Both longs and shorts are supported in the same account:

  • Short open — proceeds increase cash (minus commission when configured).
  • Short close (buy to cover) — reduces cash.

There is no margin model or borrow cost, so shorts are a pure cash-and-mark simulation (plus commission/slippage when models are set).


Snapshots

Every call to open_trade, close_trade, and tick returns the same snapshot dictionary describing the state of the account right after the call. Useful keys:

KeyWhat it contains
starting_balanceInitial cash.
cash / balanceCurrent cash.
equityCurrent mark-to-market equity.
unrealized_pnlP/L on open positions at current marks.
realized_pnlCumulative realized P/L.
open_positionsList of open position dicts: id, symbol, side, qty, entry_price, sl_price, tp_price, raw_entry_price, commission_at_open, optional entry_time. There is no per-leg P/L field on open position rows — read unrealized_pnl from the snapshot for aggregate floating P/L.
closed_tradesList of closed trades with entry/exit prices, realized P/L, commission, slippage_cost, raw_exit_price, optional raw_entry_price, and times. Also available as account.closed_trades on the instance.
tick_pricesCopy of the price map used for that snapshot (may be empty after close_trade).

There is no account.get_open_positions(symbol) API. Filter snap["open_positions"] by symbol, or read account.closed_trades for closed history.

This makes it easy to inspect the account in your strategy:

snap = account.open_trade("AAPL", "long", 10, px) print("equity now:", snap["equity"]) print("open positions:", len(snap["open_positions"]))

Performance metrics

When the run is finishing, you can ask the account to compute a full set of metrics:

def on_finish(bars, symbol=None, bars_by_symbol=None): last_px = float(bars[-1]["close"]) metrics = account.refresh_metrics({"AAPL": last_px})

The argument is a {symbol: last_price} map used as the final mark so open positions are valued correctly. Use the bars list passed into on_finish (oldest first) to get the last close — this is the canonical full-history series.

You can also pass two optional arguments:

  • risk_free_rate=0 — used by Sharpe/Sortino-style ratios.
  • calmar_annualized_return=None — overrides the annualized return used by Calmar.

Available metrics

refresh_metrics(...) returns a dictionary that includes:

GroupFields
Returnstotal_pnl, total_return, cagr
Riskmax_drawdown, volatility, risk_adjusted_return
Ratiossharpe_ratio, sortino_ratio, calmar_ratio, profit_factor
Trade statsaverage_trade_expectancy, average_win, average_loss, total_commission, total_slippage_cost
Exposurecurrent_exposure, average_exposure, max_exposure

Notes:

  • Trade-based ratios use per-trade return defined as realized_pnl / starting_balance.
  • total_return and cagr use current equity vs. starting balance.
  • For meaningful CAGR / Calmar, the engine needs calendar information — the engine already passes timestamps when it ticks the account, so you generally don't need to do anything special.
  • Some ratios may return inf when the denominator is zero and performance is favorable (for example, no losing trades).

The metrics are also surfaced in the Test Results view of the editor and in the structured result payload of the run.


Putting it together

Typical usage inside a strategy:

  1. Configure starting balance and commission / slippage on the Simulation tab (optional SL/TP / risk via .qcs / code when supported).
  2. Open trades from on_bar (or from on_tick for intrabar fills) using account.open_trade(...) — store the returned id if you'll need it.
  3. Close trades with account.close_trade(position_id, exit_price).
  4. Read snap["equity"], snap["cash"], snap["unrealized_pnl"], etc. whenever you want to inspect the account.
  5. In on_finish, call account.refresh_metrics({symbol: last_price}) to populate performance metrics for the result.

That's the whole account model — small surface area, but enough to simulate longs, shorts, cash flows, P/L, and a complete metrics set for any strategy you can express with the lifecycle callbacks.