Repository avatar
Developer Tools
v1.0.2
active

slimquant

io.github.apexhive-hq/slimquant

Deterministic quant risk gate, purged walk-forward backtest, and audit ledger MCP server.

Documentation

slimquant

CI npm version

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. slimquant never 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-in node:sqlite and unproxied node:https requests; zero Python or C++ native addons required).

    Note for MCP stdio clients on Node 22: node:sqlite may print an ExperimentalWarning on stderr; Node 24+ runs without warnings, or set NODE_NO_WARNINGS=1 in MCP client env on Node 22.

  • Optional LLM API key (GEMINI_API_KEY, OPENAI_API_KEY, or ANTHROPIC_API_KEY) and SLIMQUANT_ALLOW_ONLINE_LLM=1 only 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

  1. Market Ingestion & SSRF Guard (market-data.ts, ssrf.ts) Fetches closed daily OHLCV bars from Binance public data (CRYPTO_SPOT and spot-reference CRYPTO_PERP proxy via binance-vision-spot-ref, filtering unclosed intraday UTC bars via closeTime <= now) or Yahoo Finance (EQUITY, FUTURES, FX_METAL, applying split/dividend adjclose adjustment and excluding active intraday bars via currentTradingPeriod) behind DNS-verified IP-pinned HTTPS validation and bounded stream reads.
  2. Purged & Embargoed Walk-Forward Backtester (walkforward.ts) Evaluates trend_sma_20_50, breakout_donchian_20, and mean_reversion_rsi14 strictly observing bar i - 1 close before entering at bar i open, simulating ATR stops, 2.0R profit targets, fees, and slippage across a continuous out-of-sample segment separated from in-sample selection by embargoBars >= max(50, lookbackBars, holdBars). Ranks baseline strategies strictly by in-sample performance (zero OOS selection bias) and annualizes Sharpe using observed OOS trading frequency.
  3. 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.
  4. 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-fingerprinted VerifiedFactPack.
  5. Single-Pass Proposer & External Audit (adversarial.ts, engine.ts) Supports deterministic offline proposals, single-pass zod-validated external LLM synthesis, or direct external trade proposal injection via auditProposal.
  6. 20 Deterministic Risk Laws (laws.ts) Recomputes entry/stop/targets (target1 primary, target2 3R reference), contract pointValue multipliers, whole-contract rounding for futures, Quarter-Kelly sizing, Brier shrinkage, liquidity limits (note: micro futures MES/MNQ/MGC/MCL scale upstream parent-contract feedPointValue ADV, which acts as a coarse reference ceiling above small/mid account leverage caps), gap-tail survival, and hard vetoes before emitting GO, GO SMALLER, or NO-GO.
  7. SQLite & Hash-Chained Audit Ledger (ledger.ts) Commits verdicts atomically inside cross-process locked SQLite transactions alongside an append-only SHA-256 hash-chained verdicts_ledger.jsonl, requiring limit entry touch before resolving target1/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

#LawEffect
1Emergency Kill Switch (SLIMQUANT_KILL_FILE, ./KILL, SLIMQUANT_DATA_DIR/KILL, or ~/.slimquant/KILL)Hard veto (NO-GO)
2Non-Advisory Compliance Firewall (across thesis, edge, counterparty, invalidation, risks)Hard veto (NO-GO)
3Data Freshness Ceiling (maxDataAgeDays, capped at 2.0d for CRYPTO_*, finite pointValue > 0)Hard veto on stale or incomplete OHLCV feeds
4Embargo Integrity (embargoBars >= max(50, lookback, hold))Hard veto if anti-leakage gap violated
5Out-of-Sample Trade Sample Floor (minOosTrades)Halves size (SHRINK) below minimum OOS trade threshold
6OOS Profit Factor, Sharpe & Decay GuardHard 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
7Rolling 24h UTC Loss Circuit Breaker (maxDailyLossPct) & Consecutive Loss CooloffHard veto (NO-GO) if rolling 24h realized loss or streak threshold hit
8Directional Proposal Check (long or short)Hard veto on flat / missing direction
9Thesis & Explicit Invalidation LevelHard veto if thesis or invalidation missing
10Concise Edge Explanation (<= 5 sentences)Hard veto if missing or verbose
11Adverse Selection Counterparty CheckHard veto if missing or asymmetric
12Baseline Deterministic Signal AlignmentHard veto in autonomous mode when opposing active baseline signal; SHRINK on divergence in external mode or flat baseline
13Max Entry Distance From Close (maxEntryGapPct)Hard veto if entry gaps beyond threshold
14Anti-Chase Proximity (<= 1.0 ATR14)Hard veto if chasing beyond 1 ATR
15Minimum Volatility Stop Floor (minStopAtr)Hard veto if stop sits inside market noise
16Minimum Reward-to-Risk Gate (minRewardRisk on primary target1)Hard veto below minimum R:R threshold
17Calibrated Positive Expected Value After Humility MarginHard veto if calibrated EV <= 0
18Macro Event Horizon (FOMC/CPI/NFP), CME Maintenance & Unpaid RisksHalves size (SHRINK) when unpriced or event risks active
19Quarter-Kelly + Contract pointValue Risk Cap + Spot 20% / Margin 4x Cap + 1% 20d ADV CapCaps size (SHRINK) on exposure/liquidity ceilings (PASS when within budget)
202-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 optional bars array)
  • audit_proposal (supports optional bars array)
  • scan_watchlist (supports optional bars symbol map { "SYM": [bars] })
  • export_pine (supports optional bars array)
  • ledger_score (supports optional bars symbol map on resolveOpen: true, returns fetchErrors and ok)

Non-advisory quantitative research software. Outputs are analytical diagnostics, not personalized financial advice.

NPM
slimquant
Install Command
npm install slimquant