Quince
Quince is a low-latency Rust execution engine and the Quince-Flavored Language (QFL) runtime for event-driven trading strategies. Its hot path is synchronous, bounded, and allocation-free after strategy and indicator construction.
The system deliberately separates three concerns:
- Market data and execution adapters normalize exchange events and keep live execution fail-closed when account, market-data, or reconciliation guarantees are absent.
- The engine and QFL VM compile a strategy once, run it per event, and enforce risk and instruction budgets before an order can leave the process.
- Indicators turn public trades into finite scalar features that QFL reads
with
quince.get("name").
Quick indicator example
The indicator is declared before the strategy handlers and read inside the handler. A custom indicator has the same QFL surface as a built-in one:
@using custom_logistic_regression:0.05:0.01
on trade(t) {
feature buy_probability = quince.get("custom_logistic_regression")
if buy_probability > 0.60 {
quince.log("buy pressure")
}
}
@using is validated during startup. Unknown names, a wrong parameter count,
non-numeric arguments, or out-of-range values reject the strategy before it can
execute. An indicator may return no value during warm-up; QFL sees the normal
engine default until it has a finite scalar.
Native extension model
Custom indicators are Rust source files compiled and linked into the Quince binary. Dynamic plugins are intentionally not loaded: this makes the deployed artifact reproducible and ensures every indicator participates in review, tests, linting, and benchmark gates. See Writing a native indicator for the contract, and the native catalogue for all currently linked indicators.
Validation boundary
An indicator is a feature, not a trading claim. Validate it in the replay environment with fees, slippage, and out-of-sample data before allowing a strategy that uses it to progress from shadow mode to execution.
Production beta runbook
This runbook is the operational path for a single-operator, single-symbol production beta. It is deliberately a promotion checklist, not a promise of profitability. A strategy advances only after the previous gate has produced evidence that can be inspected and reproduced.
The supported progression is:
offline preflight → public + shadow → replay research → Binance Futures testnet
→ limited Binance live beta
Hyperliquid is supported for wallet onboarding and public market data. Its authenticated execution path is currently fail-closed; it is not a live beta venue until the binary explicitly enables it. Do not treat a configured wallet as permission to trade.
Non-negotiable rules
- Use a dedicated account or wallet with funds you can afford to lose. Never reuse a personal wallet or a general-purpose exchange API key.
- Never put a private key, API secret, recovery phrase, or full credentials in
QFL, Git, shell history, a
.envfile committed to Git, dashboard requests, or a support message. - The default dashboard is loopback-only and read-only. It is visibility, not remote order control.
- Set explicit small limits for every beta process. Defaults are safety bounds, not an approval for a given amount of capital.
- One process, one strategy revision, one symbol, and one operator at a time. Stop and reconcile before restart after a crash or an uncertain order state.
0. Build and offline preflight
Build the pinned toolchain, then validate the exact configuration without opening an exchange socket, loading credentials, or creating order artifacts.
cargo +nightly build --locked
QUINCE_PUBLIC=1 \
QUINCE_SHADOW=1 \
QUINCE_STRATEGY=strategies/scalper.qfl \
QUINCE_SYMBOL=btcusdt \
QUINCE_MAX_POSITION=0.001 \
QUINCE_MAX_ORDER_NOTIONAL=25 \
QUINCE_MAX_POSITION_NOTIONAL=50 \
QUINCE_MAX_DRAWDOWN=0.02 \
QUINCE_MAX_DAILY_LOSS=10 \
QUINCE_MAX_ORDER_FREQ=2 \
QUINCE_MAX_MARKET_DATA_AGE_MS=2000 \
cargo run --locked --bin quince -- preflight
The command must print JSON with "status":"ok", the intended exchange and
network, "input_mode":"public", and "execution_mode":"shadow". Correct
the configuration rather than weakening a limit to make preflight pass.
Before every promotion, verify that the prior process left no ambiguous orders:
cargo run --locked --bin quince -- journal verify trades.orders.jsonl
If it reports unresolved client order IDs, do not restart. Reconcile every listed ID against the exchange first.
1. Dedicated Hyperliquid wallet (public-data use)
The initial interactive launch offers wallet creation. To make this explicit, run the wizard in a private terminal:
QUINCE_WALLET_SETUP=1 cargo run --locked --bin quince
Choose create for a new dedicated wallet, or import only a dedicated key.
The private key is stored in wallet.enc.json with AES-256-CBC plus
encrypt-then-MAC authentication; the passphrase is never stored and the public
profile contains only the address. For a non-interactive authenticated process,
inject QUINCE_WALLET_PASSPHRASE from a secret manager. The wizard must never
be run through screen sharing, copied terminal transcripts, or a shell command
containing the private key or passphrase.
This is not required for Binance public/shadow/replay work. It is required before any future authenticated Hyperliquid integration, which Quince does not currently enable.
2. Public data in shadow mode
Shadow mode evaluates the strategy but suppresses each order before journal and exchange dispatch. Run it long enough to observe normal market conditions, quiet periods, reconnects, and at least one planned restart.
QUINCE_PUBLIC=1 \
QUINCE_SHADOW=1 \
QUINCE_DASHBOARD=1 \
QUINCE_STRATEGY=strategies/scalper.qfl \
QUINCE_SYMBOL=btcusdt \
QUINCE_MAX_POSITION=0.001 \
QUINCE_MAX_ORDER_NOTIONAL=25 \
QUINCE_MAX_POSITION_NOTIONAL=50 \
QUINCE_MAX_DRAWDOWN=0.02 \
QUINCE_MAX_DAILY_LOSS=10 \
QUINCE_MAX_ORDER_FREQ=2 \
QUINCE_MAX_MARKET_DATA_AGE_MS=2000 \
cargo run --locked --bin quince
Inspect the loopback dashboard at http://127.0.0.1:3000. GET /healthz
only proves the dashboard process can respond. GET /readyz is the stricter
signal: it requires a fresh healthy journal snapshot, no unresolved orders,
and execution_sync_ready=true.
For Hyperliquid public testnet observation, use the strategy directives:
QUINCE_PUBLIC=1 \
QUINCE_SHADOW=1 \
QUINCE_STRATEGY=strategies/hyperliquid_public.qfl \
QUINCE_SYMBOL=BTC \
cargo run --locked --bin quince
Promote only if telemetry stays healthy: no unexplained stream-integrity growth, no stale-data latch, no unresolved journal IDs, and strategy behavior matches the expected signal logic. A dashboard green light is necessary but is not a trading recommendation.
3. Replay research gate
Collect or import a capture, then use explicit cost assumptions. The report is deterministic for the same strategies, capture, symbol, and assumptions.
QUINCE_SYMBOL=BTCUSDT \
QUINCE_REPLAY_FEE_BPS=4 \
QUINCE_REPLAY_SLIPPAGE_BPS=2 \
QUINCE_REPLAY_INITIAL_EQUITY=10000 \
cargo run --locked --bin quince -- research \
strategies captures/btcusdt.jsonl target/research/btcusdt
Review both target/research/btcusdt/research-report.html and the paired
machine-readable research-report.json. Sharpe and Sortino in this report are
per-observation, not annualized. Do not annualize irregular tick events by
hand. Require an out-of-sample capture and reject a candidate if its result is
dependent on a single session, unrealistic fees, or zero slippage.
4. Binance Futures testnet gate
Create a dedicated Binance Futures testnet API key with only the minimum permissions the venue requires. Keep the credential outside the repository and inject it through your local secret manager or CI secret facility. Start in shadow mode first, even on testnet:
# BINANCE_API_KEY and BINANCE_SECRET_KEY are already injected by your
# local secret manager; do not type their values in this terminal command.
QUINCE_TESTNET=1 \
QUINCE_SHADOW=1 \
QUINCE_STRATEGY=strategies/scalper.qfl \
QUINCE_SYMBOL=btcusdt \
QUINCE_MAX_POSITION=0.001 \
QUINCE_MAX_ORDER_NOTIONAL=25 \
QUINCE_MAX_POSITION_NOTIONAL=50 \
QUINCE_MAX_DRAWDOWN=0.02 \
QUINCE_MAX_DAILY_LOSS=10 \
QUINCE_MAX_ORDER_FREQ=2 \
QUINCE_MAX_MARKET_DATA_AGE_MS=2000 \
cargo run --locked --bin quince -- preflight
After preflight and a clean shadow observation window, remove only
QUINCE_SHADOW=1 to exercise testnet orders. Verify each submitted order,
fill, cancellation, and restart against the venue, then run journal verification
again. Do not skip directly from public data to mainnet.
5. Limited Binance live beta
Live mode is an explicit Binance-only boundary. Hyperliquid authenticated execution remains unavailable. Before a live start, require all of the following:
- A fresh successful preflight for the exact strategy revision and symbol.
- A clean journal with no unresolved IDs.
- Public/shadow and testnet evidence for the same strategy parameters.
- A dedicated mainnet API key with the least privileges possible and IP restrictions configured at the venue.
- An operator present for the entire initial session and a written maximum loss that is lower than the account balance.
Use explicitly small bounds. These are examples, not recommended amounts:
# BINANCE_API_KEY and BINANCE_SECRET_KEY are already injected by your
# local secret manager; do not type their values in this terminal command.
QUINCE_LIVE=1 \
QUINCE_DASHBOARD=1 \
QUINCE_STRATEGY=strategies/scalper.qfl \
QUINCE_SYMBOL=btcusdt \
QUINCE_MAX_POSITION=0.001 \
QUINCE_MAX_ORDER_NOTIONAL=25 \
QUINCE_MAX_POSITION_NOTIONAL=50 \
QUINCE_MAX_DRAWDOWN=0.02 \
QUINCE_MAX_DAILY_LOSS=10 \
QUINCE_MAX_ORDER_FREQ=2 \
QUINCE_MAX_MARKET_DATA_AGE_MS=2000 \
cargo run --locked --bin quince
The engine fail-closes on missing/failing synchronization, stale or invalid market data, risk breaches, and reconciliation failure. These controls reduce risk; they cannot eliminate exchange, software, network, or market risk.
Emergency stop and recovery
There is no default HTTP endpoint that can be exposed remotely to cancel orders. For an immediate stop:
-
Interrupt the Quince process in its controlling terminal (
Ctrl-C). This stops new local order submission; it does not cancel orders already accepted by the venue. -
Use the exchange’s authenticated UI or its established emergency procedure to cancel open orders and, if needed, flatten the position. Verify the resulting account state there.
-
Disable or revoke the dedicated API key at the venue if credentials may be compromised.
-
Do not restart Quince yet. Inspect the local journal, reconcile every client order ID with the venue, and only then verify it:
cargo run --locked --bin quince -- journal inspect trades.orders.jsonl cargo run --locked --bin quince -- journal verify trades.orders.jsonl -
Preserve the journal and logs for incident review. Start the next session in
QUINCE_PUBLIC=1 QUINCE_SHADOW=1until the cause is understood.
The internal control plane is bounded and audited, but its HTTP transport is not enabled by the default dashboard. Do not rely on an unexposed endpoint as an emergency mechanism.
Native indicator catalogue
All entries below are compiled into the current binary. They consume public
trades and publish one finite f64 through quince.get("<name>"). A dash in
Parameters means that the directive takes no arguments. period is the
lookback length in trades; alpha is an exponential smoothing factor.
@using custom_ema:20
on trade(t) {
feature ema = quince.get("custom_ema")
}
Some indicators require warm-up and therefore do not yield a value until enough trades have arrived. Statistical and microstructure features are descriptive; they must be replay-tested rather than interpreted as a standalone order signal.
Trend and momentum
| Indicator | Parameters | Description |
|---|---|---|
custom_sma | period | Simple moving average of trade price; a slow, stable price baseline. |
custom_ema | period | Exponentially weighted moving average of price, with more weight on recent trades. |
custom_wma | period | Linearly weighted moving average that emphasizes newer prices. |
custom_dema | period | Double EMA, reducing lag relative to a single EMA. |
custom_tema | period | Triple EMA, a more aggressive lag-reduced moving average. |
custom_kama | period, fast, slow | Kaufman adaptive moving average; adapts smoothing to directional efficiency. |
custom_linear_regression | period | Rolling least-squares slope of price, expressing local trend direction. |
custom_momentum | period | Difference between current price and the price period trades ago. |
custom_roc | period | Percentage rate of change over a rolling trade lookback. |
custom_rsi | period | Relative Strength Index computed from trade-to-trade gains and losses. |
custom_cmo | period | Chande Momentum Oscillator, a signed gain/loss momentum measure. |
custom_macd_signal | fast, slow, signal | MACD signal line derived from fast and slow EMAs of price. |
custom_trix | period | Rate of change of a triple-smoothed EMA; suppresses short-term noise. |
custom_stochastic_k | period | Current price position within its rolling high-low range. |
custom_williams_r | period | Inverted high-low range oscillator indicating price location near extremes. |
custom_vortex | period | Directional-movement ratio over a rolling trade window. |
custom_efficiency_ratio | — | Price displacement divided by total absolute path; values near one indicate a clean move. |
custom_zscore | period | Price distance from its rolling mean in rolling standard deviations. |
Volatility and range
| Indicator | Parameters | Description |
|---|---|---|
custom_atr | period | Trade-level average true range, using absolute consecutive price changes. |
custom_true_range | — | Absolute change from the previous trade price. |
custom_bollinger_width | period | Width of a rolling price band; a compact proxy for dispersion. |
custom_donchian_width | period | Difference between the rolling high and low price. |
custom_historical_volatility | period | Rolling volatility of log returns. |
custom_ewma_volatility | alpha | Exponentially weighted volatility of log returns. |
custom_parkinson_volatility | period | Parkinson-scaled rolling root-mean-square of trade log returns. |
custom_return_variance | — | Online variance of log returns. |
custom_return_skewness | — | Online skewness of log returns; identifies asymmetry in return distribution. |
custom_return_kurtosis | — | Online excess-tailedness measure of log returns. |
custom_log_return | — | Natural logarithm of current price divided by previous price. |
Volume and money flow
| Indicator | Parameters | Description |
|---|---|---|
signed_volume | — | Cumulative buy quantity minus sell quantity. |
custom_signed_volume_ratio | — | Signed volume normalized by cumulative total volume. |
custom_buy_volume_ratio | — | Cumulative fraction of traded quantity initiated by buyers. |
custom_obv | — | On-balance volume: volume added or subtracted according to price direction. |
custom_cvd | — | Cumulative volume delta: buy quantity minus sell quantity over time. |
custom_vwap | — | Cumulative volume-weighted average trade price. |
custom_vwma | period | Rolling volume-weighted moving average of price. |
custom_mfi | period | Money Flow Index based on typical-price changes and traded quantity. |
custom_money_flow | — | Signed typical-price times quantity flow. |
custom_force_index | alpha | Smoothed price-change times quantity measure. |
custom_chaikin_oscillator | fast_alpha, slow_alpha | Difference between fast and slow exponentially smoothed money flow. |
custom_volume_roc | period | Percentage rate of change of trade quantity. |
custom_volume_zscore | period | Trade quantity relative to its rolling mean and deviation. |
custom_large_trade_ratio | threshold | Cumulative share of trades whose quantity meets the threshold. |
custom_average_trade_size | — | Running arithmetic mean of trade quantity. |
Microstructure and price transforms
| Indicator | Parameters | Description |
|---|---|---|
custom_trade_imbalance | — | Buy-versus-sell trade-count imbalance. |
custom_trade_intensity | — | Trade arrival intensity estimated from event timestamps. |
custom_price_impact | — | Absolute price move per unit of current trade quantity. |
custom_tick_direction | — | Sign of the most recent trade-to-trade price move. |
custom_tick_run_length | — | Length of the current uninterrupted directional tick run. |
custom_median_price | — | Running midpoint of the observed minimum and maximum trade price. |
custom_typical_price | — | Current trade price, exposed through an explicit custom-indicator contract. |
custom_logistic_regression | learning_rate, l2 | Online logistic model of trade log returns; emits model buy-pressure probability in [0, 1]. |
Selecting a feature
Begin with one feature per hypothesis: trend (custom_ema or
custom_linear_regression), volatility (custom_ewma_volatility), flow
(custom_cvd or custom_buy_volume_ratio), or microstructure
(custom_price_impact). Treat closely related variants as correlated features,
not independent confirmation. Keep a strategy in shadow/replay mode until its
fee- and slippage-adjusted out-of-sample behavior is understood.
Writing a native indicator
Each native plugin is one Rust file in indicators/src/custom/. The build
script discovers those files in deterministic filename order and compiles a
static registry into the binary.
Contract
Every indicator declares a name, ordered numeric parameters, and a factory.
It receives a public Trade and may yield one finite f64 value. Returning
None expresses warm-up; it is not an error. The update method must not block
or allocate on the hot path.
#![allow(unused)]
fn main() {
use quince_core::types::Trade;
use quince_indicators::{CustomIndicator, CustomIndicatorError};
struct MyIndicator;
impl CustomIndicator for MyIndicator {
fn on_trade(&mut self, trade: &Trade) -> Option<f64> {
(trade.price.is_finite() && trade.price > 0.0).then_some(trade.price)
}
}
}
Use CustomIndicatorRegistration::validate_params in the factory before
constructing state. The engine independently validates the exact @using
arguments at strategy startup, so malformed configurations fail before any live
connection or order intent.
QFL surface
For a descriptor named custom_example with one period parameter:
@using custom_example:20
on trade(t) {
feature value = quince.get("custom_example")
}
Names are lowercase ASCII identifiers with digits and underscores allowed after
the first character. All current plugins consume trades and expose one scalar
value. The name in quince.get must exactly match the descriptor name.
Required checks
Add focused deterministic tests for warm-up, expected output, and invalid parameters. Before merging, run:
cargo +nightly fmt --all -- --check
cargo test --workspace --lib --bins --tests --examples --locked
cargo clippy --workspace --all-targets --no-deps -- -D warnings
For a performance-sensitive indicator, add or run a Criterion scenario against the full QFL pipeline, then compare it to the versioned baseline in CI.
Module: ast
Source:
ast.rs
QFL AST node definitions — expressions, statements, and the program root.
Defines the typed AST produced by the parser and consumed by the compiler:
[Expr], [Stmt], [Literal], [BinOp], [UnaryOp], and [Program].
Structs
pub struct FnParam
#![allow(unused)]
fn main() {
pub struct FnParam {
pub name: String,
pub type_name: String,
};
}
A typed function parameter: name: type.
pub struct UsingEntry
#![allow(unused)]
fn main() {
pub struct UsingEntry {
pub name: String,
pub params: Vec < f64 >,
};
}
An entry in the @using directive specifying an indicator and its parameters.
Enums
pub enum BinOp
#![allow(unused)]
fn main() {
pub enum BinOp {
Add,
Sub,
Mul,
Div,
IDiv,
Mod,
Pow,
Concat,
Eq,
Ne,
Lt,
Gt,
Le,
Ge,
And,
Or,
}
}
Binary operators supported in QFL expressions.
Includes arithmetic (+, -, *, /, //, %, ^),
comparison (==, ~=, <, >, <=, >=),
concatenation (..), and logical (and, or).
pub enum UnaryOp
#![allow(unused)]
fn main() {
pub enum UnaryOp {
Neg,
Not,
Len,
}
}
Unary operators: negation (-), logical not (not), length (#).
pub enum Literal
#![allow(unused)]
fn main() {
pub enum Literal {
Nil,
Bool(bool,),
I64(i64,),
F64(f64,),
String(String,),
}
}
Literal values in QFL: nil, booleans, integers, floats, and strings.
pub enum Expr
#![allow(unused)]
fn main() {
pub enum Expr {
Literal(Literal,),
Ident(String,),
FnCall(name: String,
args: Vec < Expr >,),
MethodCall(obj: String,
method: String,
args: Vec < Expr >,),
FieldAccess(obj: Box < Expr >,
field: String,),
Index(obj: Box < Expr >,
index: Box < Expr >,),
Unary(op: UnaryOp,
expr: Box < Expr >,),
Binary(lhs: Box < Expr >,
op: BinOp,
rhs: Box < Expr >,),
Table(Vec < TableField >,),
}
}
QFL expression node. Covers literals, identifiers, function/method calls, field/index access, unary and binary operations, and table constructors.
pub enum TableField
#![allow(unused)]
fn main() {
pub enum TableField {
KeyValue(key: Expr,
value: Expr,),
Value(Expr,),
}
}
A field in a table constructor: either [key] = value or a plain value.
pub enum Stmt
#![allow(unused)]
fn main() {
pub enum Stmt {
VarDecl(names: Vec < String >,
type_name: Option < String >,
init: Option < Vec < Expr > >,
is_local: bool,
persist: bool,),
Assign(targets: Vec < Expr >,
exprs: Vec < Expr >,),
If(cond: Box < Expr >,
then_body: Vec < Stmt >,
elseif_branches: Vec < (Box < Expr > , Vec < Stmt >) >,
else_body: Vec < Stmt >,),
While(cond: Box < Expr >,
body: Vec < Stmt >,),
Repeat(body: Vec < Stmt >,
until: Box < Expr >,),
ForNum(var: String,
from: Box < Expr >,
to: Box < Expr >,
step: Option < Box < Expr > >,
body: Vec < Stmt >,),
ForIn(vars: Vec < String >,
exprs: Vec < Expr >,
body: Vec < Stmt >,),
FunctionDecl(name: String,
params: Vec < String >,
body: Vec < Stmt >,),
Return(exprs: Vec < Expr >,),
ExprStmt(Expr,),
Using(indicators: Vec < UsingEntry >,),
Window(name: String,
capacity: usize,),
Exchange(name: String,),
Network(name: String,),
Feature(name: String,
expr: Box < Expr >,),
Signal(name: String,
expr: Box < Expr >,),
EventHandler(event: String,
param: Option < String >,
body: Vec < Stmt >,),
FnDecl(name: String,
params: Vec < FnParam >,
return_type: String,
body: Vec < Stmt >,),
}
}
QFL statement node. Includes variable declarations, assignments, control flow (if/while/repeat/for), function definitions, event handlers, and declarative pipeline statements (using, window, feature, signal, state).
Type Aliases
pub type Program
#![allow(unused)]
fn main() {
pub type Program = Vec < Stmt >;
}
The top-level QFL program: a list of statements
Module: checker
Source:
checker.rs
QFL static analysis — linter for common mistakes and anti-patterns.
Checks source files for:
- C-style operators (
!=,&&,||,:=,++) that are invalid in QFL - Misspelled directives (
@persit→@persist) - Trailing whitespace, mixed indentation, overly long lines
- Unterminated strings and block comments
- UTF-8 BOM, shebang lines, carriage returns, missing trailing newlines
Entry point: [check()] returns a list of [Diagnostic]s.
Structs
pub struct Diagnostic
#![allow(unused)]
fn main() {
pub struct Diagnostic {
pub severity: Severity,
pub line: usize,
pub col: usize,
pub message: String,
pub suggestion: Option < String >,
};
}
A single diagnostic: error or warning at a specific source location.
Enums
pub enum Severity
#![allow(unused)]
fn main() {
pub enum Severity {
Error,
Warning,
}
}
Severity level of a diagnostic message.
Functions
pub fn check
#![allow(unused)]
fn main() {
pub fn check(...) { ... }
}
Run all static checks on a QFL source string.
Returns a list of [Diagnostic]s (sorted by appearance order).
Returns an empty vec for valid, clean code.
Module: compiler
Source:
compiler.rs
QFL AST в†’ IR bytecode compiler.
Translates a type-checked [Program] AST into a [QfrProgram] bytecode
representation. Allocates registers, emits opcodes, and builds the constant
pool and entry-point table.
Entry point: [compile()].
Functions
pub fn compile
#![allow(unused)]
fn main() {
pub fn compile(...) { ... }
}
Top-level entry point: compile a QFL AST Program into a QfrProgram (bytecode).
Returns Err(Vec<TypeError>) if compilation errors occur (e.g. register overflow).
pub fn compile_checked
#![allow(unused)]
fn main() {
pub fn compile_checked(...) { ... }
}
Type-check the program first, then compile if it passes.
Returns Err(Vec<TypeError>) if type checking or compilation fails.
Module: config
Source:
config.rs
Strategy-level exchange configuration parsed from QFL directives.
Structs
pub struct StrategyConfig
#![allow(unused)]
fn main() {
pub struct StrategyConfig {
pub exchange: ExchangeKind,
pub network: Network,
};
}
Enums
pub enum ExchangeKind
#![allow(unused)]
fn main() {
pub enum ExchangeKind {
Binance,
Hyperliquid,
}
}
pub enum Network
#![allow(unused)]
fn main() {
pub enum Network {
Mainnet,
Testnet,
}
}
Functions
pub fn parse_strategy_config
#![allow(unused)]
fn main() {
pub fn parse_strategy_config(...) { ... }
}
Parse configuration directives without compiling the strategy bytecode.
pub fn load_strategy_config
#![allow(unused)]
fn main() {
pub fn load_strategy_config(...) { ... }
}
Module: ir
Source:
ir.rs
QFL IR (Intermediate Representation) — serializable bytecode format.
Defines [QfrProgram] (V1/V2), the [EntryPoint] table, [ConstEntry] pool,
and [quince_hash64] checksum. Supports binary serialization/deserialization
with mmap-compatible V2 format.
Entry points: save_qfr(), [load_qfr()].
Structs
pub struct EntryPoint
#![allow(unused)]
fn main() {
pub struct EntryPoint {
pub name: String,
pub code_offset: u32,
};
}
Legacy entry point (compiler side)
pub struct QfrProgram
#![allow(unused)]
fn main() {
pub struct QfrProgram {
pub entries: Vec < EntryPoint >,
pub const_pool: Vec < ConstEntry >,
pub code: Vec < Instruction >,
pub const_map: HashMap < String , u32 >,
pub ema_alphas: Vec < f64 >,
pub f64_consts: Vec < f64 >,
pub i64_consts: Vec < i64 >,
pub string_consts: Vec < String >,
};
}
Legacy program representation used by the compiler
pub struct QfrBinarized
#![allow(unused)]
fn main() {
pub struct QfrBinarized {
pub magic: [u8 ; 4],
pub version: u16,
pub entry_count: u16,
pub num_constants: u32,
pub num_instructions: u32,
pub persist_mask: [u64 ; 4],
_reserved: [u8 ; 16],
};
}
Binary header — byte-exact layout for memory mapping. Total header size: 64 bytes (cache-line aligned).
pub struct QfrEntry
#![allow(unused)]
fn main() {
pub struct QfrEntry {
pub name_offset: u32,
pub name_len: u32,
pub code_offset: u32,
_pad: u32,
};
}
Entry point descriptor in the binary format.
pub struct Loader
#![allow(unused)]
fn main() {
pub struct Loader {
_mmap: memmap2 :: Mmap,
pub header: NonNull < QfrBinarized >,
pub constants_ptr: * const f64,
pub instructions_ptr: * const u64,
pub entry_count: u16,
pub const_count: u32,
pub instr_count: u32,
};
}
Zero-copy loader — memory-maps a .qfr file and exposes raw pointers.
Enums
pub enum ConstEntry
#![allow(unused)]
fn main() {
pub enum ConstEntry {
I64(i64,),
F64(f64,),
String(String,),
}
}
Legacy const pool entry (compiler side)
Functions
pub fn quince_hash64
#![allow(unused)]
fn main() {
pub fn quince_hash64(...) { ... }
}
pub fn serialize_binarized
#![allow(unused)]
fn main() {
pub fn serialize_binarized(...) { ... }
}
Serialize a QfrProgram into the zero-copy mmap-compatible binary format.
pub fn deserialize_binarized
#![allow(unused)]
fn main() {
pub fn deserialize_binarized(...) { ... }
}
Deserialize from binarized format back to QfrProgram (for backward compat).
pub fn serialize_v1
#![allow(unused)]
fn main() {
pub fn serialize_v1(...) { ... }
}
pub fn deserialize_v1
#![allow(unused)]
fn main() {
pub fn deserialize_v1(...) { ... }
}
pub fn serialize
#![allow(unused)]
fn main() {
pub fn serialize(...) { ... }
}
pub fn deserialize
#![allow(unused)]
fn main() {
pub fn deserialize(...) { ... }
}
Constants
pub const QFR_MAGIC_V1
#![allow(unused)]
fn main() {
pub const QFR_MAGIC_V1: & [u8 ; 4] = ...;
}
pub const QFR_MAGIC_V2
#![allow(unused)]
fn main() {
pub const QFR_MAGIC_V2: & [u8 ; 4] = ...;
}
pub const QFRC_MAGIC
#![allow(unused)]
fn main() {
pub const QFRC_MAGIC: [u8 ; 4] = ...;
}
pub const QFRC_FOOTER_SIZE
#![allow(unused)]
fn main() {
pub const QFRC_FOOTER_SIZE: usize = ...;
}
pub const QFR_VERSION_V1
#![allow(unused)]
fn main() {
pub const QFR_VERSION_V1: u32 = ...;
}
pub const QFR_VERSION_V2
#![allow(unused)]
fn main() {
pub const QFR_VERSION_V2: u16 = ...;
}
Module: lexer
Source:
lexer.rs
QFL lexer — tokenises source text into 73 token kinds.
Produces a [Token] stream consumed by the Pratt parser. Handles string
escapes, block comments, Lua-style -- comments, and @directive markers.
Entry point: [tokenize()] or [Lexer::tokenize()].
Structs
pub struct LexerError
#![allow(unused)]
fn main() {
pub struct LexerError {
pub msg: String,
pub line: usize,
pub col: usize,
};
}
An error produced during lexing with source position information.
pub struct Lexer
#![allow(unused)]
fn main() {
pub struct Lexer {
chars: Vec < char >,
pos: usize,
line: usize,
col: usize,
};
}
Character-level lexer that scans QFL source text into tokens.
Enums
pub enum Token
#![allow(unused)]
fn main() {
pub enum Token {
Function,
Local,
If,
Then,
Else,
ElseIf,
End,
While,
Do,
Repeat,
Until,
For,
In,
Return,
And,
Or,
Not,
Nil,
True,
False,
Number(String,),
String(String,),
Ident(String,),
Plus,
Minus,
Star,
Slash,
SlashSlash,
Percent,
Caret,
Hash,
Dot,
Comma,
Colon,
Semi,
LParen,
RParen,
LBrace,
RBrace,
LBracket,
RBracket,
Eq,
EqEq,
TildeEq,
Lt,
Gt,
LtEq,
GtEq,
Concat,
VarArg,
Arrow,
AtPersist,
AtUsing,
AtWindow,
AtExchange,
AtNetwork,
On,
Fn,
Comment(String,),
Eof,
}
}
A single token produced by the QFL lexer. Covers 73 variants including keywords, literals, operators, symbols, directives (@persist, @using, @window), and phase-4h keywords (state, on, fn).
Functions
pub fn tokenize
#![allow(unused)]
fn main() {
pub fn tokenize(...) { ... }
}
Tokenise a QFL source string into a token vector. Validates input size (max 1 MiB), rejects null bytes, and reports line/col on errors.
Module: lib
Source:
lib.rs
QFL (Quince-flavored Language) — a domain-specific embedded language for algorithmic trading strategies.
The pipeline: source text в†’ [lexer] в†’ tokens в†’ [parser] в†’ AST в†’ [type checker] в†’ annotated AST в†’ [compiler] в†’ QfrProgram (IR) в†’ [optimizer] в†’ optimized bytecode в†’ [VM] execution.
Architecture
| Module | Role |
|---|---|
[lexer] | Tokenises QFL source into 73 token kinds |
[parser] | Pratt parser producing an AST |
[ast] | AST node definitions (Expr, Stmt, BinOp, etc.) |
[types] | Domain-specific type system (10 types) |
[compiler] | AST в†’ IR bytecode compilation |
[opcodes] | 70 opcodes with jump-table dispatch |
[ir] | QfrProgram bytecode format (V1/V2) |
[optimize] | 11-pass optimisation pipeline |
[vm] | Register-based VM (Hot/Cold split) |
[runtime] | QFL <-> trading engine bridge |
[risk] | Risk limits and order validation |
[profiler] | Opcode counts and handler timing |
[tracer] | Event ring buffer (signals, fills, risk) |
[log_buffer] | Debug-only ring buffer for strategy logs |
Module: log_buffer
Source:
log_buffer.rs
Debug-only ring buffer for strategy log messages.
Stores the most recent max log entries, dropping oldest when full.
Only compiled in debug_assertions builds.
Structs
pub struct LogBuffer
#![allow(unused)]
fn main() {
pub struct LogBuffer {
entries: VecDeque < String >,
max: usize,
};
}
Ring buffer for strategy log messages.
Drops oldest entries when max capacity is reached.
Module: opcodes
Source:
opcodes.rs
QFL opcode definitions and instruction encoding.
Defines the [Opcode] enum (70 opcodes), the [Instruction] wrapper (u64),
and encoding/decoding helpers (Ri40, RRI, RRR).
Instruction layout: [opcode:8][rd:8][rs1:8][rs2:8][imm:32]
Structs
pub struct Instruction
#![allow(unused)]
fn main() {
pub struct Instruction(u64,);;
}
Raw 64-bit instruction (opcode in bits 0-7 for zero-shift dispatch)
Enums
pub enum InstrEncoding
#![allow(unused)]
fn main() {
pub enum InstrEncoding {
RRR,
RR,
RRI,
RI,
RI40,
Single,
}
}
pub enum Opcode
#![allow(unused)]
fn main() {
pub enum Opcode {
Add,
Sub,
Mul,
Div,
Mod,
Neg,
AddI,
SubI,
MulI,
DivI,
FAdd,
FSub,
FMul,
FDiv,
FNeg,
Eq,
Ne,
Lt,
Gt,
Le,
Ge,
FEq,
FNe,
FLt,
FGt,
FLe,
FGe,
EqI,
LtI,
GtI,
BitAnd,
BitOr,
BitXor,
BitNot,
Shl,
Shr,
Jmp,
Jz,
Jnz,
Call,
Ret,
Mov,
Ldi,
Ldi64,
LdcF64,
I2F,
F2I,
GetInd,
GetPrice,
GetPos,
GetBal,
GetDepthBid,
GetDepthAsk,
SendOrder,
PersistGet,
PersistSet,
Log,
Halt,
WindowPush,
WindowMean,
WindowStddev,
WindowMin,
WindowMax,
WindowSum,
Ema,
Log2,
LdI64,
LdcStr,
Pow,
FPow,
Sentinel,
}
}
Constants
pub const OPCODE_BITS
#![allow(unused)]
fn main() {
pub const OPCODE_BITS: u32 = ...;
}
pub const REGISTER_BITS
#![allow(unused)]
fn main() {
pub const REGISTER_BITS: u32 = ...;
}
pub const IMM_BITS
#![allow(unused)]
fn main() {
pub const IMM_BITS: u32 = ...;
}
pub const SENTINEL_OPCODE
#![allow(unused)]
fn main() {
pub const SENTINEL_OPCODE: u8 = ...;
}
Module: optimize
Source:
optimize.rs
QFL bytecode optimizer — 11-pass pipeline over compiled QfrPrograms.
Pipeline (each pass feeds the next):
constant_fold— evaluate constant expressions within basic blockscfg_simplify— merge blocks, remove unreachable code, simplify jumpssccp— sparse conditional constant propagation (cross-block)cse— common subexpression elimination (per-block)local_shadowing— PersistGet/Set forwarding within blockslicm— loop-invariant code motionloop_unroll— unroll small constant-iteration loopsfused_lowering— peephole patterns (Mov chains, zero-based idioms)persist_coalesce— merge adjacent persist operationsdead_code_eliminate— remove unreachable or unused instructionsglobal_value_numbering— redundant computation elimination
Entry point: [optimize()].
Functions
pub fn optimize
#![allow(unused)]
fn main() {
pub fn optimize(...) { ... }
}
Run the full optimization pipeline on a compiled program. Pipeline order (each pass feeds the next):
- constant_fold — evaluate constant expressions within blocks
- cfg_simplify — merge blocks, remove unreachable code, simplify jumps
- sccp — sparse conditional constant propagation (cross-block)
- cse — common subexpression elimination (per-block)
- local_shadowing — PersistGet/Set forwarding within blocks
- licm — loop-invariant code motion
- loop_unroll — unroll small constant-iteration loops
- fused_lowering — peephole patterns (Mov chains, zero-based idioms)
- gvn — global value numbering (cross-block CSE via dominators)
- dce — dead code elimination (instruction-level reachability)
- persist_coalesce — redundant PersistGet/Set removal (slot-shadowing)
pub fn dead_code_eliminate
#![allow(unused)]
fn main() {
pub fn dead_code_eliminate(...) { ... }
}
Dead Code Elimination pass. Removes instructions unreachable from any entry point. Uses instruction-level reachability tracing (unlike CFG-based which traces blocks). Correctly adjusts jump offsets for remaining instructions.
pub fn common_subexpr_elim
#![allow(unused)]
fn main() {
pub fn common_subexpr_elim(...) { ... }
}
Common Subexpression Elimination pass. Within a basic block, replaces repeated identical computations with Mov from the first result register. Uses a hashmap keyed on (opcode, rs1, operand2) to detect duplicates within the block.
pub fn constant_fold
#![allow(unused)]
fn main() {
pub fn constant_fold(...) { ... }
}
Constant-folding pass. Folds arithmetic on known-constant registers within each basic block.
pub fn cfg_simplify
#![allow(unused)]
fn main() {
pub fn cfg_simplify(...) { ... }
}
CFG Simplification pass. Builds a control flow graph, merges consecutive basic blocks, removes unreachable blocks, and simplifies jump chains.
pub fn sccp
#![allow(unused)]
fn main() {
pub fn sccp(...) { ... }
}
Sparse Conditional Constant Propagation. Uses a lattice (Top в†’ Constant в†’ Bottom) per register, propagating across the CFG. Conditional branches with constant predicates are folded: the unreachable successor is marked non-executable. After convergence, known-constant expressions are replaced with Ldi/Ldi64/Ldc, and blocks gated by a folded branch are removed.
pub fn persist_coalesce
#![allow(unused)]
fn main() {
pub fn persist_coalesce(...) { ... }
}
PersistGet/Set coalescing optimization. Removes redundant PersistGet when the same slot is already cached in a register, and removes redundant PersistSet when the register value hasn’t changed since the last PersistGet of the same slot.
Module: parser
Source:
parser.rs
QFL Pratt parser — token stream в†’ AST.
Implements a Pratt (precedence-climbing) parser over the [Token] stream
from the lexer. Produces a [Program] AST for subsequent type-checking
and compilation.
Entry point: [Parser::parse()].
Structs
pub struct ParseError
#![allow(unused)]
fn main() {
pub struct ParseError {
pub msg: String,
pub pos: usize,
};
}
Error produced during parsing, carrying the message and token position.
pub struct Parser
#![allow(unused)]
fn main() {
pub struct Parser {
tokens: Vec < Token >,
pos: usize,
};
}
Functions
pub fn parse
#![allow(unused)]
fn main() {
pub fn parse(...) { ... }
}
Module: profiler
Source:
profiler.rs
QFL VM performance profiler.
Tracks opcode execution counts, per-opcode RDTSC cycles, and per-handler
timing. Zero-allocation in the hot path when None.
Entry points: [Profiler::record_opcode()], [Profiler::profile()].
Structs
pub struct OpcodeProfile
#![allow(unused)]
fn main() {
pub struct OpcodeProfile {
pub opcode: Opcode,
pub count: u64,
pub cycles: u64,
};
}
Opcode execution profile for a single run.
pub struct HandlerSample
#![allow(unused)]
fn main() {
pub struct HandlerSample {
pub name: String,
pub elapsed_ns: u64,
pub instr_count: u64,
};
}
Per-handler timing sample.
pub struct Profiler
#![allow(unused)]
fn main() {
pub struct Profiler {
opcode_counts: [u64 ; 65],
opcode_cycles: [u64 ; 65],
handler_samples: Vec < HandlerSample >,
current_handler: Option < String >,
handler_start: Option < Instant >,
handler_start_instr: u64,
pub total_instructions: u64,
};
}
Execution profiler.
Functions
pub fn rdtsc
#![allow(unused)]
fn main() {
pub fn rdtsc(...) { ... }
}
Read the x86_64 timestamp counter (RDTSC) for cycle-accurate profiling. Returns 0 on non-x86 platforms (no cycle data available).
Module: risk
Source:
risk.rs
QFL risk engine — runtime-enforced trading limits.
Intercepts orders before they reach the exchange connector. Rejects orders that violate configured limits (max position, max notional, max orders/cycle).
Entry point: [RiskEngine::check_order()].
Structs
pub struct RiskLimits
#![allow(unused)]
fn main() {
pub struct RiskLimits {
pub max_position: f64,
pub max_order_notional: f64,
pub max_orders_per_cycle: u32,
};
}
Runtime-enforced risk limits.
pub struct RiskEngine
#![allow(unused)]
fn main() {
pub struct RiskEngine {
pub limits: RiskLimits,
pub current_position: f64,
orders_this_cycle: u32,
};
}
Runtime risk engine.
Enums
pub enum RiskVerdict
#![allow(unused)]
fn main() {
pub enum RiskVerdict {
Allowed,
Rejected(String,),
}
}
Result of a risk check.
Module: runtime
Source:
runtime.rs
QFL runtime — high-level interface between the trading engine and the VM.
Owns a [Vm], a compiled strategy path, symbol context, an order-sending
channel, and a RiskEngine. Exposes feed_*
methods that push external events (trade, depth, fill, eval) into the VM.
Entry point: [QflRuntime::load()].
Structs
pub struct QflRuntime
#![allow(unused)]
fn main() {
pub struct QflRuntime {
vm: Vm,
path_qfl: PathBuf,
current_symbol: Arc < str >,
orders_tx: Option < crossbeam_channel :: Sender < quince_core :: types :: Order > >,
pub risk_engine: crate :: risk :: RiskEngine,
};
}
Enums
pub enum Event
#![allow(unused)]
fn main() {
pub enum Event {
Trade(Trade,),
Depth(Depth,),
Fill(OrderFill,),
Eval,
}
}
Unified exchange event dispatched to the QFL runtime.
Each variant triggers a different handler (on_trade, on_depth, etc.)
inside the VM.
Module: tracer
Source:
tracer.rs
QFL event tracer — ring buffer for strategy execution events.
Records [TraceEvent]s (Signal, Feature, Fill, RiskAction) for post-hoc
analysis. Fixed-capacity ring buffer; drops oldest events when full.
Entry point: [Tracer::record()].
Structs
pub struct Tracer
#![allow(unused)]
fn main() {
pub struct Tracer {
events: Vec < TraceEvent >,
capacity: usize,
};
}
Ring-buffer event tracer for strategy execution. Records signals, features, fills, and risk actions for post-hoc analysis. Zero-allocation in the hot path when capacity is 0.
Enums
pub enum TraceEvent
#![allow(unused)]
fn main() {
pub enum TraceEvent {
Signal(kind: String,
result: bool,),
Feature(name: String,
value: f64,),
Fill(price: f64,
qty: f64,
side: String,),
RiskAction(verdict: String,
reason: String,),
}
}
A recorded event for post-hoc analysis of strategy execution. Each variant carries domain-specific payload:
Signal: a strategy signal (opcode comparison result)Feature: a computed feature value (e.g. EMA, SMA)Fill: an executed order fillRiskAction: a risk engine verdict
Module: types
Source:
types.rs
QFL type system — strong domain-specific types for algorithmic trading.
Rules:
- Numeric types (
I64,F64,Price,Qty,Timestamp,Duration) support arithmetic within their group and with direct promotion rules. - Domain types (
Symbol,Side,OrderId,Bool) are NOT numeric and do NOT support arithmetic. Price + Price в†’ Price,Price + Duration в†’ Price,Price * Qty в†’ PricePrice + Side в†’ TypeError
Entry point: [check_program()] validates a typed AST.
Structs
pub struct TypeError
#![allow(unused)]
fn main() {
pub struct TypeError {
pub msg: String,
};
}
A type error with a message.
Enums
pub enum QflType
#![allow(unused)]
fn main() {
pub enum QflType {
I64,
F64,
Bool,
Timestamp,
Duration,
Price,
Qty,
Symbol,
Side,
OrderId,
}
}
Strongly-typed domain value.
Functions
pub fn parse_state_type
#![allow(unused)]
fn main() {
pub fn parse_state_type(...) { ... }
}
Parse a state declaration type string to QflType. e.g. “f64” в†’ QflType::F64, “qty” в†’ QflType::Qty, “i32” в†’ QflType::I64
pub fn bin_op_type
#![allow(unused)]
fn main() {
pub fn bin_op_type(...) { ... }
}
Determine the result type for lhs op rhs.
Returns Err(TypeError) if the operation is invalid.
pub fn unary_op_type
#![allow(unused)]
fn main() {
pub fn unary_op_type(...) { ... }
}
Determine the result type for op expr.
pub fn literal_type
#![allow(unused)]
fn main() {
pub fn literal_type(...) { ... }
}
Infer the type of an AST literal.
pub fn type_check
#![allow(unused)]
fn main() {
pub fn type_check(...) { ... }
}
Run type-checking on a parsed QFL program.
Returns Ok(()) if valid, or Err(Vec<TypeError>) listing all errors.
Type Aliases
pub type TypeResult
#![allow(unused)]
fn main() {
pub type TypeResult = Result < QflType , TypeError >;
}
Result type for binary operations, or a TypeError.
Module: vm
Source:
vm.rs
QFL bytecode VM — register-based interpreter with direct threaded dispatch.
Architecture
The VM executes compiled [QfrProgram]s via a 256-entry function pointer table
([DISPATCH_TABLE]). Each instruction is a packed u64, decoded by bit-field
extractors (rd, rs1, rs2, imm).
Hot / Cold split
The hot path (registers, PC, call stack, raw code pointer) lives in [Vm] (~2 KB,
fits in L1). Cold data (indicators, balances, depth book, windows, persist) lives
behind Box<ColdVm> (~30+ KB, L2/L3). This keeps the dispatch loop cache-friendly.
Register file
256 slots: regs 0..=191 are conventionally integer (i64), 192..=255 float
(f64). Stored as a union Register (#[repr(C)]) for zero-overhead access.
Dispatch
The single entry point is [Vm::call] which looks up an entry offset by name,
sets vm.pc, and calls [Vm::run]. run fetches the first instruction and
dispatches via [DISPATCH_TABLE]. Each handler finishes with
become dispatch_next(vm, instr) — a guaranteed tail-call that advances pc,
fetches, and dispatches the next instruction. Control-flow handlers (vm_jmp,
vm_call, etc.) set pc directly before tail-calling. vm_halt returns
normally, unwinding the flat dispatch stack back to run.
Safety
Handlers use unchecked register access (get_unchecked) and raw pointer arithmetic
on code_ptr. Preconditions are documented per-handler via # Safety sections.
The VM is not thread-safe; each [Vm] is pinned to one thread.
Structs
pub struct PersistSlot
#![allow(unused)]
fn main() {
pub struct PersistSlot {
pub tag: u8,
pub int_val: i64,
pub float_val: f64,
};
}
A single persist slot — survives across hot-reload cycles.
tag determines which field carries the value:
pub struct EmaState
#![allow(unused)]
fn main() {
pub struct EmaState {
pub alpha: f64,
pub value: f64,
pub initialized: bool,
};
}
EMA (Exponential Moving Average) state for one slot.
Used by the vm_ema opcode. On first push (initialized == false) the value
is seeded directly; thereafter it updates as value = alpha * input + (1 - alpha) * value.
pub struct WindowMeta
#![allow(unused)]
fn main() {
pub struct WindowMeta {
pub offset: u16,
pub capacity: u16,
pub head: u16,
pub len: u16,
pub sum: f64,
pub sum_sq: f64,
pub min: f64,
pub max: f64,
pub min_deque: [u8 ; 64],
pub max_deque: [u8 ; 64],
pub min_dq_front: u8,
pub min_dq_back: u8,
pub max_dq_front: u8,
pub max_dq_back: u8,
};
}
pub struct ColdVm
#![allow(unused)]
fn main() {
pub struct ColdVm {
pub indicators: [f64 ; MAX_INDICATORS],
pub indicator_by_str: Vec < u16 >,
pub balances: [f64 ; MAX_BALANCES],
pub balance_by_str: Vec < u16 >,
pub depth_bids_price: [f64 ; MAX_DEPTH_LEVELS],
pub depth_bids_qty: [f64 ; MAX_DEPTH_LEVELS],
pub depth_asks_price: [f64 ; MAX_DEPTH_LEVELS],
pub depth_asks_qty: [f64 ; MAX_DEPTH_LEVELS],
pub depth_bids_len: u8,
pub depth_asks_len: u8,
pub persist: [PersistSlot ; PERSIST_SLOTS],
pub window_arena: Vec < f64 >,
pub window_meta: [WindowMeta ; MAX_WINDOWS],
pub ema_states: [EmaState ; MAX_EMA_STATES],
_code_owned: Vec < u64 >,
_consts_owned: Vec < f64 >,
_i64_consts_owned: Vec < i64 >,
pub const_pool: Vec < ConstEntry >,
pub const_strings: Vec < String >,
pub indicator_map: HashMap < String , u16 >,
pub balance_map: HashMap < String , u16 >,
pub profiler: Option < crate :: profiler :: Profiler >,
pub tracer: Option < crate :: tracer :: Tracer >,
pub trace_vm_enabled: bool,
pub trace_file: Option < std :: io :: BufWriter < std :: fs :: File > >,
pub trace_start: std :: time :: Instant,
pub log_buffer: Option < crate :: log_buffer :: LogBuffer >,
};
}
Cold (L2/L3) VM data — behind a Box to keep [Vm] cache-friendly.
Contains large arrays (~30+ KB) pushed out of L1: indicators, balances,
depth book, persist slots, window arena, EMA states, and profiling/tracing
infrastructure. Accessed through [Vm::cold].
pub struct Vm
#![allow(unused)]
fn main() {
pub struct Vm {
pub regs: [Register ; NUM_REGS],
pub pc: usize,
pub running: bool,
pub call_stack: [usize ; MAX_CALL_DEPTH],
pub call_depth: u8,
instruction_budget: u32,
instructions_remaining: u32,
last_event_instruction_count: u32,
instruction_budget_exhausted: bool,
pub code_ptr: * const u64,
pub code_len: usize,
pub consts_ptr: * const f64,
pub const_count: u32,
pub i64_consts_ptr: * const i64,
pub i64_const_count: u32,
pub last_price: f64,
pub position_size: f64,
pub has_pending_order: bool,
pub entry_names: [u64 ; 8],
pub entry_offsets: [u32 ; 8],
pub entry_count: u8,
handler_cache: [u32 ; 4],
pub cold: Box < ColdVm >,
};
}
Hot VM — the primary interpreter struct, sized to fit in L1 cache (~2 KB).
Registers, PC, call stack, and raw code pointers live here. All cold
(large-array) state lives in [ColdVm] behind a Box.
Thread safety
Vm is not Send or Sync. Each instance must remain on one thread.
pub struct VmSnapshot
#![allow(unused)]
fn main() {
pub struct VmSnapshot {
pub regs: [Register ; NUM_REGS],
pub persist: [PersistSlot ; PERSIST_SLOTS],
pub pc: usize,
pub indicators: [f64 ; MAX_INDICATORS],
pub balances: [f64 ; MAX_BALANCES],
};
}
Snapshot of VM state that survives hot-reload.
Captured by [Vm::snapshot] before a hot-reload and restored by
[Vm::restore] afterwards. Carries registers, persist slots, program
counter, indicators, and balances.
Unions
pub union Register
#![allow(unused)]
fn main() {
pub union Register { ... }
}
A single register slot — stores either an i64 or f64 via union.
Regs 0..=191 are conventionally integer, 192..=255 float.
Access via [Self::from_i64], [Self::from_f64], or directly through the union
fields (reg.i, reg.f).
Functions
pub fn dispatch_next
#![allow(unused)]
fn main() {
pub fn dispatch_next(...) { ... }
}
Tail-call helper: advance PC, fetch next instruction, dispatch.
Every normal handler ends with become dispatch_next(vm, instr).
Control-flow handlers (jmp, jz, jnz, call, ret) set vm.pc directly,
then tail-call [dispatch_current] to charge and dispatch the target.
Safety
vm.code_ptrmust point to valid bytecode with at leastvm.pc + 1instructions.- Caller must ensure
vmis in a consistent state before dispatching.
pub fn dispatch_current
#![allow(unused)]
fn main() {
pub fn dispatch_current(...) { ... }
}
Dispatch the instruction at the current PC after charging it to the active event handler’s budget.
Safety
vm.code_ptr must point to valid bytecode at vm.pc; callers must only
dispatch a VM initialized from a valid [QfrProgram].
Constants
pub const NUM_REGS
#![allow(unused)]
fn main() {
pub const NUM_REGS: usize = ...;
}
pub const INT_REG_COUNT
#![allow(unused)]
fn main() {
pub const INT_REG_COUNT: u8 = ...;
}
pub const PERSIST_SLOTS
#![allow(unused)]
fn main() {
pub const PERSIST_SLOTS: usize = ...;
}
pub const MAX_CALL_DEPTH
#![allow(unused)]
fn main() {
pub const MAX_CALL_DEPTH: usize = ...;
}
pub const MAX_INDICATORS
#![allow(unused)]
fn main() {
pub const MAX_INDICATORS: usize = ...;
}
pub const MAX_BALANCES
#![allow(unused)]
fn main() {
pub const MAX_BALANCES: usize = ...;
}
pub const MAX_WINDOWS
#![allow(unused)]
fn main() {
pub const MAX_WINDOWS: usize = ...;
}
pub const WINDOW_ARENA_SIZE
#![allow(unused)]
fn main() {
pub const WINDOW_ARENA_SIZE: usize = ...;
}
pub const MAX_DEPTH_LEVELS
#![allow(unused)]
fn main() {
pub const MAX_DEPTH_LEVELS: usize = ...;
}
pub const MAX_EMA_STATES
#![allow(unused)]
fn main() {
pub const MAX_EMA_STATES: usize = ...;
}
pub const DEFAULT_INSTRUCTION_BUDGET
#![allow(unused)]
fn main() {
pub const DEFAULT_INSTRUCTION_BUDGET: u32 = ...;
}
Maximum bytecode instructions one event handler may execute by default. This bounds strategy latency even when a source loop fails to make progress.
pub const REG_SEND_SIDE
#![allow(unused)]
fn main() {
pub const REG_SEND_SIDE: u8 = ...;
}
pub const REG_SEND_QTY
#![allow(unused)]
fn main() {
pub const REG_SEND_QTY: u8 = ...;
}
pub const REG_SEND_PRICE
#![allow(unused)]
fn main() {
pub const REG_SEND_PRICE: u8 = ...;
}
pub const REG_SEND_TYPE
#![allow(unused)]
fn main() {
pub const REG_SEND_TYPE: u8 = ...;
}
pub const REG_SEND_REDUCE
#![allow(unused)]
fn main() {
pub const REG_SEND_REDUCE: u8 = ...;
}
Module: lib
Source:
lib.rs
Core types and data structures shared across all Quince crates.
Provides RingVec, RingBuffer,
and domain types (Trade, Depth, Order, OrderFill, Side, etc.)
from [types].
Module: ring
Source:
ring.rs
Lock-free ring buffer data structures for zero-allocation fixed-capacity storage.
Provides [RingBuffer] (const-generic inline buffer) and [RingVec] (heap-allocated)
with O(1) push/pop and optional eviction of oldest elements at capacity.
Structs
pub struct RingBuffer<T, const N : usize>
#![allow(unused)]
fn main() {
pub struct RingBuffer<T, const N : usize> {
buf: [MaybeUninit < T > ; N],
head: usize,
len: usize,
};
}
pub struct RingIter<'a, T, const N : usize>
#![allow(unused)]
fn main() {
pub struct RingIter<'a, T, const N : usize> {
buf: & 'a RingBuffer < T , N >,
pos: usize,
};
}
pub struct RingVec
#![allow(unused)]
fn main() {
pub struct RingVec {
data: Vec < f64 >,
head: usize,
len: usize,
cap: usize,
};
}
pub struct RingVecIter<'a>
#![allow(unused)]
fn main() {
pub struct RingVecIter<'a> {
buf: & 'a RingVec,
pos: usize,
};
}
Module: types
Source:
types.rs
Core domain types shared across all Quince crates.
Defines [Trade], [Side], [Depth], [Order], [Position], [Balance],
and related types used throughout the trading pipeline.
Structs
pub struct Trade
#![allow(unused)]
fn main() {
pub struct Trade {
pub price: f64,
pub qty: f64,
pub time: DateTime < Utc >,
pub side: Side,
pub trade_id: u64,
};
}
pub struct DepthLevel
#![allow(unused)]
fn main() {
pub struct DepthLevel {
pub price: f64,
pub qty: f64,
};
}
pub struct Depth
#![allow(unused)]
fn main() {
pub struct Depth {
pub bids: Vec < DepthLevel >,
pub asks: Vec < DepthLevel >,
};
}
pub struct Order
#![allow(unused)]
fn main() {
pub struct Order {
pub symbol: Arc < str >,
pub side: Side,
pub qty: f64,
pub price: Option < f64 >,
pub order_type: OrderType,
pub reduce_only: bool,
pub stop_loss: Option < f64 >,
pub take_profit: Option < f64 >,
};
}
pub struct OrderFill
#![allow(unused)]
fn main() {
pub struct OrderFill {
pub order_id: String,
pub side: Side,
pub price: f64,
pub qty: f64,
pub fee: f64,
pub fee_asset: String,
pub time: DateTime < Utc >,
};
}
pub struct AccountInfo
#![allow(unused)]
fn main() {
pub struct AccountInfo {
pub balances: Vec < Balance >,
pub positions: Vec < Position >,
};
}
pub struct Balance
#![allow(unused)]
fn main() {
pub struct Balance {
pub asset: String,
pub wallet: f64,
pub cross_wallet: f64,
};
}
pub struct Position
#![allow(unused)]
fn main() {
pub struct Position {
pub symbol: String,
pub side: PositionSide,
pub size: f64,
pub entry_price: f64,
pub unrealized_pnl: f64,
};
}
Enums
pub enum Side
#![allow(unused)]
fn main() {
pub enum Side {
Buy,
Sell,
}
}
pub enum OrderType
#![allow(unused)]
fn main() {
pub enum OrderType {
Market,
Limit,
}
}
pub enum PositionSide
#![allow(unused)]
fn main() {
pub enum PositionSide {
Long,
Short,
None,
}
}
Module: control
Source:
control.rs
Bounded, auditable control-plane commands for strategy lifecycle changes.
HTTP and other operator transports only receive a [StrategyControlSender].
The engine loop owns the matching [StrategyControlReceiver] and applies
commands through [StrategyLifecycle]. This deliberately prevents
a transport handler from mutating the VM, journal, or exchange directly.
Structs
pub struct StrategyControlRequest
#![allow(unused)]
fn main() {
pub struct StrategyControlRequest {
pub id: u64,
pub requested_by: String,
pub command: StrategyControlCommand,
};
}
A single command with a caller-supplied operator identity.
pub struct StrategyControlAuditRecord
#![allow(unused)]
fn main() {
pub struct StrategyControlAuditRecord {
pub audit_sequence: u64,
pub timestamp: DateTime < Utc >,
pub request: StrategyControlRequest,
pub status: StrategyControlAuditStatus,
pub detail: Option < String >,
};
}
Immutable audit event emitted when a command is queued or resolved.
pub struct StrategyControlSender
#![allow(unused)]
fn main() {
pub struct StrategyControlSender {
sender: Sender < StrategyControlRequest >,
next_request_id: Arc < AtomicU64 >,
audit: Arc < Mutex < AuditLog > >,
};
}
Send-only side exposed to control-plane transports.
pub struct StrategyControlReceiver
#![allow(unused)]
fn main() {
pub struct StrategyControlReceiver {
receiver: Receiver < StrategyControlRequest >,
audit: Arc < Mutex < AuditLog > >,
};
}
Engine-owned receive side. Only this side may take a command from the queue and append its terminal audit result.
Enums
pub enum StrategyControlCommand
#![allow(unused)]
fn main() {
pub enum StrategyControlCommand {
DeployShadow(version: u64,
artifact_digest: [u8 ; 32],),
PromoteShadow,
Rollback,
DemoteToShadow,
PauseExecution(reason: String,),
ResumeExecution,
}
}
A lifecycle command that an external control plane may request.
There is intentionally no DeployLive or generic SetMode(Live) command:
an operator must deploy a candidate into shadow and explicitly promote the
active shadow revision through the lifecycle state machine.
pub enum StrategyControlCommandKind
#![allow(unused)]
fn main() {
pub enum StrategyControlCommandKind {
DeployShadow,
PromoteShadow,
Rollback,
DemoteToShadow,
PauseExecution,
ResumeExecution,
}
}
Stable command label suitable for audit/filtering APIs.
pub enum StrategyControlAuditStatus
#![allow(unused)]
fn main() {
pub enum StrategyControlAuditStatus {
Queued,
Applied,
Rejected,
}
}
Lifecycle command result as retained in the audit stream.
pub enum StrategyControlError
#![allow(unused)]
fn main() {
pub enum StrategyControlError {
ZeroQueueCapacity,
ZeroAuditCapacity,
InvalidActor,
QueueFull,
Disconnected,
}
}
Functions
pub fn strategy_control_channel
#![allow(unused)]
fn main() {
pub fn strategy_control_channel(...) { ... }
}
Create a bounded control command queue and bounded audit stream.
pub fn default_strategy_control_channel
#![allow(unused)]
fn main() {
pub fn default_strategy_control_channel(...) { ... }
}
Create a control queue with production defaults.
Constants
pub const DEFAULT_CONTROL_QUEUE_CAPACITY
#![allow(unused)]
fn main() {
pub const DEFAULT_CONTROL_QUEUE_CAPACITY: usize = ...;
}
Default maximum number of commands waiting for the engine loop.
pub const DEFAULT_CONTROL_AUDIT_CAPACITY
#![allow(unused)]
fn main() {
pub const DEFAULT_CONTROL_AUDIT_CAPACITY: usize = ...;
}
Default number of in-memory audit records retained for operator inspection.
Module: indicators
Source:
indicators.rs
Indicator parsing and management for the trading engine.
Parses @using directives from QFL strategy headers into [IndicatorEntry] lists
and provides [IndicatorBank] for runtime indicator lifecycle.
Structs
pub struct IndicatorEntry
#![allow(unused)]
fn main() {
pub struct IndicatorEntry {
pub name: String,
pub params: Vec < f64 >,
pub buffer: usize,
};
}
pub struct IndicatorBank
#![allow(unused)]
fn main() {
pub struct IndicatorBank {
indicators: Vec < ActiveIndicator >,
results: Vec < (u16 , f64) >,
slot_sma: u16,
slot_ema: u16,
slot_wma: u16,
slot_vwma: u16,
slot_lsma: u16,
slot_rsi: u16,
slot_macd: u16,
slot_macd_signal: u16,
slot_macd_histogram: u16,
slot_cci: u16,
slot_roc: u16,
slot_stoch: u16,
slot_bb_middle: u16,
slot_bb_upper: u16,
slot_bb_lower: u16,
slot_bb_bandwidth: u16,
slot_kc_middle: u16,
slot_kc_upper: u16,
slot_kc_lower: u16,
slot_atr: u16,
slot_mfi: u16,
slot_adx: u16,
slot_zscore: u16,
slot_cvd: u16,
slot_pmdi: u16,
slot_nmdi: u16,
slot_price: u16,
slot_volume_delta: u16,
slot_avg_trade_size: u16,
slot_trade_count: u16,
slot_bid_depth: u16,
slot_ask_depth: u16,
slot_depth_imbalance: u16,
cum_buy: f64,
cum_sell: f64,
trades: u64,
};
}
Functions
pub fn parse_using
#![allow(unused)]
fn main() {
pub fn parse_using(...) { ... }
}
pub fn parse_using_strict
#![allow(unused)]
fn main() {
pub fn parse_using_strict(...) { ... }
}
Strict production parser for @using directives.
Unlike [parse_using], it rejects malformed numeric parameters instead of
silently dropping them. The engine uses this at startup.
Module: journal
Source:
journal.rs
Durable append-only order journal.
The journal is deliberately independent from the live order manager. It
records the client-order-id lifecycle before the engine attempts a remote
action, allowing a future startup recovery pass to find orders whose
submission outcome is unknown. Each record is one versioned JSON line and
is synced before [OrderJournal::append] returns.
Structs
pub struct JournalRecord
#![allow(unused)]
fn main() {
pub struct JournalRecord {
pub version: u32,
pub sequence: u64,
pub recorded_at_ms: u64,
pub event: JournalEvent,
};
}
pub struct OrderJournal
#![allow(unused)]
fn main() {
pub struct OrderJournal {
path: PathBuf,
file: File,
next_sequence: u64,
};
}
A single-process writer for a durable order lifecycle journal.
Enums
pub enum JournalEvent
#![allow(unused)]
fn main() {
pub enum JournalEvent {
Registered(client_order_id: String,
symbol: String,
side: String,
qty: f64,
reduce_only: bool,),
Accepted(client_order_id: String,
exchange_order_id: String,),
SubmissionUnknown(client_order_id: String,
error: String,),
CancelRequested(client_order_id: String,
exchange_order_id: String,),
Terminal(client_order_id: String,
status: String,),
}
}
pub enum JournalError
#![allow(unused)]
fn main() {
pub enum JournalError {
Io(std :: io :: Error,),
Json(line: usize,
source: serde_json :: Error,),
Serialize(serde_json :: Error,),
UnsupportedVersion(line: usize,
version: u32,),
InvalidSequence(line: usize,
expected: u64,
actual: u64,),
Clock,
}
}
Type Aliases
pub type Result
#![allow(unused)]
fn main() {
pub type Result = std :: result :: Result < T , JournalError >;
}
Constants
pub const JOURNAL_VERSION
#![allow(unused)]
fn main() {
pub const JOURNAL_VERSION: u32 = ...;
}
Current on-disk JSONL schema version.
Module: lib
Source:
lib.rs
Quince trading engine — event loop, order manager, indicator bank.
The Engine drives the strategy lifecycle: feeds market
data into the QFL runtime, dispatches orders, manages hot-reload, and
coordinates with the exchange connector.
Module: loop
Source:
loop.rs
Main trading engine event loop.
Drives the [Engine] lifecycle: subscribes to exchange streams, evaluates
strategy conditions via QFL runtime, manages order placement/tracking,
applies risk controls, and coordinates all subsystems.
Structs
pub struct Engine<E : Exchange>
#![allow(unused)]
fn main() {
pub struct Engine<E : Exchange> {
exchange: E,
symbols: Vec < String >,
orders_rx: crossbeam_channel :: Receiver < Order >,
control_rx: StrategyControlReceiver,
control_sender: StrategyControlSender,
qfl: QflRuntime,
risk: RiskControls,
logger: TradeLog,
order_manager: OrderManager,
order_journal: OrderJournal,
execution_sync_ready: bool,
execution_halted: bool,
strategy_lifecycle: StrategyLifecycle,
telemetry: Arc < RuntimeTelemetry >,
indicators: IndicatorBank,
last_price: f64,
daily_pnl: f64,
peak_equity: f64,
balance_names: Vec < String >,
balance_values: Vec < f64 >,
position: Option < Position >,
next_eval: Instant,
next_account: Instant,
entry_price_slot: u16,
unrealized_pnl_slot: u16,
profiling_frame: u64,
};
}
Enums
pub enum EngineError
#![allow(unused)]
fn main() {
pub enum EngineError {
Exchange(ExchangeError,),
Strategy(String,),
RiskRejected(String,),
OrderTimeout(String,),
Journal(JournalError,),
}
}
Module: orders
Source:
orders.rs
Order lifecycle management.
Tracks pending orders, active stop-loss/take-profit levels, and order fill
reconciliation via [OrderManager], [PendingOrder], and [ActiveStop].
Structs
pub struct ActiveStop
#![allow(unused)]
fn main() {
pub struct ActiveStop {
pub client_id: String,
pub side: Side,
pub qty: f64,
pub entry_price: f64,
pub stop_loss: Option < f64 >,
pub take_profit: Option < f64 >,
};
}
pub struct PendingOrder
#![allow(unused)]
fn main() {
pub struct PendingOrder {
pub client_id: String,
pub order: Order,
pub status: PendingStatus,
pub placed_at: Instant,
pub last_update: Instant,
pub filled_qty: f64,
pub avg_price: f64,
};
}
pub struct OrderManager
#![allow(unused)]
fn main() {
pub struct OrderManager {
pub orders: HashMap < String , PendingOrder >,
pub exchange_to_client: HashMap < String , String >,
};
}
Enums
pub enum PendingStatus
#![allow(unused)]
fn main() {
pub enum PendingStatus {
Waiting,
Placed(order_id: String,),
PartiallyFilled(order_id: String,
filled_qty: f64,),
CancelRequested(order_id: String,),
SubmissionUnknown(error: String,),
Filled,
Cancelled,
Failed(String,),
}
}
Module: strategy_lifecycle
Source:
strategy_lifecycle.rs
Versioned, rollback-safe strategy deployment state.
This module deliberately contains no VM or exchange code. A caller must
compile and validate a candidate before calling [StrategyLifecycle::deploy];
deployment then changes the active slot atomically from the caller’s point
of view. The previous slot retains its own opaque runtime state, so a
rollback can never run state created by a different strategy version.
Structs
pub struct StrategyRevision
#![allow(unused)]
fn main() {
pub struct StrategyRevision {
pub version: u64,
pub artifact_digest: [u8 ; 32],
pub mode: DeploymentMode,
};
}
Immutable identity of compiled strategy code.
pub struct StrategySlot
#![allow(unused)]
fn main() {
pub struct StrategySlot {
pub revision: StrategyRevision,
pub runtime_state: Vec < u8 >,
};
}
A revision plus only the state generated while that exact revision was active.
pub struct StrategyLifecycle
#![allow(unused)]
fn main() {
pub struct StrategyLifecycle {
active: Option < StrategySlot >,
previous: Option < StrategySlot >,
};
}
Two-slot deployment register.
At most one live revision and one known-good rollback target are retained.
deploy validates all invariants before mutating either slot.
Enums
pub enum DeploymentMode
#![allow(unused)]
fn main() {
pub enum DeploymentMode {
Shadow,
Live,
}
}
Whether a deployed strategy may emit orders.
pub enum StrategyLifecycleError
#![allow(unused)]
fn main() {
pub enum StrategyLifecycleError {
ZeroVersion,
NonMonotonicVersion(candidate: u64,
active: u64,),
NoRollbackTarget,
NoActiveRevision,
VersionOverflow,
ActiveRevisionIsNotShadow,
}
}
Module: telemetry
Source:
telemetry.rs
Lock-free runtime counters exposed to an out-of-band operator surface.
Structs
pub struct RuntimeTelemetrySnapshot
#![allow(unused)]
fn main() {
pub struct RuntimeTelemetrySnapshot {
pub strategy_version: u64,
pub execution_mode: & 'static str,
pub artifact_digest: String,
pub market_events: u64,
pub order_intents: u64,
pub suppressed_orders: u64,
pub stream_integrity_events: u64,
pub stream_overflows: u64,
pub stream_gaps: u64,
pub stream_stale_or_other: u64,
pub execution_sync_ready: bool,
pub market_event_latency_samples: u64,
pub market_event_latency_p50_us: u64,
pub market_event_latency_p95_us: u64,
pub market_event_latency_p99_us: u64,
};
}
pub struct RuntimeTelemetry
#![allow(unused)]
fn main() {
pub struct RuntimeTelemetry {
strategy_version: AtomicU64,
mode: AtomicU8,
digest_prefix: AtomicU64,
market_events: AtomicU64,
order_intents: AtomicU64,
suppressed_orders: AtomicU64,
stream_integrity_events: AtomicU64,
stream_overflows: AtomicU64,
stream_gaps: AtomicU64,
stream_stale_or_other: AtomicU64,
execution_sync_ready: AtomicU8,
market_event_latency_ns: [AtomicU64 ; LATENCY_BUCKETS],
};
}
Atomic counters only: recording telemetry is safe in the market-data hot path and never waits for an operator client.
Module: bin/strategy_bench
Source:
bin/strategy_bench.rs
Reproducible QFL strategy latency matrix.
Measures the single-threaded hot path: indicator update, indicator-slot
writes and on_trade VM dispatch. Networking, disk I/O, logging sinks and
exchange acknowledgements are deliberately outside the measurement.
Module: lib
Source:
lib.rs
Exchange abstraction layer.
Defines the Exchange trait and provides exchange-specific
implementations (Binance and Hyperliquid public WebSocket adapters).
Module: trait
Source:
trait.rs
Exchange trait definitions and shared types.
Defines [Exchange], [ExchangeError], [StreamMsg], [OrderStatus],
and the [Stream] subscription handle used by all exchange backends.
Structs
pub struct Stream
#![allow(unused)]
fn main() {
pub struct Stream {
pub rx: crossbeam_channel :: Receiver < StreamMsg >,
};
}
pub struct OrderRequest
#![allow(unused)]
fn main() {
pub struct OrderRequest {
pub client_order_id: String,
pub order: Order,
};
}
An order paired with the caller-generated idempotency key. The key is created by the engine before submission and must remain stable across transport failures. Adapters that support native client IDs must send it verbatim and expose lookup by it for reconciliation.
pub struct OrderStatus
#![allow(unused)]
fn main() {
pub struct OrderStatus {
pub order_id: String,
pub symbol: String,
pub side: Side,
pub qty: f64,
pub filled_qty: f64,
pub price: f64,
pub avg_price: f64,
pub status: String,
};
}
Enums
pub enum ExchangeError
#![allow(unused)]
fn main() {
pub enum ExchangeError {
Ws(String,),
Rest(String,),
Auth(String,),
Order(String,),
Timeout,
Disconnected,
}
}
pub enum StreamMsg
#![allow(unused)]
fn main() {
pub enum StreamMsg {
Trade(Trade,),
Depth(Depth,),
MarkPrice(price: f64,
time: chrono :: DateTime < chrono :: Utc >,),
OpenInterest(qty: f64,
time: chrono :: DateTime < chrono :: Utc >,),
ForceOrder(Trade,),
AccountUpdate(AccountInfo,),
OrderUpdate(OrderFill,),
ReconcileRequired(source: & 'static str,
reason: String,),
}
}
Traits
pub trait Exchange
#![allow(unused)]
fn main() {
pub trait Exchange: Send: Sync {
async fn subscribe (& self , symbols : & [String]) -> Result < Stream >;
async fn place_order (& self , request : OrderRequest) -> Result < String >;
async fn cancel_order (& self , symbol : & str , order_id : & str) -> Result < () >;
async fn order_status (& self , symbol : & str , order_id : & str) -> Result < OrderStatus >;
async fn order_status_by_client_id (& self , _symbol : & str , _client_order_id : & str ,) -> Result < OrderStatus > { ... }
async fn account_info (& self) -> Result < AccountInfo >;
async fn current_price (& self , symbol : & str) -> Result < f64 >;
}
}
Type Aliases
pub type Result
#![allow(unused)]
fn main() {
pub type Result = std :: result :: Result < T , ExchangeError >;
}
Module: binance/filters
Source:
binance/filters.rs
Local validation for Binance exchangeInfo symbol filters.
This module deliberately consumes the exchange response instead of carrying
a hand-maintained precision table. It currently understands the common
PRICE_FILTER, LOT_SIZE, and MIN_NOTIONAL/NOTIONAL fields. Binance
represents numeric fields as decimal strings; JSON numbers are accepted as
a convenience for fixtures, but production callers should preserve the
response unchanged.
A zero min/max bound is treated as disabled, matching Binance’s documented filter convention. Price and quantity normalization floors toward zero to the permitted increment: normalization never increases an order’s price or exposure. Callers must submit the returned values, not the original input.
Structs
pub struct NormalizedLimitOrder
#![allow(unused)]
fn main() {
pub struct NormalizedLimitOrder {
pub symbol: String,
pub price: f64,
pub qty: f64,
};
}
pub struct SymbolFilters
#![allow(unused)]
fn main() {
pub struct SymbolFilters {
symbol: String,
tick_size: f64,
tick_precision: usize,
min_price: Option < f64 >,
max_price: Option < f64 >,
step_size: f64,
qty_precision: usize,
min_qty: Option < f64 >,
max_qty: Option < f64 >,
min_notional: Option < f64 >,
};
}
pub struct BinanceFilters
#![allow(unused)]
fn main() {
pub struct BinanceFilters {
symbols: HashMap < String , SymbolFilters >,
};
}
Indexes symbol filters parsed from one Binance exchangeInfo response.
Module: binance/mod
Source:
binance/mod.rs
Authenticated Binance exchange implementation.
Provides REST order placement, account queries, and WebSocket-backed
market data streaming via the [Binance] struct.
Structs
pub struct Binance
#![allow(unused)]
fn main() {
pub struct Binance {
api_key: String,
secret_key: String,
testnet: bool,
client: OnceLock < ws :: WsClient >,
filters: OnceLock < filters :: BinanceFilters >,
};
}
Module: binance/public
Source:
binance/public.rs
Read-only Binance exchange for public market data.
[BinancePublic] implements the [Exchange] trait without authentication,
supporting trade/depth subscriptions via combined WebSocket streams.
Structs
pub struct BinancePublic
#![allow(unused)]
fn main() {
pub struct BinancePublic;;
}
Module: binance/types
Source:
binance/types.rs
Binance WebSocket message parsing.
Fast JSON deserialization of Binance stream events (aggTrade, depth, kline)
into [StreamMsg] variants using simd-json.
Functions
pub fn parse_ws_msg
#![allow(unused)]
fn main() {
pub fn parse_ws_msg(...) { ... }
}
Module: binance/user_data
Source:
binance/user_data.rs
Strict parser for Binance USDⓈ-M Futures user-data events.
It owns the listen-key lifecycle as well as strict payload decoding. Socket producers use a bounded crossbeam ingress and never wait for the engine.
Enums
pub enum UserDataParseError
#![allow(unused)]
fn main() {
pub enum UserDataParseError {
Json(String,),
Invalid(& 'static str,),
}
}
A malformed event must not be allowed to silently alter risk/accounting
state. Unknown event names are deliberately returned as Ok(None) so a
future Binance addition does not take down the stream by itself.
Functions
pub fn start_user_data_stream
#![allow(unused)]
fn main() {
pub fn start_user_data_stream(...) { ... }
}
Starts a self-healing private-stream supervisor. Every disconnect, parser
error, queue overflow, or listen-key failure emits ReconcileRequired
before reconnecting. Thus a transient stream gap never becomes invisible.
pub fn parse_user_data_msg
#![allow(unused)]
fn main() {
pub fn parse_user_data_msg(...) { ... }
}
Parses ORDER_TRADE_UPDATE and ACCOUNT_UPDATE payloads from the Binance
USDⓈ-M Futures user-data stream.
ORDER_TRADE_UPDATE produces OrderUpdate only for an actual TRADE
execution with positive last-fill quantity. Other valid order lifecycle
events have no corresponding lossless StreamMsg variant and return
Ok(None); they must still be consumed by a future order-status/reconcile
layer rather than being mistaken for fills.
Type Aliases
pub type Result
#![allow(unused)]
fn main() {
pub type Result = std :: result :: Result < T , UserDataParseError >;
}
Module: binance/ws
Source:
binance/ws.rs
Binance WebSocket client implementation. Maintains a persistent WSS connection with request/response routing. Reconnection is deliberately owned by the caller: pending order outcomes must be reconciled before a new connection can safely retry work. request/response routing, and HMAC-SHA256 signed authenticated requests.
Structs
pub struct WsClient
#![allow(unused)]
fn main() {
pub struct WsClient {
pub req_tx: crossbeam_channel :: Sender < WsRequest >,
pub stream_tx: crossbeam_channel :: Sender < StreamMsg >,
};
}
pub struct WsRequest
#![allow(unused)]
fn main() {
pub struct WsRequest {
pub method: String,
pub params: Map < String , Value >,
pub response_tx: oneshot :: Sender < Result < Value > >,
};
}
pub struct BinanceWs
#![allow(unused)]
fn main() {
pub struct BinanceWs {
url: String,
api_key: String,
secret_key: String,
};
}
Module: hyperliquid/execution
Source:
hyperliquid/execution.rs
Safe boundary for authenticated Hyperliquid execution.
This module deliberately does not serialize or submit L1 actions yet. Hyperliquid’s action signatures depend on canonical msgpack encoding and a protocol-specific EIP-712 payload. A locally-valid ECDSA signature is not sufficient proof that the exchange will recover the intended signer. Until that encoding is covered by official test vectors, every mutating operation fails closed.
The types here are still useful now: they keep private-key ownership out of the exchange adapter, bind a signer to an account, validate order intents, and provide one place to add a reviewed signing implementation later.
Structs
pub struct HyperliquidSignature
#![allow(unused)]
fn main() {
pub struct HyperliquidSignature {
pub r: String,
pub s: String,
pub v: u8,
};
}
A signature produced by an external EIP-712/L1-action signer. The adapter never receives a private key. The signer may be backed by an OS keychain, hardware wallet, or a separate signing process.
pub struct ValidatedOrder
#![allow(unused)]
fn main() {
pub struct ValidatedOrder {
pub order: Order,
pub network: HyperliquidNetwork,
pub account_address: String,
};
}
A checked order intent. It is intentionally not a wire request.
pub struct HyperliquidPerpMeta
#![allow(unused)]
fn main() {
pub struct HyperliquidPerpMeta {
assets: HashMap < String , PerpAsset >,
};
}
Authoritative perp asset metadata used to bind a user coin to its protocol asset index and permitted size precision.
pub struct PerpAsset
#![allow(unused)]
fn main() {
pub struct PerpAsset {
pub index: u32,
pub size_decimals: u8,
};
}
pub struct PreparedHyperliquidOrder
#![allow(unused)]
fn main() {
pub struct PreparedHyperliquidOrder {
pub client_order_id: String,
pub nonce: u64,
pub payload: serde_json :: Value,
};
}
Fully prepared, signed exchange payload. It is intentionally separate from transport so callers can journal the immutable idempotency context before any network side effect occurs.
pub struct ExecutionPreflight
#![allow(unused)]
fn main() {
pub struct ExecutionPreflight {
pub market_observed_at: DateTime < Utc >,
pub max_market_age: Duration,
};
}
Inputs captured immediately before signing. An absent or stale market view is a hard execution failure, never a reason to reuse a last known quote.
pub struct OpenOrderReconciliation
#![allow(unused)]
fn main() {
pub struct OpenOrderReconciliation {
pub missing_expected_ids: Vec < String >,
};
}
Result of comparing journal-tracked active exchange IDs to the
authoritative openOrders snapshot. Missing IDs are ambiguous until a
terminal fill/cancel record is independently observed.
pub struct HyperliquidExecution
#![allow(unused)]
fn main() {
pub struct HyperliquidExecution {
network: HyperliquidNetwork,
account_address: String,
signer: Arc < dyn HyperliquidSigner >,
public: HyperliquidPublic,
nonce: AtomicU64,
};
}
Authenticated adapter shell.
Public-data methods work through [HyperliquidPublic]. Mutating methods
reject until canonical action encoding, signing vectors, submission, and
reconciliation are all implemented together.
Enums
pub enum HyperliquidNetwork
#![allow(unused)]
fn main() {
pub enum HyperliquidNetwork {
Mainnet,
Testnet,
}
}
Hyperliquid deployment selected for an authenticated session.
Traits
pub trait HyperliquidSigner
#![allow(unused)]
fn main() {
pub trait HyperliquidSigner: Send: Sync {
fn address (& self) -> & str;
fn sign_l1_action (& self , action_hash : [u8 ; 32] , network : HyperliquidNetwork ,) -> Result < HyperliquidSignature >;
}
}
Boundary for a future, protocol-reviewed Hyperliquid L1 action signer.
action_hash must be produced by a canonical encoder with official test
vectors. This crate intentionally does not manufacture it yet.
Functions
pub fn reconcile_open_orders
#![allow(unused)]
fn main() {
pub fn reconcile_open_orders(...) { ... }
}
Module: hyperliquid/mod
Source:
hyperliquid/mod.rs
Hyperliquid exchange adapters.
Module: hyperliquid/preflight
Source:
hyperliquid/preflight.rs
Fail-closed market-context checks for authenticated execution.
This module is deliberately transport-free: a caller must bind an order to a specific, fresh, finite market observation before it is signed. A wall clock timestamp alone is not evidence that a quote is usable for an order.
Structs
pub struct MarketSnapshot
#![allow(unused)]
fn main() {
pub struct MarketSnapshot {
pub symbol: String,
pub observed_at: DateTime < Utc >,
pub reference_price: f64,
};
}
Immutable quote evidence captured at the decision boundary.
pub struct MarketContextPolicy
#![allow(unused)]
fn main() {
pub struct MarketContextPolicy {
pub max_age: Duration,
pub max_limit_deviation_bps: u32,
};
}
Explicit bounds for accepting a market observation for execution.
Module: hyperliquid/public
Source:
hyperliquid/public.rs
Read-only Hyperliquid market-data adapter.
Subscribes to the official trades and l2Book WebSocket feeds. Trading
is deliberately rejected here: Hyperliquid requires EIP-712 action signing,
which must be implemented as a dedicated authenticated adapter.
Structs
pub struct HyperliquidPublic
#![allow(unused)]
fn main() {
pub struct HyperliquidPublic {
testnet: bool,
};
}
Module: hyperliquid/signing
Source:
hyperliquid/signing.rs
Minimal, vector-tested primitives for Hyperliquid L1-action signatures.
This covers the EIP-712 envelope and the narrow limit-order action shape needed by the first execution path. Each wire representation is fixed by a protocol test vector before it becomes usable by an adapter.
Functions
pub fn limit_order_connection_id
#![allow(unused)]
fn main() {
pub fn limit_order_connection_id(...) { ... }
}
Hashes the exact MessagePack limit-order action accepted by Hyperliquid. This intentionally supports only an IOC, non-reduce-only order with no client ID or builder. Broader action variants must add their own vectors, rather than sharing a permissive serializer with different semantics.
pub fn cancel_connection_id
#![allow(unused)]
fn main() {
pub fn cancel_connection_id(...) { ... }
}
Hashes the exact single-order cancel action accepted by Hyperliquid.
pub fn l1_action_signing_digest
#![allow(unused)]
fn main() {
pub fn l1_action_signing_digest(...) { ... }
}
Returns the EIP-712 digest the wallet must sign for a canonical L1 action
connection ID. The protocol uses source a on mainnet and b on testnet.
pub fn sign_l1_action
#![allow(unused)]
fn main() {
pub fn sign_l1_action(...) { ... }
}
Signs a canonical L1 action connection ID using Ethereum’s r || s || v
shape. v is normalized to 27 or 28 for the exchange API.
Module: hyperliquid/user_data
Source:
hyperliquid/user_data.rs
Hyperliquid private user-stream decoding and supervision.
The WebSocket subscriptions are read-only, but their payloads are part of
the execution integrity boundary. A malformed event, disconnect, or full
ingress queue therefore emits ReconcileRequired before reconnecting.
Enums
pub enum UserDataParseError
#![allow(unused)]
fn main() {
pub enum UserDataParseError {
Json(String,),
Invalid(& 'static str,),
}
}
Functions
pub fn start_user_data_stream
#![allow(unused)]
fn main() {
pub fn start_user_data_stream(...) { ... }
}
Starts a self-healing private user-data supervisor. A returned value means the initial subscriptions are live; later gaps cause an immediate engine reconciliation signal and bounded-delay reconnect.
pub fn parse_user_data_msgs
#![allow(unused)]
fn main() {
pub fn parse_user_data_msgs(...) { ... }
}
Parses every lossless engine event in one private WebSocket payload.
userFills may contain multiple fills; dropping all but the first would
silently understate fee and position accounting.
Type Aliases
pub type ParseResult
#![allow(unused)]
fn main() {
pub type ParseResult = std :: result :: Result < T , UserDataParseError >;
}
Module: custom
Source:
custom.rs
Native, compile-time custom-indicator extension API.
Put one Rust source file in src/custom/. The build script discovers it at
compile time and adds its [CustomIndicatorRegistration] to the registry.
Dynamic loading is deliberately unsupported: every plugin is reviewed,
compiled, and linked into the Quince binary.
Structs
pub struct IndicatorParameter
#![allow(unused)]
fn main() {
pub struct IndicatorParameter {
pub name: & 'static str,
pub min: f64,
pub max: f64,
};
}
A named numeric parameter accepted by a custom indicator.
pub struct IndicatorDescriptor
#![allow(unused)]
fn main() {
pub struct IndicatorDescriptor {
pub name: & 'static str,
pub input: IndicatorInput,
pub output: IndicatorOutput,
pub parameters: & 'static [IndicatorParameter],
};
}
Immutable metadata declared by every custom indicator.
pub struct CustomIndicatorRegistration
#![allow(unused)]
fn main() {
pub struct CustomIndicatorRegistration {
pub descriptor: & 'static IndicatorDescriptor,
pub create: CustomIndicatorFactory,
};
}
Compile-time registration emitted by a custom-indicator source file.
Enums
pub enum IndicatorInput
#![allow(unused)]
fn main() {
pub enum IndicatorInput {
Trade,
}
}
Market-event format accepted by an indicator.
pub enum IndicatorOutput
#![allow(unused)]
fn main() {
pub enum IndicatorOutput {
ScalarF64,
}
}
Output format exposed to QFL through quince.get("<name>").
pub enum CustomIndicatorError
#![allow(unused)]
fn main() {
pub enum CustomIndicatorError {
UnknownIndicator(String,),
InvalidParameterCount(indicator: & 'static str,
expected: usize,
actual: usize,),
InvalidParameter(indicator: & 'static str,
parameter: & 'static str,
value: f64,
min: f64,
max: f64,),
Construction(indicator: & 'static str,
reason: & 'static str,),
}
}
Construction or validation failure for a custom indicator.
Traits
pub trait CustomIndicator
#![allow(unused)]
fn main() {
pub trait CustomIndicator: Send {
fn on_trade (& mut self , trade : & Trade) -> Option < f64 >;
}
}
Native indicator implementation. on_trade must not allocate or block.
Functions
pub fn custom_indicator
#![allow(unused)]
fn main() {
pub fn custom_indicator(...) { ... }
}
Finds a compile-time registered custom indicator by its QFL name.
pub fn custom_indicators
#![allow(unused)]
fn main() {
pub fn custom_indicators(...) { ... }
}
All custom indicators linked into this Quince build, in deterministic filename order. This is intended for startup validation and tooling only.
Type Aliases
pub type CustomIndicatorFactory
#![allow(unused)]
fn main() {
pub type CustomIndicatorFactory = fn (& [f64]) -> Result < Box < dyn CustomIndicator > , CustomIndicatorError >;
}
Factory signature used by the generated custom-indicator registry.
Module: flow
Source:
flow.rs
Money Flow Index (MFI) indicator.
A volume-weighted momentum oscillator that uses price and volume to identify
overbought/oversold conditions. [Mfi] tracks positive and negative money flow.
Structs
pub struct Mfi
#![allow(unused)]
fn main() {
pub struct Mfi {
period: usize,
typical_prev: Option < f64 >,
pos_flow: RingVec,
neg_flow: RingVec,
count: usize,
};
}
pub struct VolumeDelta
#![allow(unused)]
fn main() {
pub struct VolumeDelta;;
}
pub struct Cvd
#![allow(unused)]
fn main() {
pub struct Cvd {
cumulative: f64,
};
}
pub struct Obv
#![allow(unused)]
fn main() {
pub struct Obv {
obv: f64,
prev_close: Option < f64 >,
};
}
pub struct AccDist
#![allow(unused)]
fn main() {
pub struct AccDist {
ad: f64,
};
}
pub struct Pmdi
#![allow(unused)]
fn main() {
pub struct Pmdi {
value: f64,
prev_data: Option < f64 >,
};
}
pub struct Nmdi
#![allow(unused)]
fn main() {
pub struct Nmdi {
value: f64,
prev_data: Option < f64 >,
};
}
pub struct AverageTradeSize
#![allow(unused)]
fn main() {
pub struct AverageTradeSize;;
}
Module: lib
Source:
lib.rs
Technical analysis indicators for trading strategies.
Provides moving averages, oscillators, volatility measures, flow indicators,
and structure detection — all operating on the shared [Candle] type.
Structs
pub struct Candle
#![allow(unused)]
fn main() {
pub struct Candle {
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
};
}
Module: ma
Source:
ma.rs
Moving average indicators.
Provides [Sma] (Simple), [Ema] (Exponential), [Wma] (Weighted),
and [Hma] (Hull) moving averages with O(1) incremental updates.
Structs
pub struct Sma
#![allow(unused)]
fn main() {
pub struct Sma {
period: usize,
buffer: RingVec,
sum: f64,
};
}
pub struct Ema
#![allow(unused)]
fn main() {
pub struct Ema {
multiplier: f64,
current: Option < f64 >,
};
}
pub struct Wma
#![allow(unused)]
fn main() {
pub struct Wma {
period: usize,
buffer: RingVec,
denominator: f64,
};
}
pub struct Vwma
#![allow(unused)]
fn main() {
pub struct Vwma {
period: usize,
price_buffer: RingVec,
vol_buffer: RingVec,
pv_sum: f64,
v_sum: f64,
};
}
pub struct Lsma
#![allow(unused)]
fn main() {
pub struct Lsma {
period: usize,
buffer: RingVec,
sum_x: f64,
sum_x2: f64,
};
}
Module: oscillator
Source:
oscillator.rs
Oscillator indicators for momentum and mean-reversion analysis.
Includes [Rsi] (Relative Strength Index), [Stochastic], [Cci]
(Commodity Channel Index), and [WilliamsR] (%R).
Structs
pub struct Rsi
#![allow(unused)]
fn main() {
pub struct Rsi {
period: usize,
gains: RingVec,
losses: RingVec,
avg_gain: Option < f64 >,
avg_loss: Option < f64 >,
prev: Option < f64 >,
count: usize,
};
}
pub struct Macd
#![allow(unused)]
fn main() {
pub struct Macd {
fast_ema: super :: ma :: Ema,
slow_ema: super :: ma :: Ema,
signal_ema: super :: ma :: Ema,
};
}
pub struct MacdOutput
#![allow(unused)]
fn main() {
pub struct MacdOutput {
pub macd_line: f64,
pub signal_line: f64,
pub histogram: f64,
};
}
pub struct Cci
#![allow(unused)]
fn main() {
pub struct Cci {
period: usize,
typical_buffer: RingVec,
constant: f64,
};
}
pub struct Roc
#![allow(unused)]
fn main() {
pub struct Roc {
period: usize,
buffer: RingVec,
};
}
pub struct Stochastic
#![allow(unused)]
fn main() {
pub struct Stochastic {
period: usize,
high_buffer: RingVec,
low_buffer: RingVec,
};
}
Module: simd
Source:
simd.rs
No module documentation.
Functions
pub fn sum
#![allow(unused)]
fn main() {
pub fn sum(...) { ... }
}
pub fn sum_sq_diff
#![allow(unused)]
fn main() {
pub fn sum_sq_diff(...) { ... }
}
pub fn weighted_sum
#![allow(unused)]
fn main() {
pub fn weighted_sum(...) { ... }
}
pub fn sum_and_sum_xy
#![allow(unused)]
fn main() {
pub fn sum_and_sum_xy(...) { ... }
}
pub fn sum_abs_diff
#![allow(unused)]
fn main() {
pub fn sum_abs_diff(...) { ... }
}
pub fn min_max
#![allow(unused)]
fn main() {
pub fn min_max(...) { ... }
}
Module: structure
Source:
structure.rs
Market structure indicators.
Provides [Adx] (Average Directional Index) for trend strength measurement
and [Psar] (Parabolic SAR) for trend direction and reversal points.
Structs
pub struct Adx
#![allow(unused)]
fn main() {
pub struct Adx {
period: usize,
tr_buffer: RingVec,
plus_dm_buffer: RingVec,
minus_dm_buffer: RingVec,
prev_candle: Option < Candle >,
count: usize,
tr_smooth: Option < f64 >,
plus_di: Option < f64 >,
minus_di: Option < f64 >,
adx_ema: Option < f64 >,
};
}
pub struct BidAskImbalance
#![allow(unused)]
fn main() {
pub struct BidAskImbalance;;
}
pub struct DomDepth
#![allow(unused)]
fn main() {
pub struct DomDepth;;
}
pub struct ZScore
#![allow(unused)]
fn main() {
pub struct ZScore {
period: usize,
buffer: RingVec,
};
}
pub struct NetOpenInterest
#![allow(unused)]
fn main() {
pub struct NetOpenInterest;;
}
pub struct NetOiOutput
#![allow(unused)]
fn main() {
pub struct NetOiOutput {
pub taker_long: f64,
pub taker_short: f64,
pub volume_delta: f64,
pub oi_delta: f64,
};
}
Module: volatility
Source:
volatility.rs
Volatility indicators.
Provides [TrueRange], [Atr] (Average True Range), [BollingerBands],
and [KeltnerChannel] for measuring and visualizing market volatility.
Structs
pub struct TrueRange
#![allow(unused)]
fn main() {
pub struct TrueRange;;
}
pub struct Atr
#![allow(unused)]
fn main() {
pub struct Atr {
period: usize,
atr: Option < f64 >,
prev_close: Option < f64 >,
count: usize,
initial_tr: RingVec,
};
}
pub struct BollingerBands
#![allow(unused)]
fn main() {
pub struct BollingerBands {
period: usize,
multiplier: f64,
sma: super :: ma :: Sma,
buffer: RingVec,
};
}
pub struct BollingerOutput
#![allow(unused)]
fn main() {
pub struct BollingerOutput {
pub middle: f64,
pub upper: f64,
pub lower: f64,
pub bandwidth: f64,
};
}
pub struct KeltnerChannel
#![allow(unused)]
fn main() {
pub struct KeltnerChannel {
multiplier: f64,
ema: super :: ma :: Ema,
atr: Atr,
};
}
pub struct KeltnerOutput
#![allow(unused)]
fn main() {
pub struct KeltnerOutput {
pub middle: f64,
pub upper: f64,
pub lower: f64,
};
}
Module: custom/custom_atr
Source:
custom/custom_atr.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_average_trade_size
Source:
custom/custom_average_trade_size.rs
Arithmetic mean of valid trade quantities.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_bollinger_width
Source:
custom/custom_bollinger_width.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_buy_volume_ratio
Source:
custom/custom_buy_volume_ratio.rs
Cumulative buy volume share.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_chaikin_oscillator
Source:
custom/custom_chaikin_oscillator.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_cmo
Source:
custom/custom_cmo.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_cvd
Source:
custom/custom_cvd.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_dema
Source:
custom/custom_dema.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_donchian_width
Source:
custom/custom_donchian_width.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_efficiency_ratio
Source:
custom/custom_efficiency_ratio.rs
Cumulative net price displacement divided by cumulative absolute movement.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_ema
Source:
custom/custom_ema.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_ewma_volatility
Source:
custom/custom_ewma_volatility.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_force_index
Source:
custom/custom_force_index.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_historical_volatility
Source:
custom/custom_historical_volatility.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_kama
Source:
custom/custom_kama.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_large_trade_ratio
Source:
custom/custom_large_trade_ratio.rs
Share of trades whose quantity is at least a configured threshold.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_linear_regression
Source:
custom/custom_linear_regression.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_log_return
Source:
custom/custom_log_return.rs
Natural log return between consecutive positive trade prices.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_logistic_regression
Source:
custom/custom_logistic_regression.rs
Online logistic regression over trade log-returns.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_macd_signal
Source:
custom/custom_macd_signal.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_median_price
Source:
custom/custom_median_price.rs
Running midpoint of the observed trade-price range.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_mfi
Source:
custom/custom_mfi.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_momentum
Source:
custom/custom_momentum.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_money_flow
Source:
custom/custom_money_flow.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_obv
Source:
custom/custom_obv.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_parkinson_volatility
Source:
custom/custom_parkinson_volatility.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_price_impact
Source:
custom/custom_price_impact.rs
Absolute price change per unit of the current trade quantity.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_return_kurtosis
Source:
custom/custom_return_kurtosis.rs
Online excess population kurtosis of simple returns.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_return_skewness
Source:
custom/custom_return_skewness.rs
Online population skewness of simple returns.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_return_variance
Source:
custom/custom_return_variance.rs
Online population variance of simple trade-to-trade returns.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_roc
Source:
custom/custom_roc.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_rsi
Source:
custom/custom_rsi.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_signed_volume_ratio
Source:
custom/custom_signed_volume_ratio.rs
Cumulative signed volume divided by cumulative volume.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_sma
Source:
custom/custom_sma.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_stochastic_k
Source:
custom/custom_stochastic_k.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_tema
Source:
custom/custom_tema.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_tick_direction
Source:
custom/custom_tick_direction.rs
Latest non-zero price tick direction: -1, 0, or 1.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_tick_run_length
Source:
custom/custom_tick_run_length.rs
Number of consecutive non-zero price ticks in the latest direction.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_trade_imbalance
Source:
custom/custom_trade_imbalance.rs
Net count of buyer-initiated minus seller-initiated trades.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_trade_intensity
Source:
custom/custom_trade_intensity.rs
Trades per elapsed second since the first valid trade.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_trix
Source:
custom/custom_trix.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_true_range
Source:
custom/custom_true_range.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_typical_price
Source:
custom/custom_typical_price.rs
Trade-price value, provided as an explicit custom-indicator contract.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_volume_roc
Source:
custom/custom_volume_roc.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_volume_zscore
Source:
custom/custom_volume_zscore.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_vortex
Source:
custom/custom_vortex.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_vwap
Source:
custom/custom_vwap.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_vwma
Source:
custom/custom_vwma.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_williams_r
Source:
custom/custom_williams_r.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_wma
Source:
custom/custom_wma.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/custom_zscore
Source:
custom/custom_zscore.rs
No module documentation.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: custom/signed_volume
Source:
custom/signed_volume.rs
Example custom indicator discovered automatically by build.rs.
Statics
pub static REGISTRATION
#![allow(unused)]
fn main() {
pub static REGISTRATION: CustomIndicatorRegistration = ...;
}
Module: lib
Source:
lib.rs
Structured trade logging.
[TradeLog] writes JSON-formatted fill records to a CSV-compatible
log file for post-session analysis and reconciliation.
Structs
pub struct TradeLog
#![allow(unused)]
fn main() {
pub struct TradeLog {
writer: Option < BufWriter < File > >,
};
}
Module: controls
Source:
controls.rs
Risk control enforcement at runtime.
[RiskControls] validates orders and positions against configured limits
(max position size, max drawdown, order frequency, daily loss, cooldown).
Structs
pub struct RiskControls
#![allow(unused)]
fn main() {
pub struct RiskControls {
pub max_position_size: f64,
pub max_order_notional: f64,
pub max_position_notional: f64,
pub max_drawdown: f64,
pub max_order_freq: u32,
pub max_daily_loss: f64,
pub cooldown_after_loss_secs: u64,
order_count: u32,
window_start: Instant,
daily_loss: f64,
peak_equity: f64,
in_cooldown: bool,
cooldown_end: Instant,
last_market_data_at: Option < Instant >,
max_market_data_age: Duration,
paused: bool,
pause_reason: Option < String >,
};
}
Module: lib
Source:
lib.rs
Risk management configuration and controls.
Defines [RiskConfig] for parameterizing position sizing, drawdown limits,
order frequency, daily loss caps, and cooldown periods.
Structs
pub struct RiskConfig
#![allow(unused)]
fn main() {
pub struct RiskConfig {
pub max_position_size: f64,
pub max_order_notional: f64,
pub max_position_notional: f64,
pub max_drawdown: f64,
pub max_order_freq: u32,
pub max_daily_loss: f64,
pub cooldown_after_loss_secs: u64,
};
}
Module: capture_merge
Source:
capture_merge.rs
Deterministic, offline merger for independently captured replay streams.
This tool is deliberately narrow: it joins one converted trade capture and one converted depth capture. It opens no network connection and preserves every input JSON object verbatim. When the millisecond timestamps tie, a trade is emitted before depth. That conservative ordering prevents a same-timestamp depth snapshot from influencing a preceding trade; ties are counted in the report because their true exchange ordering is unknown.
Structs
pub struct MergeSummary
#![allow(unused)]
fn main() {
pub struct MergeSummary {
pub trades: u64,
pub depth_snapshots: u64,
pub timestamp_ties: u64,
pub output: String,
};
}
Functions
pub fn merge
#![allow(unused)]
fn main() {
pub fn merge(...) { ... }
}
Merge converted trade and depth JSONL captures in market-time order.
Input files must each be nondecreasing by timestamp_ms. Same-millisecond
cross-stream events are allowed but reported; trades come first as the
conservative deterministic tie-breaker described in this module’s docs.
Module: dashboard
Source:
dashboard.rs
Read-only local operator dashboard.
It deliberately has no order-control endpoints. A dedicated background worker reads the durable journal and delivers snapshots through a bounded crossbeam channel; the engine’s latency-sensitive loop never waits on HTTP, a mutex, or a dashboard client.
Functions
pub fn start
#![allow(unused)]
fn main() {
pub fn start(...) { ... }
}
Module: lib
Source:
lib.rs
Quince trading bot — crate root.
Re-exports all sub-crates (core, engine, exchange, indicators,
logger, risk) as a unified public API for the binary entry point.
Module: main
Source:
main.rs
Quince trading bot binary entry point. Configures the trading environment from environment variables, selects mock/public/live exchange mode, and launches the main engine event loop.
Module: mock
Source:
mock.rs
Mock exchange for local strategy testing.
[MockExchange] simulates order matching, position tracking, and price
streams without network dependencies — suitable for integration tests
and strategy dry-runs.
Structs
pub struct MockExchange
#![allow(unused)]
fn main() {
pub struct MockExchange {
order_counter: AtomicU64,
public: Option < BinancePublic >,
state: Arc < Mutex < MockState > >,
};
}
Module: okx_import
Source:
okx_import.rs
Streaming importer for reconstructed OKX/Tardis book_snapshot_25 CSV.
Input is read from stdin so compressed archives can be decompressed outside the process without buffering a trading day in memory.
Functions
pub fn import_snapshot_25
#![allow(unused)]
fn main() {
pub fn import_snapshot_25(...) { ... }
}
pub fn import_trades
#![allow(unused)]
fn main() {
pub fn import_trades(...) { ... }
}
Module: replay
Source:
replay.rs
Deterministic, offline QFL market-data replay.
The input is newline-delimited JSON. Every line has schema_version: 1
and one of these event shapes:
{"schema_version":1,"type":"trade","timestamp_ms":...,"price":..., "qty":...,"side":"buy|sell","trade_id":...};
{"schema_version":1,"type":"depth","timestamp_ms":...,"bids":[{"price":...,"qty":...}], "asks":[...]}; or {"schema_version":1,"type":"eval","timestamp_ms":...}.
Replay never opens a socket and never sends an exchange order. QFL order intents are captured in-memory and reported as deterministic counters.
Structs
pub struct ReplayCostModel
#![allow(unused)]
fn main() {
pub struct ReplayCostModel {
pub fee_bps: f64,
pub slippage_bps: f64,
};
}
Taker-style cost assumptions for offline paper execution.
The defaults are intentionally conservative: 10 bps fee and 5 bps of
adverse slippage per fill. They are not an exchange fee schedule. Set
QUINCE_REPLAY_FEE_BPS and QUINCE_REPLAY_SLIPPAGE_BPS to model a
specific venue/account tier.
pub struct ReplaySummary
#![allow(unused)]
fn main() {
pub struct ReplaySummary {
pub schema_version: u8,
pub events: u64,
pub trades: u64,
pub depth_snapshots: u64,
pub eval_ticks: u64,
pub order_intents: u64,
pub buy_intents: u64,
pub sell_intents: u64,
pub strategy_logs: u64,
pub signal_logs: u64,
pub log_samples: Vec < String >,
pub cost_model: ReplayCostModel,
pub paper_fills: u64,
pub unfilled_intents: u64,
pub filled_notional_quote: f64,
pub fees_quote: f64,
pub slippage_cost_quote: f64,
pub realized_gross_pnl_quote: f64,
pub unrealized_gross_pnl_quote: f64,
pub gross_pnl_quote: f64,
pub net_pnl_quote: f64,
pub ending_position_qty: f64,
pub ending_mark_price: Option < f64 >,
pub performance: ReplayPerformance,
};
}
pub struct ReplayPerformance
#![allow(unused)]
fn main() {
pub struct ReplayPerformance {
pub initial_equity_quote: f64,
pub ending_equity_quote: f64,
pub net_return_fraction: f64,
pub max_drawdown_fraction: f64,
pub observations: u64,
pub mean_return_per_observation: f64,
pub volatility_per_observation: f64,
pub sharpe_per_observation: Option < f64 >,
pub sortino_per_observation: Option < f64 >,
};
}
Reproducible performance statistics for one offline replay.
Enums
pub enum ReplayError
#![allow(unused)]
fn main() {
pub enum ReplayError {
Open(path: String,
source: std :: io :: Error,),
Read(line: usize,
source: std :: io :: Error,),
Invalid(line: usize,
reason: String,),
Strategy(String,),
CostModel(String,),
}
}
Functions
pub fn run
#![allow(unused)]
fn main() {
pub fn run(...) { ... }
}
Replay a versioned JSONL market-data capture through a QFL strategy. Event order is the file order, deliberately: no wall-clock scheduling, random identifiers, exchange requests, or parallel dispatch are involved.
pub fn run_with_cost_model
#![allow(unused)]
fn main() {
pub fn run_with_cost_model(...) { ... }
}
As [run], with explicit cost assumptions for deterministic tests and
programmatic callers. It is still strictly offline paper execution.
Module: replay_suite
Source:
replay_suite.rs
Deterministic batch replay reporting.
A suite never turns a failed/unsupported strategy into a zero-result run. Every discovered artifact has a corresponding outcome, so an operator can distinguish a strategy that produced no intents from one that did not load.
Structs
pub struct ReplaySuiteResult
#![allow(unused)]
fn main() {
pub struct ReplaySuiteResult {
pub strategy: String,
pub status: String,
pub summary: Option < ReplaySummary >,
pub error: Option < String >,
};
}
pub struct ReplaySuiteSummary
#![allow(unused)]
fn main() {
pub struct ReplaySuiteSummary {
pub schema_version: u8,
pub capture: String,
pub symbol: String,
pub strategies_discovered: u64,
pub strategies_succeeded: u64,
pub strategies_failed: u64,
pub results: Vec < ReplaySuiteResult >,
};
}
Enums
pub enum ReplaySuiteError
#![allow(unused)]
fn main() {
pub enum ReplaySuiteError {
ReadDirectory(path: String,
source: std :: io :: Error,),
ReadDirectoryEntry(path: String,
source: std :: io :: Error,),
}
}
Functions
pub fn run
#![allow(unused)]
fn main() {
pub fn run(...) { ... }
}
Run every immediate .qfl artifact in strategy_directory in a
stable lexical order. The capture is replayed separately for every strategy
so state can never leak between artifacts.
Module: research
Source:
research.rs
Reproducible offline research reports built on deterministic replay.
Structs
pub struct ResearchReport
#![allow(unused)]
fn main() {
pub struct ResearchReport {
pub schema_version: u8,
pub capture: String,
pub symbol: String,
pub strategies_discovered: u64,
pub strategies_succeeded: u64,
pub strategies_failed: u64,
pub results: Vec < ReplaySuiteResult >,
};
}
Stable, machine-readable outcome of replaying a strategy set on one capture.
Enums
pub enum ResearchError
#![allow(unused)]
fn main() {
pub enum ResearchError {
ReplaySuite(replay_suite :: ReplaySuiteError,),
CreateDirectory(path: String,
source: std :: io :: Error,),
Serialize(serde_json :: Error,),
Write(path: String,
source: std :: io :: Error,),
}
}
Functions
pub fn write_report
#![allow(unused)]
fn main() {
pub fn write_report(...) { ... }
}
Run the replay suite and atomically materialize JSON and self-contained HTML
under output_directory. The report has no wall-clock timestamp so equal
inputs produce byte-for-byte equal JSON.
Module: wallet
Source:
wallet.rs
Local EVM wallet onboarding for Hyperliquid.
The public profile is stored separately from a file-encrypted private key. The private key is encrypted with AES-256-CBC and authenticated with HMAC-SHA-256 (encrypt-then-MAC). The passphrase is never persisted.
Structs
pub struct WalletProfile
#![allow(unused)]
fn main() {
pub struct WalletProfile {
pub version: u8,
pub hyperliquid_address: String,
};
}
pub struct EncryptedFileHyperliquidSigner
#![allow(unused)]
fn main() {
pub struct EncryptedFileHyperliquidSigner {
address: String,
passphrase: Zeroizing < String >,
};
}
Signer backed by the encrypted wallet file. It retains a passphrase only for the lifetime of this process; the decrypted signing key is zeroized after every signature.
Functions
pub fn load_profile
#![allow(unused)]
fn main() {
pub fn load_profile(...) { ... }
}
pub fn has_private_key
#![allow(unused)]
fn main() {
pub fn has_private_key(...) { ... }
}
pub fn load_hyperliquid_signer
#![allow(unused)]
fn main() {
pub fn load_hyperliquid_signer(...) { ... }
}
Opens the encrypted-file signer only if its secret belongs to the public profile. This catches a replaced encrypted file before authenticated use.
pub fn is_interactive
#![allow(unused)]
fn main() {
pub fn is_interactive(...) { ... }
}
pub fn needs_setup
#![allow(unused)]
fn main() {
pub fn needs_setup(...) { ... }
}
pub fn create_wallet
#![allow(unused)]
fn main() {
pub fn create_wallet(...) { ... }
}
pub fn import_wallet
#![allow(unused)]
fn main() {
pub fn import_wallet(...) { ... }
}
pub fn run_setup_wizard
#![allow(unused)]
fn main() {
pub fn run_setup_wizard(...) { ... }
}
Start a terminal-only setup wizard. Private-key and passphrase input is never echoed.
Module: bin/dump_qfl
Source:
bin/dump_qfl.rs
QFL program dump utility.
Parses, compiles, and optionally optimizes a .qfl strategy file,
then prints its IR instructions and entry points for debugging.