Skip to content

Repository files navigation

RegimeRoute

RegimeRoute is a paper-trading crypto router focused on proof-carrying routing resilience, not timing alpha. Every routing decision becomes a downloadable, hash-verifiable Execution Receipt with a deterministic Decision Robustness Certificate: what the router knew, why it acted, how the route behaves under evidence-supported counterfactuals, and which claims it refuses when retained depth is insufficient.

Release: 0.9.0 pre-release

DEMO · PAPER TRADING · SIMULATED FUNDS — no real orders, custody, or balances.

Screenshot 2026-08-18 at 11 51 41 PM

Overview

RegimeRoute routes simulated orders over live public feeds from Binance, Coinbase, Kraken, Bybit, OKX, and Bitfinex. Its regime-aware scheduler changes child-slice timing and falls back to flat TWAP when confidence is low. For each decision it preserves a best-execution-proof/v2 evidence object and exposes it in an execution-receipt/v1 envelope. Common-coverage and capacity-adjusted claims are independently qualified; unsupported capacity claims have a null edge and an explicit reason code rather than a price extrapolated beyond observed depth.

FireShot Capture 003 - RegimeRoute — Smart Order Router -  localhost

Execution Receipt workflow

  1. Submit a paper order with POST /api/orders and inspect its decision evidence with GET /api/orders/:id/proofs.
  2. Download a receipt with authenticated GET /api/proofs/:id/receipt. The response is JSON with Content-Disposition: attachment.
  3. Read integrity.status (verified or invalid) and inspect each claim's status (supported or unavailable), reason_code, coverage, benchmark, and nullable edge_bps.
  4. Inspect decision_robustness: four deterministic scenarios report alternative feasibility, route, comparable quantity, counterfactual effective price, degradation bps when supported, or a reason code when not.
  5. Independently recompute SHA-256 over canonical proof.evidence (including the certificate), or ask the engine with POST /api/proofs/:id/verify.

Demo: submit a paper order, open its receipt card, compare the stable/fragile classification and scenario coverage, expand the outage/price/fee/freshness rows, then recompute the hash and download the JSON. The product edge is inspectable resilience and refusal-to-claim—not proven alpha.

Concise receipt shape:

{
  "schema_version": "execution-receipt/v1",
  "integrity": {
    "status": "verified",
    "hash_algorithm": "SHA-256",
    "signature": null,
    "external_anchor": null
  },
  "claims": {
    "common_coverage_edge": {
      "status": "supported",
      "reason_code": "common_comparable_quantity_observed",
      "edge_bps": -0.12
    },
    "capacity_adjusted_edge": {
      "status": "unavailable",
      "reason_code": "selected_venue_insufficient_observed_depth",
      "edge_bps": null
    }
  }
}

Values above illustrate the contract, not a captured run. A verified hash is tamper-evident for the embedded evidence; it is not a signature and is not externally anchored. A receipt does not establish globally best execution, exchange fill, regulatory compliance, or a profitable strategy.

Architecture

flowchart LR
    E[Exchange feeds<br/>Binance, Coinbase, Kraken,<br/>Bybit, OKX, Bitfinex]
    N[Normalization]
    B[Consolidated in-memory books]
    D[Regime detector]
    R[Routing and scheduling]
    P[Paper-fill simulation]
    A[REST and WebSocket API]
    U[Next.js dashboard]
    C[Normalized NDJSON capture]
    X[Replay runners and scenarios]
    DB[(PostgreSQL)]
    RD[(Redis snapshots)]

    E --> N --> B --> D --> R --> P --> A --> U
    B --> RD
    P --> DB
    N --> C --> X
    X --> B
Loading

The live engine and replay executables share the C++ rr_core routing, scheduling, regime, and market-data code. Capture stores normalized production updates before book mutation; replay feeds those records back through the same market-data boundary using a semantic replay clock.

Why it exists and what makes it different

The system exists to make routing decisions inspectable and reproducible. Its differentiator is evidence-aware, auditable routing decisions and execution receipts—not a promise of profit or globally best execution.

Research result

The original economic alpha hypothesis was tested and did not demonstrate a meaningful trading edge in the validated dataset.

A paired real-data test compared the regime-aware adaptive schedule against a flat TWAP baseline on identical real market data. The core hypothesis — that front-loading execution in a detected TRENDING regime beats a timing-blind schedule — was tested and not supported: front-loaded TRENDING executions averaged +0.00275 bps and won only 28.6% of paired comparisons.

A separate venue-selection comparison (choosing the best real venue vs. a single-venue naive baseline) found a small measurable edge at medium/large order sizes (~0.02 bps average), which is economically smaller than typical real exchange trading fees and not a meaningful trading advantage on its own.

No economically meaningful, tradeable edge was found in either the timing mechanism or the venue-selection mechanism, at the sample sizes tested. The timing test's clean split had a small sample—7 front-loaded and 5 back-loaded TRENDING orders—and would benefit from more accumulated real data over time; that does not change the current conclusion.

How this was validated

Validation focused on whether the claimed edge survived reproducible tests, not on making the result look favorable.

  • Debugging found and fixed a corrupted-venue-quote issue involving bad Coinbase data, a partial-fill realized-price averaging bug, and a naive-baseline comparison bug that extrapolated price across quantity the baseline could not access and handled BUY/SELL comparisons inconsistently.
  • The execution comparison now separates common-coverage edge from a capacity-adjusted metric. When captured depth is insufficient to price the excess quantity honestly, the capacity-adjusted result is NULL rather than an estimate based on unobserved liquidity.
  • The replay harness consumes normalized NDJSON captured from live public exchange feeds and runs it through the production market-data, regime, router, scheduler, paper-fill, and persistence paths.
  • A paired counterfactual runner submits the same side, size, start timestamp, and real market data to the adaptive scheduler and flat TWAP scheduler. Both use the same router, so the comparison isolates timing rather than combining timing and venue-selection effects.
  • Each paired result is persisted as structured NDJSON with its regime, size tier, actual schedule shape, realized prices, filled quantities, improvement in basis points, and win/loss result. Aggregate reporting excludes pairs with unequal filled quantities rather than treating them as comparable.

The resulting negative finding is a complete engineering outcome: the project provides an auditable test infrastructure and can repeat the same evaluation as more real data accumulates, but it does not claim a proven trading edge.

Features

  • Multi-user demo registration, session authentication, profiles, balances, orders, fills, analytics, and owner-scoped WebSockets
  • Idempotent paper-order submission with transactional reservations
  • Public multi-venue market feeds, regime classification, routing, scheduling, capture, and replay
  • Downloadable hash-verifiable evidence receipts with explicit supported/unavailable claims
  • Honest liveness/readiness, migrations, backup/restore scripts, TLS reverse proxy, and CI

Local development

Prerequisites: Docker with Compose, Python 3 for the integration suite, and outbound HTTPS/WSS access to public exchange feeds.

cp .env.example .env
# Edit .env: use a unique SESSION_SECRET; development may keep COOKIE_SECURE=false.
docker compose up -d --build
docker compose ps

The only host-facing service is nginx on HTTP_PORT (default 80), so open http://localhost. PostgreSQL (5432), Redis (6379), the engine (9001), and Next.js (3000) remain internal to the Compose network. Registration requires an email-shaped identifier and an 8+ character password and immediately creates a tenant-isolated sandbox demo account. All balances, orders, and fills are simulated.

Liveness and readiness can be checked without curl:

python3 - <<'PY'
import json, urllib.request
for path in ('/api/health/live', '/api/health/ready'):
    with urllib.request.urlopen('http://localhost' + path) as r:
        print(path, r.status, json.load(r))
PY

live only confirms the engine process. ready additionally requires PostgreSQL, Redis, at least one fresh routable market, and—when enabled—a running capture writer with zero drops and errors. A disconnected or stale individual venue may still be reported while readiness remains healthy if another venue is routable.

Tests

# Against the started stack; override RR_HOST/RR_PORT if HTTP_PORT is not 80.
python3 tests/integration.py

# Frontend checks.
cd frontend
npm ci
npm audit --omit=dev --audit-level=high
npm run typecheck
npm run lint
npm run build
cd ..

# Engine release build and four CTest targets (or build the Docker build stage).
cmake -S engine -B engine/build -DCMAKE_BUILD_TYPE=Release
cmake --build engine/build -j4
ctest --test-dir engine/build --output-on-failure
python3 -m unittest replay/test_build_binance_backfill.py

The live suite creates ephemeral accounts and checks CSRF, owner scoping, repeated authenticated WebSocket isolation, idempotency, insufficient demo funds, cancellation accounting, logout revocation, and login. It depends on a routable public feed. docker compose down -v irreversibly removes disposable database and capture volumes.

Authentication, tenants, and order lifecycle

  • Authentication is email/password only. New password verifiers use scrypt; a legacy salted SHA-256 form is accepted only for migration. Opaque server-side sessions are stored by token hash, expire according to SESSION_TTL_HOURS, and are revoked on logout. Cookies are HttpOnly, SameSite=Strict, and Secure in production. State-changing authenticated requests require the returned CSRF token in X-CSRF-Token.
  • There is no email verification/delivery, password reset, MFA, OAuth, wallet login, or exchange credential custody. Auth and API requests are rate-limited through Redis; production also adds nginx per-IP limiting and same-origin enforcement via PUBLIC_ORIGIN.
  • Orders, proofs, account state, analytics, profiles, ledger rows, sessions, audit events, and authenticated WebSocket active_orders are user scoped. Non-owned order/proof IDs are deliberately returned as not found. Database triggers enforce order/decision and order/ledger tenant consistency; this is application/database isolation, not PostgreSQL row-level security.
  • Registration creates one USDT sandbox account with DEMO_STARTING_BALANCE. BUYs reserve simulated quote funds including simulated fees, fills settle the reservation, and cancellation releases the remainder. SELLs are cash-credit-only: base-asset inventory is not modeled or reserved. The append-only ledger is not real money, custody, or an exchange balance.
  • POST /api/orders requires an Idempotency-Key (maximum 128 characters). Reusing it with the same canonical payload returns the prior order; changing the payload returns a conflict. Orders begin pending, execute immediately (instant_sweep) or through slices (twap/regime_aware), may run and complete, or can be cancelled while active. Low-confidence regime-aware schedules fall back to equal-quantity TWAP. Partial/full-fill policy, venue allowlist, minimum quantity, and slippage limits constrain routing.

For the REST/WS contract, error envelope, receipt reason codes, and endpoint list, see docs/api.md.

Documentation

Production deployment and operations

See the complete fresh-server deployment guide. This is a single-host Compose deployment, not an orchestrated high-availability design. Before deployment, create a unique .env, set a random 32+ character SESSION_SECRET, set APP_ENV=production, disable SEED_DEMO unless intentionally required, and align POSTGRES_PASSWORD with the content of the protected password file. Set these shell variables without committing values:

  • PUBLIC_ORIGIN=https://your-canonical-domain (exact scheme and host used by browsers)
  • POSTGRES_PASSWORD_FILE=/absolute/protected/path/postgres_password
  • TLS_CERT_DIR=/absolute/protected/path/tls containing fullchain.pem and privkey.pem
export PUBLIC_ORIGIN='https://your-canonical-domain'
export POSTGRES_PASSWORD_FILE='/absolute/protected/path/postgres_password'
export TLS_CERT_DIR='/absolute/protected/path/tls'
docker compose -f docker-compose.yml -f docker-compose.prod.yml config --quiet
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d --build
docker compose -f docker-compose.yml -f docker-compose.prod.yml ps
scripts/migrate.sh

The production override redirects HTTP to HTTPS, exposes 80/443, mounts operator-provided TLS files, enables secure cookies, drops engine/frontend capabilities, prevents privilege escalation, uses read-only filesystems with /tmp tmpfs, and rotates local JSON logs. It does not issue or renew certificates. Restrict the host firewall and secret/TLS file permissions; do not expose database, Redis, or engine ports.

Numbered migrations are applied transactionally and recorded in schema_migrations; reruns skip recorded versions. Review every migration and take a verified backup before applying it. Do not edit an already-applied migration. Startup SQL initializes fresh volumes, but scripts/migrate.sh is the explicit upgrade path for existing volumes.

# Backup: creates mode-600-compatible files under BACKUP_DIR and prunes by age.
BACKUP_DIR=/protected/backups BACKUP_RETENTION_DAYS=30 scripts/backup.sh

# Restore is destructive (--clean --if-exists). Stop writers first and use a reviewed dump.
docker compose stop engine frontend nginx
scripts/restore.sh /protected/backups/regimeroute-YYYYMMDDTHHMMSSZ.dump
scripts/migrate.sh
docker compose up -d

Test restore regularly in a disposable database/stack, then run liveness, readiness, and a smoke workflow. Capture files live in the named captures volume and are not included in the PostgreSQL dump; back up that volume separately when capture retention is required.

Rollback and incidents

  • Application rollback: preserve the database backup, stop request-serving services, deploy the previously tested image/source revision, and restart. Database migrations have no automated down path; restore the pre-migration dump when schema rollback is required. Never run down -v in production.
  • Readiness failure: keep the instance out of service; inspect docker compose ps and docker compose logs --since=15m engine postgres redis nginx. Determine whether storage, all routable feeds, or enabled capture caused the failure. A stale single feed is degraded capacity, not necessarily total unavailability.
  • Suspected account/session abuse: preserve append-only audit_events and logs, rotate SESSION_SECRET (which invalidates existing cookie authentication), restart the engine, and investigate request/correlation IDs. There is no administrative session-revocation UI.
  • Data/receipt concern: stop new writes, preserve database and capture evidence, verify receipts, and compare hash-covered evidence. A failed hash detects evidence mismatch but cannot identify a signer or trusted timestamp.
  • Capacity or feed incident: prefer not-ready/failed routing over relaxing freshness, slippage, or capture-loss checks without review. Record the timeline, affected tenants/orders, actions, and recovery evidence.

Compose logs are the implemented observability layer. Engine logs carry request/correlation IDs; nginx and production containers use bounded local JSON logs. Health endpoints expose storage, feed/routability, regime, and capture state. No external metrics collector, alert routing, tracing backend, dashboard, SIEM export, SLO, or paging infrastructure is included; operators must supply and test those before production use.

Roadmap

Realistic future work includes signed/external receipt anchoring, measured capacity baselines, stronger account recovery/MFA, automated image publishing, and HA only after operational evidence justifies it. Real-money execution remains out of scope by default.

License

MIT

Tech stack

  • C++20 engine built with CMake, Boost/Asio/Beast, OpenSSL, libpq, and hiredis
  • Public exchange WebSocket market-data feeds
  • PostgreSQL 16 for users, orders, fills, proofs, replay provenance, and comparison fields
  • Redis 7 for current book snapshots
  • Next.js 16, React 19, and TypeScript dashboard
  • nginx reverse proxy
  • Docker Compose deployment
  • NDJSON capture and deterministic replay tooling

Project structure

.
├── engine/                 # C++ engine, replay tools, and tests
│   ├── include/rr/
│   ├── src/
│   └── tests/
├── frontend/               # Next.js dashboard
├── db/                     # PostgreSQL schema and migrations
├── nginx/                  # Reverse-proxy configuration
├── captures/               # Local capture samples
├── replay/                 # Replay scenarios and backfill tooling
├── postman/                # Local Postman workspace artifacts
├── scripts/                # Migration, backup, and restore commands
├── tests/                  # Live two-tenant integration suite
├── vault/                  # Focused architecture/operator/developer notes
├── .github/workflows/ci.yml
├── docker-compose.yml
├── docker-compose.prod.yml
└── .env.example

CI and repository readiness

The workflow in .github/workflows/ci.yml runs frontend install/audit/typecheck/lint/build, builds the engine Docker build stage (which runs four CTest targets), runs replay backfill unit tests, and validates development Compose on pushes and pull requests. Production Compose validation, the live integration suite, restore rehearsal, image publishing, deployment, and release signing are not automated by this workflow.

This repository uses the main branch. .gitignore excludes local environment files, dependencies/build output, credentials, logs, dumps, caches, and generated replay bulk data.

Security

See Security for implemented controls, operational requirements, and limitations.

Backup and recovery

See Backup and restore and the operator runbook.

Limitations

  • Historical backfills are synthetic approximations. Their modeled venues are near-deterministic clones rather than faithful historical venue books, so they are unsuitable evidence of cross-venue edge.
  • Synthetic and captured snapshots can lack enough depth for capacity testing. The capacity-adjusted metric therefore frequently returns NULL instead of inventing prices beyond observed levels.
  • Execution is paper trading only. No exchange orders are submitted, and simulated fills do not model queue position, exchange acknowledgement/rejection, real inventory, custody, withdrawals, or full end-to-end latency.
  • The clean TRENDING split is small: 7 comparable front-loaded orders and 5 comparable back-loaded orders. At the tested sample sizes, no economically meaningful, tradeable edge was found in regime-aware timing or venue selection.
  • SHA-256 receipt verification is tamper evidence for embedded canonical evidence only. There is no signing identity, trusted timestamp, key management, transparency log, or external anchor; supported claims are bounded to retained observed evidence, and unavailable claims remain null.
  • The system is single-host and has no replicas, failover, zero-downtime migration mechanism, automated certificate lifecycle, external monitoring/alerting/tracing, SIEM, or production SLO evidence.
  • The live verification covered repeated two-user WebSocket isolation and sequential idempotency/funds checks, but not true simultaneous multi-process double-spend stress. The C++ tamper test passed; a live receipt-verification audit event was not observed in the final integration run.
  • A disposable migration/backup/restore rehearsal passed before the final migration-script improvement; Compose and shell/config checks were rerun afterward, but the complete recovery rehearsal was not repeated after that edit.
  • This documentation and test evidence are not a security audit, regulatory review, disaster-recovery certification, performance capacity study, or production certification.

About

RegimeRoute is a paper-trading crypto router focused on proof-carrying routing resilience, not timing alpha.

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages