
slimquant
io.github.apexhive-hq/slimquant
Deterministic quant risk gate, purged walk-forward backtest, and audit ledger MCP server.
Documentation
slimquant
Deterministic quantitative risk gate, purged walk-forward backtester, Brier calibration ledger, TradingView Pine Script v6 exporter, and native Model Context Protocol (stdio) server in a single Node.js >= 22.13.0 package.
Non-advisory quantitative research & risk-gate software.
slimquantnever connects to broker execution APIs or places live orders.
slimquant runs offline with deterministic market & risk checks by default (provider: "offline"), audits arbitrary trade proposals from external AI agents (audit_proposal / slimquant audit), or pairs a compact BM25-indexed VerifiedFactPack with a single opt-in LLM pass (SLIMQUANT_ALLOW_ONLINE_LLM=1 + gemini, openai, or anthropic) behind 20 fail-closed risk laws.
Requirements
- Node.js
>= 22.13.0(uses built-innode:sqliteand unproxiednode:httpsrequests; zero Python or C++ native addons required).Note for MCP
stdioclients on Node 22:node:sqlitemay print anExperimentalWarningonstderr; Node 24+ runs without warnings, or setNODE_NO_WARNINGS=1in MCP client env on Node 22. - Optional LLM API key (
GEMINI_API_KEY,OPENAI_API_KEY, orANTHROPIC_API_KEY) andSLIMQUANT_ALLOW_ONLINE_LLM=1only when explicitly enabling an online provider.
Install & Quick Start (npm / npx)
Run directly via npx or install globally (zero API keys required, offline-safe by default):
npx -y slimquant --version
npx -y slimquant doctor
npx -y slimquant benchmark --json
# Or install globally:
npm install -g slimquant
slimquant doctor
Run offline with the bundled sample OHLCV fixtures (examples/sample-bars.json array or examples/watchlist-bars.json symbol map; CLI defaults to read-only unless --persist is passed):
# If running from source (or use `slimquant` when installed globally):
node dist/src/cli.js analyze AAPL --bars-file ./examples/sample-bars.json --json
node dist/src/cli.js scan AAPL,MSFT --bars-file ./examples/watchlist-bars.json --json
node dist/src/cli.js score --resolve --bars-file ./examples/watchlist-bars.json --json
node dist/src/cli.js pine AAPL --bars-file ./examples/sample-bars.json --out aapl_audit.pine
Audit an external agent's trade proposal against offline --bars-file (or live) market checks and all 20 deterministic laws:
node dist/src/cli.js audit AAPL --bars-file ./examples/sample-bars.json --decision long --entry 240 --stop 230 --target 260 --pwin 0.56 --thesis "Institutional accumulation above rising 50-day mean." --edge "Vol-adjusted breakout after compression." --other-side "Profit taking from prior quarter range sellers." --invalidation "Daily close below 230."
Build & Run From Source
git clone https://github.com/apexhive-hq/slimquant.git
cd slimquant
pnpm install --ignore-scripts
pnpm run build:prod
node dist/src/cli.js doctor
node dist/src/cli.js --help
Live Market & Opt-In LLM Examples (Requires Outbound DNS/HTTPS)
# Live daily bars from Yahoo Finance / Binance public APIs:
node dist/src/cli.js analyze AAPL --capital 100000
node dist/src/cli.js analyze MES --capital 100000 --pine
node dist/src/cli.js scan AAPL,MSFT,BTCUSDT,MES
# Opt-in single-pass online LLM synthesis (requires explicit SLIMQUANT_ALLOW_ONLINE_LLM=1):
export SLIMQUANT_ALLOW_ONLINE_LLM=1
export GEMINI_API_KEY="..."
node dist/src/cli.js analyze AAPL --provider gemini --bars-file ./examples/sample-bars.json
Inspect ledger hash-chain integrity and Brier calibration (live or --bars-file):
node dist/src/cli.js score --resolve --bars-file ./examples/watchlist-bars.json
Architecture
- Market Ingestion & SSRF Guard (
market-data.ts,ssrf.ts) Fetches closed daily OHLCV bars from Binance public data (CRYPTO_SPOTand spot-referenceCRYPTO_PERPproxy viabinance-vision-spot-ref, filtering unclosed intraday UTC bars viacloseTime <= now) or Yahoo Finance (EQUITY,FUTURES,FX_METAL, applying split/dividendadjcloseadjustment and excluding active intraday bars viacurrentTradingPeriod) behind DNS-verified IP-pinned HTTPS validation and bounded stream reads. - Purged & Embargoed Walk-Forward Backtester (
walkforward.ts) Evaluatestrend_sma_20_50,breakout_donchian_20, andmean_reversion_rsi14strictly observing bari - 1close before entering at bariopen, simulating ATR stops, 2.0R profit targets, fees, and slippage across a continuous out-of-sample segment separated from in-sample selection byembargoBars >= max(50, lookbackBars, holdBars). Ranks baseline strategies strictly by in-sample performance (zero OOS selection bias) and annualizes Sharpe using observed OOS trading frequency. - Macro Calendar (
macro.ts) Tracks 2026–2027 Federal Reserve FOMC (14:00 ET), BLS CPI (08:30 ET), and BLS NFP (08:30 ET) windows with US/EU DST mismatch detection, CME futures maintenance flags, and post-2027 schedule expiry notice. - Compact FactPack & BM25 Retrieval (
evidence.ts,redactor.ts) Indexes regime snapshots, OOS metrics, macro notices, and research notes in pure TypeScript BM25 with regex secret redaction, assembling a SHA-256-fingerprintedVerifiedFactPack. - Single-Pass Proposer & External Audit (
adversarial.ts,engine.ts) Supports deterministic offline proposals, single-passzod-validated external LLM synthesis, or direct external trade proposal injection viaauditProposal. - 20 Deterministic Risk Laws (
laws.ts) Recomputes entry/stop/targets (target1primary,target23R reference), contractpointValuemultipliers, whole-contract rounding for futures, Quarter-Kelly sizing, Brier shrinkage, liquidity limits (note: micro futuresMES/MNQ/MGC/MCLscale upstream parent-contractfeedPointValueADV, which acts as a coarse reference ceiling above small/mid account leverage caps), gap-tail survival, and hard vetoes before emittingGO,GO SMALLER, orNO-GO. - SQLite & Hash-Chained Audit Ledger (
ledger.ts) Commits verdicts atomically inside cross-process locked SQLite transactions alongside an append-only SHA-256 hash-chainedverdicts_ledger.jsonl, requiring limit entry touch before resolvingtarget1/stop collisions conservatively as losses (-1R), modeling conditional limit orders gapping past stop before fill as invalidated (EXPIRED: setup_invalidated_before_fill), expiring unfilled setups after 30 days on fresh feeds, and path-containing MCP storage (SLIMQUANT_DATA_DIR/~/.slimquant).
20 Deterministic Risk Laws
| # | Law | Effect |
|---|---|---|
| 1 | Emergency Kill Switch (SLIMQUANT_KILL_FILE, ./KILL, SLIMQUANT_DATA_DIR/KILL, or ~/.slimquant/KILL) | Hard veto (NO-GO) |
| 2 | Non-Advisory Compliance Firewall (across thesis, edge, counterparty, invalidation, risks) | Hard veto (NO-GO) |
| 3 | Data Freshness Ceiling (maxDataAgeDays, capped at 2.0d for CRYPTO_*, finite pointValue > 0) | Hard veto on stale or incomplete OHLCV feeds |
| 4 | Embargo Integrity (embargoBars >= max(50, lookback, hold)) | Hard veto if anti-leakage gap violated |
| 5 | Out-of-Sample Trade Sample Floor (minOosTrades) | Halves size (SHRINK) below minimum OOS trade threshold |
| 6 | OOS Profit Factor, Sharpe & Decay Guard | Hard veto (NO-GO) in autonomous mode if Sharpe <= 0, PF <= 1.0, or recent decay < -15%; halving (SHRINK) if overfitDecayRatio < 0.45 or weak in external mode |
| 7 | Rolling 24h UTC Loss Circuit Breaker (maxDailyLossPct) & Consecutive Loss Cooloff | Hard veto (NO-GO) if rolling 24h realized loss or streak threshold hit |
| 8 | Directional Proposal Check (long or short) | Hard veto on flat / missing direction |
| 9 | Thesis & Explicit Invalidation Level | Hard veto if thesis or invalidation missing |
| 10 | Concise Edge Explanation (<= 5 sentences) | Hard veto if missing or verbose |
| 11 | Adverse Selection Counterparty Check | Hard veto if missing or asymmetric |
| 12 | Baseline Deterministic Signal Alignment | Hard veto in autonomous mode when opposing active baseline signal; SHRINK on divergence in external mode or flat baseline |
| 13 | Max Entry Distance From Close (maxEntryGapPct) | Hard veto if entry gaps beyond threshold |
| 14 | Anti-Chase Proximity (<= 1.0 ATR14) | Hard veto if chasing beyond 1 ATR |
| 15 | Minimum Volatility Stop Floor (minStopAtr) | Hard veto if stop sits inside market noise |
| 16 | Minimum Reward-to-Risk Gate (minRewardRisk on primary target1) | Hard veto below minimum R:R threshold |
| 17 | Calibrated Positive Expected Value After Humility Margin | Hard veto if calibrated EV <= 0 |
| 18 | Macro Event Horizon (FOMC/CPI/NFP), CME Maintenance & Unpaid Risks | Halves size (SHRINK) when unpriced or event risks active |
| 19 | Quarter-Kelly + Contract pointValue Risk Cap + Spot 20% / Margin 4x Cap + 1% 20d ADV Cap | Caps size (SHRINK) on exposure/liquidity ceilings (PASS when within budget) |
| 20 | 2-ATR Overnight Gap-Tail Survival + Whole-Contract Rounding (Futures) | Reduces size (SHRINK) or vetoes (NO-GO) if budget cannot carry 1 contract |
MCP Server Integration
Start over stdio (CLI and MCP share one default ledger under SLIMQUANT_DATA_DIR or ~/.slimquant; paid LLM providers are disabled by default — set SLIMQUANT_ALLOW_ONLINE_LLM=1 explicitly to enable online LLMs):
node dist/src/cli.js serve
Example MCP client configuration:
{
"mcpServers": {
"slimquant": {
"command": "node",
"args": ["/path/to/slimquant/dist/src/cli.js", "serve"]
}
}
}
Exposed MCP tools:
analyze_asset(supports optionalbarsarray)audit_proposal(supports optionalbarsarray)scan_watchlist(supports optionalbarssymbol map{ "SYM": [bars] })export_pine(supports optionalbarsarray)ledger_score(supports optionalbarssymbol map onresolveOpen: true, returnsfetchErrorsandok)
Non-advisory quantitative research software. Outputs are analytical diagnostics, not personalized financial advice.
- Security & Contact:
apexhive.hq@proton.me· SeeSECURITY.md&CHANGELOG.md - License: MIT
slimquantnpm install slimquant