Skip to main content

Crate wickra_backtest

Crate wickra_backtest 

Source
Expand description

§wickra-backtest

Streaming-native, event-driven backtester for the Wickra technical-indicator library.

This facade re-exports the engine (wickra_backtest_core) and the data loaders (wickra_backtest_data) behind one crate, plus the historical backtest runner and reports.

The same engine, fed live instead of historical bars, becomes the live bot — so backtest == live, byte-identical, and (because the strategy is a JSON spec, not code) identical across every Wickra language binding.

use wickra_backtest::{run_with_capital, Candle, StreamingBacktest, StrategySpec};

// A strategy is data. This one buys above 100 and sells below it.
let spec = StrategySpec::parse(
    r#"{"symbol":"BTCUSDT","timeframe":"1h","indicators":{},
        "entry":{"gt":[{"price":"close"},100]},
        "exit":{"lt":[{"price":"close"},100]},
        "sizing":{"type":"fixed_qty","qty":1}}"#,
)?;

let candles: Vec<Candle> = [(100.0, 101.0), (102.0, 103.0), (104.0, 99.0), (98.0, 97.0)]
    .iter()
    .enumerate()
    .map(|(i, &(open, close))| Candle {
        time: i as i64,
        open,
        high: open.max(close),
        low: open.min(close),
        close,
        volume: 0.0,
    })
    .collect();

// The whole series at once.
let batch = run_with_capital(&spec, &candles, 1_000.0)?;

// The same spec, one bar at a time. Replace the loop with reads from a
// socket and this is a live strategy; nothing else about it changes.
let mut live = StreamingBacktest::new(&spec, 1_000.0)?;
for candle in &candles {
    live.step(candle)?;
}
let streamed = live.finish();

// That equality is the point of the crate, not a coincidence.
assert_eq!(streamed.metrics.num_trades, batch.metrics.num_trades);
assert_eq!(streamed.metrics.pnl, batch.metrics.pnl);

Re-exports§

pub use wickra_backtest_core as core;
pub use wickra_backtest_data as data;

Modules§

engine
The event-driven backtest loop.
error
Error types for the backtest engine.
metrics
Performance metrics computed from the equity curve and the trade log.
portfolio
Cash/position accounting for one signed position (long qty > 0 or short qty < 0).
registry
Indicator registry: constructs wickra-core indicators by name and wraps them behind a uniform, object-safe EvalIndicator the engine can drive from a Candle.
report
The backtest result: metrics, the trade log and the equity curve.
request
A single JSON request bundling candles, the strategy spec and optional feeds — the uniform entry point the language bindings call, so every binding can run any feed combination by passing one JSON document.
rules
Evaluation of the strategy DSL (Operand / Condition) against the per-bar history. Operands resolve to a number (or None when an indicator is still warming up); conditions resolve to a boolean (false when any operand is missing). Cross conditions compare the current bar with the previous one.
spec
The data-driven strategy specification (StrategySpec).

Structs§

BacktestReport
The result of a backtest run.
Candle
One OHLCV bar. time is the bar’s open time (engine-defined epoch unit; it is passed straight through to indicators that need a timestamp).
Costs
Trading costs.
CrossSection
A market-wide cross-section (a panel of CrossSectionMembers at one tick), fed to the market-breadth indicators (advance/decline, McClellan, TRIN, …).
CrossSectionMember
One symbol’s breadth signals within a CrossSection.
DerivativesTick
A derivatives (perpetual / futures) tick, fed to derivatives indicators.
EquityPoint
One point on the equity curve (marked at each bar close).
Execution
Execution model.
Feeds
The optional non-OHLCV feeds for one bar: a reference-series close (pairwise), a derivatives tick (derivatives) and an order-book snapshot (order-book). Absent feeds are None; indicators that need a missing feed yield nothing.
IndicatorSpec
One indicator instance: a wickra-core type name plus its parameters.
Level
One order-book price level.
Metrics
Summary performance metrics.
OrderBook
An order-book snapshot (best level first on each side), fed to order-book indicators.
Risk
Risk controls (all optional).
RunRequest
A complete backtest request: the strategy, the candle stream, the starting capital and any optional per-bar feeds. Each present feed must be the same length as candles.
StepFeeds
One bar’s optional side feeds, as a JSON document.
StepRequest
One streaming step as a JSON document: the bar, plus that bar’s feeds.
StrategySpec
A complete strategy specification.
StreamingBacktest
A streaming backtest: feed bars one at a time with StreamingBacktest::step, then StreamingBacktest::finish. The historical runner is exactly this fed from a slice, so backtest and live share one code path — point step at a live feed and the same engine becomes the live bot.
Trade
A completed round-trip trade.
TradePrint
A single trade print, fed to trade-flow indicators.

Enums§

BacktestError
An error raised while parsing a strategy spec or running a backtest.
Condition
A boolean node — evaluates to true/false each bar.
Feed
The data feed an indicator is driven by.
FillTiming
When a signalled order fills.
IntPredicate
An integer comparison predicate (used by stateful conditions).
Operand
A value node — evaluates to a number each bar.
OperandExpr
The object-shaped operand forms.
OrderType
Order type.
PriceField
A price field of the current bar.
Sizing
Position sizing model.
Slippage
Slippage model.
TradeSide
Aggressor side of a TradePrint.

Constants§

DEFAULT_CAPITAL
Default starting capital for the runner.
REPORT_SCHEMA_VERSION
Current report schema version.
SPEC_VERSION
Current strategy-spec format version. Bumped on breaking DSL changes.

Traits§

EvalIndicator
A uniform, object-safe indicator the engine drives one bar at a time.

Functions§

run
Run a backtest of spec over candles with the default capital.
run_json
Run a backtest from a single JSON RunRequest, returning the report JSON. This is the uniform entry point every language binding wraps.
run_stream
Run a backtest over a candle stream, invoking on_bar with the streaming state after each bar — the streaming entry point for a live tail or for emitting the equity curve incrementally.
run_with_capital
Run a backtest with explicit starting capital.
run_with_cross_section
Run a backtest with a per-bar market cross-section for breadth indicators (advance/decline, McClellan, TRIN, …). sections must be the same length as candles.
run_with_deriv
Run a backtest with a per-bar derivatives feed for derivatives indicators (funding, open interest, long/short ratio, …). derivs must be the same length as candles.
run_with_orderbook
Run a backtest with a per-bar order-book feed for order-book indicators (imbalance, microprice, quoted spread, …). books must be the same length as candles.
run_with_ref
Run a backtest with a reference price series for pairwise indicators. The reference candle at each index supplies the second input (its close) to pairwise indicators such as correlation, beta or spread. reference must be the same length as candles.
run_with_trades
Run a backtest with a per-bar trade feed for trade-flow indicators (CVD, trade imbalance, VPIN, signed volume, …). trades[i] is the list of trades that printed within bar i; the outer length must match candles.
strategy_spec_schema
The JSON Schema for StrategySpec, pretty-printed. Editors and tooling can validate strategy specs against it; the committed schema/strategy_spec.schema.json is generated from this.
version
The crate version, surfaced for diagnostics.

Type Aliases§

Result
Convenience result alias for the engine.