# KeronisEngine — Complete Documentation Source: https://engine.keronis.ai/ | Repo: https://github.com/JNeuvonen/keronisengine --- # KeronisEngine **Process all of Binance's live market data — 10,000+ messages/sec with continuous streaming state-machine features and in-process ONNX predictions — on a single ~$100 dedicated server.** KeronisEngine is an open-source C++20 trading engine designed for zero train/serve feature skew. Your strategy functions, streaming state machines, and ONNX models run across offline Parquet feature generation (`historical_feature_gen`), event-driven backtesting (`backtest_runner`), depth-based paper trading (`PaperExchange`), and live venue execution (`live_infra`). [Get Started](quickstart.md){ .md-button .md-button--primary } [Architecture](architecture.md){ .md-button } [Comparison](comparison.md){ .md-button } [GitHub Repo](https://github.com/JNeuvonen/keronisengine){ .md-button } --- ## Core Dataflow ```mermaid flowchart LR MD["Market Data
(Parquet / Live WS, 10k+ msg/s)"] --> BOOK["RingBufferBook
(16B slots, bitmap + ctzll)"] MD --> SM["Streaming State Machines
(KERONIS_REGISTER_STATE_MACHINE)"] SM --> ONNX["ONNX Runtime
In-Process Inference"] BOOK --> ENG["Core::Engine
(Inventory, Risk, QuoteHolds)"] ONNX --> STRAT["Strategies
(KERONIS_REGISTER_STRATEGY)"] ENG --> STRAT STRAT --> BT["BacktestState
(Event Replay)"] STRAT --> PAPER["PaperExchange
(Taker/Maker Depth Fills)"] STRAT --> LIVE["Live Venues
(Hyperliquid, Aster, Polymarket)"] ``` ## What Makes It Different - **Built for full-exchange throughput on commodity hardware:** `RingBufferBook` uses flat tick-indexed 16-byte POD slots, an occupancy bitmap with `__builtin_ctzll` depth walks, and lazy OS page commitment—benchmarking at **~1.5 ns/op** for `apply_bid` on an Intel Core Ultra 9 285K under strict IEEE-754 flags (`-fno-fast-math -ffp-contract=off -frounding-math`). - **Zero train/serve feature skew:** Write a streaming `StrategyStateMachine` once in C++20; run it in `historical_feature_gen` to emit Parquet training panels, then run the exact same machine in `backtest_runner` and `live_infra` feeding in-process ONNX Runtime inference. - **Realistic execution & crash-safe live controls:** `PaperExchange` judges orders as taker at `ack + latency` and fills resting remainders against quotes and subsequent prints; `BacktestState` tracks Polymarket queue-position notional; and `QuoteHolds` persists quote pulls across engine restarts with a `quote_guard` staleness heartbeat. - **Zero-fork extensibility:** Register external strategies and state machines with `-DKERONIS_STRATEGY_DIRS=...`—the engine never needs editing. - **High-precision MPFR arithmetic:** Order quantities, fees, and realized PnL use a clean-room Apache-2.0 `mpreal` wrapper over dynamically linked MPFR/GMP. ## Supported Venues | Venue | Market Data | Order Execution | Notes | |---|---|---|---| | **Hyperliquid** | Native WebSocket | Native (Rust signer) | Mainnet & testnet (`HYPERLIQUID_USE_TESTNET=1`) | | **Aster** | Native WebSocket | Native | Mainnet & testnet (`ASTER_USE_TESTNET=1`) | | **Polymarket** | Native CLOB WS | Native | Queue-position notional modeling in `BacktestState` | | **Lighter** | Native REST + L2 WS | `PaperExchange` | Nonce-validated `LighterOrderBook` & `DepthHistory` | | **Binance / Bybit / Others** | Native / Parquet | External proxy (`CCXT_PROXY_BASE_URL`) | Proxy not bundled in this repo | ## 60-Second Quickstart ```bash docker run --rm ghcr.io/jneuvonen/keronisengine:latest \ ./examples/quickstart_backtest/run.sh /src/build/bin/backtest_runner ``` !!! warning "Risk Disclaimer" KeronisEngine is Apache-2.0 licensed software provided **as-is** with no warranty. Always validate strategies in `backtest_runner` and `PaperExchange` before connecting live exchange credentials. --- # Quickstart Get KeronisEngine built, run the unit test suite, and execute your first end-to-end backtest in minutes. ## Option 1: Docker (Easiest) The repository includes a self-contained `Dockerfile` (Ubuntu 24.04 + vcpkg + Rust + ONNX Runtime): ```bash docker build -t keronisengine . # Run core engine tests docker run --rm keronisengine trading_engine_tests # Run the bundled SMA crossover backtest docker run --rm keronisengine ./examples/quickstart_backtest/run.sh /src/build/bin/backtest_runner ``` ## Option 2: Native Build (Linux) ### Prerequisites - Linux (Ubuntu 24.04 recommended; `backtest_runner` and `live_infra` target POSIX/Linux) - CMake ≥ 3.24, Ninja, C++20 compiler (GCC 13+ or Clang 17+) - [vcpkg](https://github.com/microsoft/vcpkg) - Rust toolchain (`cargo`) for `src/rust/hyperliquid_signer` - `python3` + `pyarrow` (`python3 -m venv .venv && .venv/bin/pip install pyarrow`) for generating the quickstart sample Parquet data ### Build ```bash export VCPKG_ROOT=/path/to/vcpkg ORT=$(./scripts/fetch_onnxruntime.sh) cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \ -DONNXRUNTIME_ROOT="$ORT" cmake --build build -j"$(nproc)" ``` This produces four binaries under `build/bin/`: | Binary | Purpose | |---|---| | `backtest_runner` | Event-driven historical replay | | `live_infra` | Live and paper trading runtime | | `historical_feature_gen` | Offline state-machine feature generation | | `export_strategy_config` | Export a live DB strategy row to backtest `config.json` | ### Run Tests ```bash # Core trading engine suite ./build/bin/trading_engine_tests # Offline live_infra unit tests (PaperExchange, quote holds, Lighter book, etc.) ./build/bin/live_infra_tests "[paper_exchange],[paper_trading],[quote_holds],[normalized_trade],[lighter_market_data],[ohlcv]" ``` ### Run the Quickstart Backtest `examples/quickstart_backtest/run.sh` generates 6 hours of synthetic 1-minute `BTCUSDT` Parquet bars and runs the bundled `sma_crossover` strategy through `backtest_runner`: ```bash ./examples/quickstart_backtest/run.sh ./build/bin/backtest_runner ``` Expected output includes periodic NAV/PnL snapshots and a final summary similar to: ```text [BACKTEST 2026-01-01 05:59:59.999UTC] NAV: 100084 | PnL: +79.7 | Fees: 2.5 | MaxDD: 0.00% | Trades: 6 (W:5 L:1 83%) | ... ``` ## Next Steps - Understand the [Architecture](architecture.md) - Write your own strategy in [Writing a Strategy](strategies.md) - Spin up Postgres + NATS for [Live & Paper Trading](live-and-paper.md) --- # Architecture KeronisEngine separates **market data & feature computation**, **core strategy & order/risk state**, and **venue execution** so the same strategy binary runs identically in simulation and production. ## High-Level Components ```mermaid graph TD subgraph MarketData ["market_data"] STREAMS["WebSocket & Parquet Readers"] BOOKS["OrderBook / LighterOrderBook / DepthHistory"] DISP["StateMachineDispatcher"] SM["StrategyStateMachine (registered)"] end subgraph Engine ["trading_engine"] CORE["Core::Engine (Singleton)"] STRAT["Core::Strategy (registered)"] TICK["Core::TradeTicker (per symbol)"] BT["Core::BacktestState"] end subgraph Live ["live_infra"] UPD["Live::StateUpdater"] PAPER["Live::PaperExchange"] EXCH["Native Clients (Hyperliquid, Aster, Polymarket)"] ECS["engine_control_server (HTTP)"] end STREAMS --> BOOKS --> CORE STREAMS --> DISP --> SM --> CORE CORE --> STRAT --> TICK TICK --> BT TICK --> PAPER TICK --> EXCH UPD --> CORE ECS --> CORE ``` ## Package Breakdown ### `trading_engine` - **`Core::Engine`**: Central coordinator owning active strategies, per-venue order books, BBA/price caches, inventory, exchange symbol metadata, and the simulation or wall-clock timer. - **`Core::Strategy`**: Holds strategy configuration (`StrategyConfig`), risk caps, virtual balance, pause state (`stop_making_markets`), quote-pull state (`quotes_pulled`), and per-symbol `TradeTicker` instances. - **`Core::TradeTicker`**: Manages open orders, removed/late-fill orders, open trades, and order construction (`construct_order`) with pre-trade risk and rate-limit validation. - **`Core::BacktestState`**: Deterministic event-loop simulator reading Arrow/Parquet bars, trades, and order-book data, simulating latency, fees, leverage, and fills. - **`Core::StrategyRegistry`**: Static self-registration table (`KERONIS_REGISTER_STRATEGY`). Binaries link `keronis_engine` with `WHOLE_ARCHIVE` so registered strategies are never stripped by the linker. ### `market_data` - **`OhlcvDataset` & `DatasetsManager`**: Partitioned Arrow/Parquet bar storage (`parquets/year=*/month=*/day=*/.parquet`). - **`StrategyStateMachine` & `StateMachineDispatcher`**: Streaming feature engines that update on every trade/bar/book event and expose point-in-time feature vectors to strategies and ONNX models. - **`LighterOrderBook` & `DepthHistory`**: Nonce-validated L2 book maintenance and historical depth lookup (also used by `PaperExchange`). ### `live_infra` - **`Live::StateUpdater`**: Syncs strategies, accounts, exchange info, inventory snapshots, and open trades with PostgreSQL and venues, and enforces quote holds (`quote_holds.h`) and graceful `SIGTERM` shutdown. - **`Live::PaperExchange`**: Dedicated paper-trading venue that evaluates paper orders against live/recorded market depth with configurable latency and slippage. - **Native exchange clients**: Direct REST/WebSocket and order signing for Hyperliquid (via `src/rust/hyperliquid_signer`), Aster, and Polymarket. ### `historical_feature_gen` - Replays historical datasets through any registered `StrategyStateMachine` using `MergeIterator` to emit Parquet training panels with guaranteed train/serve feature parity. ### `engine_control_server` - Embedded HTTP server (`cpp-httplib`) exposing read-only engine introspection (`/control/health`, `/control/engine/orders`, `/control/engine/inventory`, etc.) and optional gated mutations. ## Numeric Determinism & Design Notes - All targets compile with `-fno-fast-math -fno-strict-aliasing -ffp-contract=off -frounding-math`. - Order quantities, prices, fees, and realized PnL use `mpfr::mpreal` (a clean-room Apache-2.0 wrapper in `src/cpp/packages/common/include/mpreal.h` over dynamically linked MPFR/GMP arbitrary-precision binary floating point). - **`Core::Engine` singleton:** One engine instance per process keeps hot-path callbacks lightweight and matches the single-process-per-host live deployment model; unit tests reset state explicitly between cases. - **Header layout:** Headers for the `trading_engine` package live under `include/market_making/` for historical continuity across all strategy and live callers. --- # Comparison: KeronisEngine vs. NautilusTrader vs. HFTBacktest Every serious trading framework makes deliberate architectural tradeoffs. Here is an honest look at where KeronisEngine fits and where other tools may be a better choice. | Dimension | **KeronisEngine** | **NautilusTrader** | **HFTBacktest** | |---|---|---|---| | **Core language** | C++20 (+ Rust signer for Hyperliquid) | Rust core + Python/Cython API | Rust + Python (Numba) | | **Primary sweet spot** | Full-exchange crypto feeds (10k+ msg/s on a single commodity server) with streaming state-machine features & in-process ONNX inference | Broad multi-asset ecosystem with Python strategy ergonomics | Ultra-faithful L3 tick/queue-position research and latency modeling | | **Strategy authoring** | Native C++20 functions registered via `KERONIS_REGISTER_STRATEGY` (no fork needed) | Python or Rust | Python (Numba) or Rust | | **Feature & ML pipeline** | Built-in C++ `StrategyStateMachine`s shared across `historical_feature_gen`, `backtest_runner`, and `live_infra` + in-process ONNX Runtime | External / user-managed | External / user-managed | | **Order book data structure** | `RingBufferBook`: tick-indexed 16-byte slots, occupancy bitmap + `__builtin_ctzll` walks, lazy OS page commitment | Tree/level-based | HashMap / BTree / tick arrays | | **Queue-position modeling** | Supported for Polymarket (`order_queue_notional_accumulated`); CEX backtests model depth/latency/price-through rather than full L3 queue priority | L2/L3 fill models | Full L3 queue-position modeling (primary focus) | | **Paper trading** | Built-in `PaperExchange` (taker at ack + latency, maker against resting quote + subsequent trades, cancels stop later prints) | Simulated / sandbox adapters | Backtest-focused + live connectors | | **Native live venues** | Hyperliquid (Rust signer), Aster, Polymarket; Lighter L2 market data; other venues via external proxy | Binance, Bybit, OKX, Interactive Brokers, Polymarket, etc. | Binance Futures, Bybit | | **Operational safety** | Durable `QuoteHolds` (survives restart + stale `quote_guard` heartbeat), localhost HTTP control server, graceful `SIGTERM` quote pull | Risk engine & execution controls | Connector-dependent | ## When to Pick KeronisEngine - You want to ingest **an entire exchange's live market data** (10,000+ msg/s) on a single ~$100 dedicated box while computing streaming features and running continuous ONNX inference in the same C++ process. - You care deeply about **zero train/serve feature skew**—running the exact same C++ state-machine code in offline Parquet feature generation (`historical_feature_gen`), backtesting, and live trading. - You want **crash-resilient live operations** (durable quote holds, localhost HTTP introspection, high-precision MPFR accounting) without writing a C++ engine from scratch. ## When to Pick Something Else - **Pick NautilusTrader** if you want to write strategies in Python and want turnkey adapters for a wide catalog of traditional and crypto brokers out of the box. - **Pick HFTBacktest** if your primary edge depends on strict L3 order-queue-position simulation on CEX order books and you prefer Numba/Rust research notebooks. --- # Writing a Strategy Strategies self-register by name with `KERONIS_REGISTER_STRATEGY`. You do **not** need to edit any engine source file to add a strategy. ## External Strategy Directories Keep your strategies in your own private repository and point CMake at them: ```bash cmake -S . -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \ -DONNXRUNTIME_ROOT="$ORT" \ -DKERONIS_STRATEGY_DIRS="/path/to/my_strategies;/path/to/my_state_machines" cmake --build build -j"$(nproc)" ``` Every `.cpp` under `KERONIS_STRATEGY_DIRS` is compiled into `keronis_engine` and linked with `WHOLE_ARCHIVE` into `backtest_runner`, `live_infra`, and `historical_feature_gen`. ## Anatomy of a Strategy See [`src/cpp/packages/strategies/sma_crossover/sma_crossover.cpp`](https://github.com/JNeuvonen/keronisengine/blob/main/src/cpp/packages/strategies/sma_crossover/sma_crossover.cpp) for a complete runnable strategy. The key hooks are: ```cpp #include "market_making/strategy_registry.h" #include "market_making/engine.h" #include "market_making/strategy.h" #include "market_making/ticker.h" namespace { std::vector on_market_event( Core::Engine& engine, Core::Strategy& strategy, std::optional event) { std::vector decisions; const long long now_ms = engine.get_time(); for (auto& [symbol, ticker_ptr] : strategy.trade_tickers) { std::lock_guard lock(ticker_ptr->trading_mutex); if (!ticker_ptr->get_orders(false).empty()) continue; const auto& em = ticker_ptr->exchange_and_markets.front(); const auto price = engine.get_price(symbol, em.exchange_name, em.market_type); if (!price.has_value()) continue; // Build Core::CreateOrderParams, call ticker_ptr->construct_order(...), // then ticker_ptr->mark_order_to_be_created(engine, order, decision, strategy). } return decisions; } void bind_my_strategy(Core::Strategy& strategy) { strategy.strategy_callback = on_market_event; strategy.compute_predictions_callback = [](Core::Engine&, Core::Strategy&) {}; } } // namespace KERONIS_REGISTER_STRATEGY("my_strategy", bind_my_strategy); ``` ## Key Conventions - **Locking:** Always lock `ticker_ptr->trading_mutex` before inspecting `get_orders(false)` / `get_trades(false)` or calling `construct_order`. - **Order construction:** Always go through `ticker_ptr->construct_order(engine, strategy, params)` so pre-trade risk limits, order-rate caps, reduce-only checks, and quote-pull gates are enforced consistently. - **Quote holds (`quotes_pulled`):** When `strategy.quotes_pulled` is set (via `PULL_SIGNAL`, `GUARD_STALE`, or `SHUTDOWN`), resting `LIMIT` / `LIMIT_MAKER` entry orders are refused and existing resting entries are swept/canceled, while close orders and `IOC`/`FOK`/`MARKET` orders remain allowed. - **Bundled reference strategies:** - `sma_crossover` — bar-driven moving average crossover (used by the quickstart backtest) - `test_quoter` — resting limit bid quoting against BBA - `test_taker` — market taker flow against BBA - `test_market_maker` — two-sided post-only quoting around BBA - `discretionary` — command-driven discretionary execution with stops and take-profits --- # State Machines & ONNX Inference To eliminate train/serve skew, KeronisEngine computes streaming features inside C++ `MarketData::StrategyStateMachine` classes that run identically in: 1. `historical_feature_gen` (offline training panel generation) 2. `backtest_runner` (historical strategy replay) 3. `live_infra` (live and paper trading) ## Registering a State Machine Subclass `MarketData::StrategyStateMachine`, implement its required virtual methods (`initialize_symbol_states`, `react_impl`, `emit_state_impl`), and register the type with `KERONIS_REGISTER_STATE_MACHINE(name, Type)`: ```cpp #include "market_data/state_machine_registry.h" #include "market_data/strategy_state_machine.h" namespace { class MyFeatureSM : public MarketData::StrategyStateMachine { public: std::string get_name() const override { return "my_features"; } std::vector feature_names() const override { return {"last_price"}; } void initialize_symbol_states() override { last_price_ = 0.0f; } protected: void react_impl(const MarketData::MarketEvent& event) override { if (event.type == MarketData::MarketEvent::Type::TRADE && event.trade.has_value()) { last_price_ = static_cast(event.trade->price); } } std::optional> emit_state_impl() const override { if (last_price_ <= 0.0f) return std::nullopt; return std::vector{last_price_}; } private: float last_price_ = 0.0f; }; } // namespace KERONIS_REGISTER_STATE_MACHINE("my_features", MyFeatureSM); ``` See the bundled state machines under `src/cpp/packages/historical_feature_gen/src/transformations/` (`spread_sm.cpp`, `taker_flow_sm.cpp`, `windowed_taker_flow_sm.cpp`, `bba_imbalance_ratio_sm.cpp`, `global_bba_sm.cpp`, `six_venue_order_sm.cpp`, `polymarket_trade_flow_sm.cpp`) for complete examples. ## Lifecycle Hooks `MarketData::StrategyStateMachine` provides hooks for live resilience: - `on_trade_stream_disconnected(symbol, exchange_name, market_type)` — invoked by the stream health monitor when a trade feed drops. - `run_background_work()` — called approximately once per second from the syncer thread for slow work (such as REST catch-up) that must not block the event dispatcher. ## ONNX Model Inference `common/include/onnx_model.h` wraps ONNX Runtime C++ sessions for low-latency in-process inference: - Export your trained model (LightGBM, XGBoost, PyTorch, etc.) to `.onnx`. - Configure `models` or `model_schedule_path` on your `StrategyConfig`. - Score the feature vector produced by your `StrategyStateMachine` inside `compute_predictions_callback` or `on_market_event`. --- # Live & Paper Trading `live_infra` is the runtime process for both **paper trading** (`PaperExchange`) and **live venue execution**. ## 1. Start PostgreSQL and NATS The `deploy/` directory provides a local Docker Compose stack (bound to `127.0.0.1`) that initializes PostgreSQL with [`deploy/schema.sql`](https://github.com/JNeuvonen/keronisengine/blob/main/deploy/schema.sql) and seeds a paper account + `test_quoter` strategy (`version = '2.0'`, `backtest_json_format_version = '3.0'`) via [`deploy/seed_paper_strategy.sql`](https://github.com/JNeuvonen/keronisengine/blob/main/deploy/seed_paper_strategy.sql): ```bash cd deploy cp .env.example .env docker compose up -d ``` Verify Postgres and NATS are running: ```bash docker compose ps ``` ## 2. Configure Venue Credentials Copy `deploy/accounts.example.json` to `deploy/accounts.json` and edit it: ```bash cp deploy/accounts.example.json deploy/accounts.json ``` ```json { "hyperliquid_futures_accounts": [ { "account_id": 1, "access": "0xYOUR_WALLET_ADDRESS", "secret": "0xYOUR_PRIVATE_KEY" } ], "aster_futures_accounts": [], "polymarket_accounts": [] } ``` Restrict file permissions: ```bash chmod 600 deploy/accounts.json ``` ## 3. Run `live_infra` Load your `.env` (including the required `NATS_TOKEN`) and start with `IS_ORDER_CREATION_DISABLED=1` first to verify market data, database sync, and the HTTP control server: ```bash set -a source deploy/.env set +a mkdir -p "$DATA_DIR_ROOT" ./build/bin/live_infra ``` Check health via the control server: ```bash curl -s http://127.0.0.1:8090/control/health | jq . ``` ## Paper Trading (`PaperExchange`) When a strategy has `is_paper_trading = true` (or its account has `account_type = 'paper'`), orders are routed to `Live::PaperExchange` instead of the live venue: - Orders are evaluated on a dedicated thread against live/recorded market depth with simulated ack latency and configurable slippage (`PAPER_SLIPPAGE_BPS`, default `3`). - Paper trades are labeled as paper in the database and can transition cleanly to live without colliding with live inventory. ## Direct Signing, `IS_PROD`, and Proxy Notes - **Direct signing flags:** `HYPERLIQUID_DIRECT_SIGNING`, `ASTER_DIRECT_SIGNING`, and `POLYMARKET_DIRECT_SIGNING` are **enabled by default** (`1`). Set `HYPERLIQUID_USE_TESTNET=1` / `ASTER_USE_TESTNET=1` to target testnets (leaving them unset targets mainnet). - **Credential lookup (pre-release limitation):** Direct-signing order submission currently still fetches account credentials through `CCXT_PROXY_BASE_URL` (`ccxt_proxy.cpp`), which is not bundled in this repository. Paper trading (`PaperExchange`) does not require live venue signing. - **`IS_PROD` and `quote_guard`:** Setting `IS_PROD=1` enforces a fresh `quote_guard` heartbeat in PostgreSQL's `engine_health` table (`engine_instance = 'quote_guard'`) on all non-paper strategies; without a heartbeat writer, `live_infra` pulls resting quotes (`QuotesPullReason::GUARD_STALE`). Keep `IS_PROD=0` (or unset) for local paper runs. - **Other venues (Binance, Bybit, etc.):** Require an external HTTP/WS execution proxy configured via `CCXT_PROXY_BASE_URL` and `CCXT_PROXY_USER_DATA_WS_URL`. ## Graceful Shutdown Sending `SIGTERM` once requests a clean shutdown: `live_infra` pulls resting entry quotes (`QuotesPullReason::SHUTDOWN`) and exits cleanly after the main loop drains. A second `SIGTERM` exits immediately. --- # Engine Control Server API When `ENABLE_ENGINE_CONTROL_SERVER=1` is set, `live_infra` starts an embedded HTTP server (default `127.0.0.1:8090`) for live introspection and optional operational control. !!! danger "Security" Keep `ENGINE_CONTROL_SERVER_BIND=127.0.0.1` and `ENABLE_ENGINE_CONTROL_MUTATIONS=0` in production unless exposed strictly behind an authenticated internal network. ## Read Endpoints (`GET`) | Endpoint | Description | |---|---| | `/control/health` | Engine uptime, readiness, and whether mutations are enabled | | `/control/engine/strategies` | Loaded strategies, pause state, and quote-pull status | | `/control/engine/strategy-telemetry` | Per-strategy runtime telemetry and order-rate counters | | `/control/engine/orders` | Active orders (supports query filtering) | | `/control/engine/orders/unacked` | Orders awaiting venue acknowledgment | | `/control/engine/orders/failed-cancels` | Cancel requests that failed | | `/control/engine/trades` | Open and active trades | | `/control/engine/exposure` | Aggregate and per-symbol directional exposure | | `/control/engine/inventory` | Per-account venue inventory | | `/control/engine/full-account-state` | Combined account balances, inventory, and open orders | | `/control/engine/bba` | Current best bid/ask for a symbol/venue | | `/control/engine/orderbook` | Current L2 order book snapshot | | `/control/engine/price` | Latest cached mark/last price | | `/control/engine/spread` | Current bid/ask spread | | `/control/engine/state-snapshot` | Full engine state snapshot | | `/control/engine/orderbooks-out-of-sync` | Books currently flagged out-of-sync | | `/control/engine/counters` | Internal engine counters | | `/control/engine/markouts/pending` | Pending fill markout trackers | | `/control/engine/exchange-info` | Loaded symbol precision and tick/lot rules | | `/control/engine/time` | Current engine timestamp (ms) | ## Mutating Endpoints (`POST`) Mutating endpoints return `403` unless `ENABLE_ENGINE_CONTROL_MUTATIONS=1` is set. They are primarily used for integration testing, scenario replay, and controlled incident operations: - **Order lifecycle injection:** `/control/engine/orders/created-ack`, `/control/engine/orders/filled-ack`, `/control/engine/orders/canceled-ack`, `/control/engine/orders/update` - **Market data injection:** `/control/engine/bba`, `/control/engine/price`, `/control/engine/orderbook/init`, `/control/engine/orderbook/full-refresh`, `/control/engine/orderbook/update` --- # Configuration & Environment Variables ## Environment Variables (`live_infra`) ### Required | Variable | Description | |---|---| | `DATA_DIR_ROOT` | Root directory for market data, caches, and state-machine persistence | | `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD` | PostgreSQL connection parameters | | `ACCOUNTS_FILE` | Path to JSON file mapping `account_id` to venue credentials | | `NATS_TOKEN` | Required NATS authentication token (`live_infra` exits if unset) | ### Optional / Runtime Switches | Variable | Default | Description | |---|---|---| | `NATS_URL` | `nats://localhost:4222` | NATS server URL | | `IS_PROD` | *(unset / 0)* | Production flag; when `1`, non-paper strategies require a fresh `quote_guard` heartbeat in `engine_health` (`engine_instance = 'quote_guard'`) | | `IS_ORDER_CREATION_DISABLED` | `0` | Set to `1` to block all live order submissions | | `PAPER_SLIPPAGE_BPS` | `3` | Slippage (bps) applied by `PaperExchange` | | `HYPERLIQUID_DIRECT_SIGNING` | `1` | Native Rust Hyperliquid signing (enabled by default; set `0` to disable) | | `HYPERLIQUID_USE_TESTNET` | `0` | Route Hyperliquid client to testnet (unset/`0` = mainnet) | | `ASTER_DIRECT_SIGNING` | `1` | Native Aster signing (enabled by default; set `0` to disable) | | `ASTER_USE_TESTNET` | `0` | Route Aster client to testnet (unset/`0` = mainnet) | | `POLYMARKET_DIRECT_SIGNING` | `1` | Native Polymarket CLOB signing (enabled by default; set `0` to disable) | | `ENABLE_ENGINE_CONTROL_SERVER` | `0` | Enable HTTP control/introspection server | | `ENGINE_CONTROL_SERVER_BIND` | `127.0.0.1` | Bind address for control server | | `ENGINE_CONTROL_SERVER_PORT` | `8090` | Listen port for control server | | `ENABLE_ENGINE_CONTROL_MUTATIONS` | `0` | Allow `POST` mutation endpoints on control server | | `LOG_DIRECTORY` | *(unset)* | Rotating disk log directory (when built with `-DKERONIS_DISK_LOGGING=ON`) | | `CCXT_PROXY_BASE_URL` | *(unset)* | External proxy base URL (used for non-native venues and proxy credential lookups) | | `CCXT_PROXY_USER_DATA_WS_URL` | `ws://localhost:8040/api/v1/user-data/stream` | External proxy user-data WebSocket | ## Environment Variables (`export_strategy_config`) | Variable | Description | |---|---| | `DB_CONNECTION_STR` | libpq connection string used by `export_strategy_config` to read strategy rows from PostgreSQL | ## Backtest Config (`config.json`) `backtest_runner` takes a single JSON file (`./build/bin/backtest_runner /path/to/config.json`) and never reads PostgreSQL. Key top-level sections: - **`strategies`**: Array of `StrategyConfig` objects (including `strategy_name`, `exchanges_list`, `trade_tickers`, `models`, risk caps, and order-rate limits). Use `export_strategy_config` to dump a live DB strategy into this format. - **`market_data`**: Paths to Parquet datasets (`ohlcv_klines`, `trades`, `aggr_trades`, `order_book_snapshots`, `order_book_updates`, `predictions`). - **`exchanges`**: Fee schedules (`maker_fee_rate`, `taker_fee_rate`, `maker_rebate_rate`) and initial quote-asset balances per `account_id`. - **`simulation_start_date_ms` / `simulation_end_date_ms`**: Replay window in UTC epoch milliseconds. - **`market_data_replay`**: `load_mode` (`"eager"` or `"streaming"`), `chunk_duration_ms`, and `reader_threads`. See [`examples/quickstart_backtest/generate_sample_data.py`](https://github.com/JNeuvonen/keronisengine/blob/main/examples/quickstart_backtest/generate_sample_data.py) for a complete, working `config.json` generator.