# chrislernunes/oraculus architecture

> Architecture diagram of the GitHub repository chrislernunes/oraculus, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-07). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/chrislernunes/oraculus
- Repository: https://github.com/chrislernunes/oraculus

## Overview

1. **Overall shape**
   - This repo is a **single-process paper-trading service** with two major runtime parts: a **Flask web server** for the dashboard/API and an **async arbitrage engine** running in a background thread.
   - The engine scans Polymarket binary markets, generates signals, sizes paper trades, and writes state for the UI to read.

2. **Runtime boundary**
   - `app.py` is the web-entry boundary: it starts Flask and launches the engine thread in the same process.
   - There is no separate backend service, no queue, and no database. The main integration point between the engine and the UI is a **JSON file in `/tmp/oraculus_state.json`**.

3. **Engine subsystem**
   - `engine.py` is the core trading system.
   - It contains the asynchronous scan loop, market-data refresh, crypto-price polling, strategy evaluation, signal deduping/ranking, Kelly sizing, and paper-account updates.
   - The engine appears to own the “business logic” boundary; the web layer is deliberately thin.

4. **Market data ingestion**
   - The engine pulls **binary market metadata** from **Polymarket Gamma** and **orderbook/depth data** from the **Polymarket CLOB API**.
   - It constructs per-market `MarketData` objects with YES/NO bid-ask and depth, which become the input to all strategies.
   - Market refresh is periodic and slower than the main scan loop, so strategies operate on cached market snapshots between refreshes.

5. **External price feed**
   - A separate crypto feed polls **CoinGecko** for BTC, ETH, and SOL spot prices.
   - Those prices are used only by the `DEP_GRAPH` strategy’s latency/move detection; this is the only non-Polymarket external signal source.

6. **Strategy layer**
   - The engine runs **three independent arbitrage strategies** in parallel:
     - `SPREAD_FADE`
     - `CROSS_MARKET`
     - `DEP_GRAPH`
   - Each strategy scans the same market snapshot but uses different structural relationships:
     - local YES/NO quote consistency,
     - cross-market mutual exclusivity,
     - and dependency/price-ladder plus crypto-lag signals.
   - Strategies emit normalized signals with fields like strategy, outcome, price, edge, size, and reason.

7. **Execution and risk sizing**
   - Signals are **deduplicated, ranked by edge, filtered against existing positions**, and only the top signals are executed each cycle.
   - Position sizing is done via **fractional Kelly**, capped by config limits and a hard per-bet maximum.
   - The execution model is explicitly **paper-only** via a `PaperAccount`; the README says there is no live wallet or real-money execution.

8. **State and data flow to the UI**
   - After each scan cycle, the engine writes a snapshot to `/tmp/oraculus_state.json`.
   - The dashboard reads that state through Flask’s `/api/state` endpoint.
   - The browser polls the API every couple of seconds, so the UI is effectively a **read-only observer** of engine state.

9. **Presentation layer**
   - The dashboard is a single-page HTML app, represented by `index.html` and `templates/index.html`.
   - It renders NAV, scan metrics, signals, trade history, positions, market scanner data, and charts from the state payload.
   - The frontend does not compute trading logic; it visualizes engine output.

10. **Configuration boundary**
    - `config.py` centralizes all tunable runtime constants: balance, Kelly cap, edge thresholds, minimum depth, fee assumptions, scan interval, refresh cadence, and CoinGecko polling interval.
    - This makes the system’s behavior largely driven by a single config source shared by the engine and any tests/backtests.

11. **Deployment/runtime tooling**
    - `Procfile` and `start.sh` indicate the app is intended to run as a hosted web service, specifically called out as **Render-deployable** in the README.
    - `requirements.txt` implies a Python runtime with Flask, aiohttp, and gunicorn-style deployment components.

12. **Research/backtest artifacts**
    - `oraculus_paper.pdf` is a non-runtime research artifact.
    - The README references backtesting and strategy tests, but those files are not present in the tree shown; the production architecture is still clear: **engine + file-backed state + Flask dashboard**.

13. **Important architectural constraint**
    - The system is intentionally simple and stateless at the infrastructure level, but the trade-off is that **persistence is file-based and ephemeral**.
    - That means the key diagram boundaries are:
      - external market feeds in,
      - async engine processing,
      - local JSON state out,
      - Flask/UI read-only on top.

Main entry points: [`engine.py`](https://github.com/chrislernunes/oraculus/blob/main/engine.py) (engine.py), [`app.py`](https://github.com/chrislernunes/oraculus/blob/main/app.py) (app.py), [`templates/index.html`](https://github.com/chrislernunes/oraculus/blob/main/templates/index.html) (Dashboard), [`Procfile`](https://github.com/chrislernunes/oraculus/tree/main/Procfile) (Procfile)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime"]
  node_app_py["app.py<br/>web entry<br/>[app.py]"]
  node_engine_py["engine.py<br/>arbitrage engine<br/>[engine.py]"]
  node_state_file[("State file<br/>json snapshot")]
end

subgraph group_market["Market Data"]
  node_market_cache[("Market cache<br/>market snapshots")]
  node_polymarket_gamma["Gamma API<br/>market metadata"]
  node_polymarket_clob["CLOB API<br/>orderbook feed"]
  node_coingecko["CoinGecko<br/>crypto feed"]
end

subgraph group_strategy["Strategy"]
  node_signal_ranker["Signal ranker<br/>filtering"]
  node_spread_fade{{"Spread Fade<br/>strategy"}}
  node_cross_market{{"Cross Market<br/>strategy"}}
  node_dep_graph{{"Dep Graph<br/>strategy"}}
end

subgraph group_execution["Execution"]
  node_paper_account[("PaperAccount<br/>paper execution")]
  node_kelly_sizer["Kelly sizing<br/>risk sizing"]
end

subgraph group_ui["UI"]
  node_dashboard_html["Dashboard<br/>SPA template<br/>[index.html]"]
  node_state_api["/api/state<br/>read API"]
end

subgraph group_ops["Ops"]
  node_config_py["config.py<br/>runtime config<br/>[config.py]"]
  node_procfile["Procfile<br/>deploy entry"]
  node_start_sh["start.sh<br/>startup script<br/>[start.sh]"]
  node_requirements_txt["requirements.txt<br/>python deps<br/>[requirements.txt]"]
end

node_app_py -->|"starts"| node_engine_py
node_app_py -->|"serves"| node_state_api
node_state_api -->|"reads"| node_state_file
node_dashboard_html -->|"polls"| node_state_api
node_engine_py -->|"uses"| node_config_py
node_engine_py -->|"fetches"| node_polymarket_gamma
node_engine_py -->|"fetches"| node_polymarket_clob
node_engine_py -->|"polls"| node_coingecko
node_polymarket_gamma -->|"feeds"| node_market_cache
node_polymarket_clob -->|"feeds"| node_market_cache
node_coingecko -->|"signals"| node_dep_graph
node_market_cache -->|"inputs"| node_spread_fade
node_market_cache -->|"inputs"| node_cross_market
node_market_cache -->|"inputs"| node_dep_graph
node_spread_fade -->|"emits"| node_signal_ranker
node_cross_market -->|"emits"| node_signal_ranker
node_dep_graph -->|"emits"| node_signal_ranker
node_signal_ranker -->|"selects"| node_kelly_sizer
node_kelly_sizer -->|"executes"| node_paper_account
node_paper_account -->|"persists"| node_state_file
node_engine_py -->|"writes"| node_state_file
node_dashboard_html -.->|"renders"| node_state_file
node_procfile -->|"starts"| node_app_py
node_start_sh -->|"boots"| node_app_py
node_requirements_txt -.->|"supports"| node_app_py

click node_app_py "https://github.com/chrislernunes/oraculus/blob/main/app.py"
click node_engine_py "https://github.com/chrislernunes/oraculus/blob/main/engine.py"
click node_config_py "https://github.com/chrislernunes/oraculus/blob/main/config.py"
click node_procfile "https://github.com/chrislernunes/oraculus/tree/main/Procfile"
click node_start_sh "https://github.com/chrislernunes/oraculus/blob/main/start.sh"
click node_requirements_txt "https://github.com/chrislernunes/oraculus/blob/main/requirements.txt"
click node_dashboard_html "https://github.com/chrislernunes/oraculus/blob/main/templates/index.html"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_app_py,node_engine_py,node_state_file toneBlue
class node_market_cache,node_polymarket_gamma,node_polymarket_clob,node_coingecko toneAmber
class node_signal_ranker,node_spread_fade,node_cross_market,node_dep_graph toneMint
class node_paper_account,node_kelly_sizer toneRose
class node_dashboard_html,node_state_api toneIndigo
class node_config_py,node_procfile,node_start_sh,node_requirements_txt toneTeal
```

## Components

### Runtime

Single-process web app and background engine

- [app.py](https://github.com/chrislernunes/oraculus/blob/main/app.py): web entry · Flask entrypoint that starts the engine thread and serves the API · `app.py`
- [engine.py](https://github.com/chrislernunes/oraculus/blob/main/engine.py): arbitrage engine · Async scan loop, market refresh, strategy evaluation, sizing, and state writes · `engine.py`
- **State file**: json snapshot · Ephemeral engine snapshot at /tmp/oraculus_state.json

### Market Data

External feeds and cached inputs

- **Market cache**: market snapshots · Cached per-market metadata, quotes, and depth used by all strategies
- **Gamma API**: market metadata · Polymarket market metadata source
- **CLOB API**: orderbook feed · Polymarket orderbook and depth source
- **CoinGecko**: crypto feed · BTC, ETH, and SOL spot prices used by one strategy

### Strategy

Signal generation and ranking

- **Signal ranker**: filtering · Deduplicates signals, ranks by edge, and filters against positions
- **Spread Fade**: strategy · Checks YES/NO quote consistency inside a market
- **Cross Market**: strategy · Finds arbitrage across mutually exclusive markets
- **Dep Graph**: strategy · Uses dependency graph relationships and crypto lag signals

### Execution

Paper trading and risk sizing

- **PaperAccount**: paper execution · Virtual account that tracks positions and PnL without live trading
- **Kelly sizing**: risk sizing · Fractional Kelly position sizing with caps and bet limits

### UI

Read-only dashboard and API

- [Dashboard](https://github.com/chrislernunes/oraculus/blob/main/templates/index.html): SPA template · Single-page dashboard rendering state, signals, positions, and charts · `templates/index.html`
- **/api/state**: read API · Flask endpoint exposing the latest engine snapshot

### Ops

Runtime configuration and deployment

- [config.py](https://github.com/chrislernunes/oraculus/blob/main/config.py): runtime config · Central tuning knobs for scan cadence, thresholds, sizing, and fees · `config.py`
- [Procfile](https://github.com/chrislernunes/oraculus/tree/main/Procfile): deploy entry · Process definition for hosted deployment · `Procfile`
- [start.sh](https://github.com/chrislernunes/oraculus/blob/main/start.sh): startup script · Shell launcher for the hosted runtime · `start.sh`
- [requirements.txt](https://github.com/chrislernunes/oraculus/blob/main/requirements.txt): python deps · Runtime dependency set for Flask, async networking, and deployment · `requirements.txt`

## Connections

- app.py → engine.py: starts · Launches the async engine in a background thread
- app.py → /api/state: serves · Flask exposes the state endpoint
- /api/state → State file: reads · API returns the latest snapshot from disk
- Dashboard → /api/state: polls · Browser refreshes read-only state every few seconds
- engine.py → config.py: uses · Reads shared runtime thresholds and cadence
- engine.py → Gamma API: fetches · Loads market metadata periodically
- engine.py → CLOB API: fetches · Refreshes orderbook and depth data
- engine.py → CoinGecko: polls · Reads crypto spot prices for latency detection
- Gamma API → Market cache: feeds · Market metadata is normalized into cached snapshots
- CLOB API → Market cache: feeds · Quote and depth data populate the market cache
- CoinGecko → Dep Graph: signals · Crypto prices inform dependency/lag logic
- Market cache → Spread Fade: inputs · Strategy scans local YES/NO consistency
- Market cache → Cross Market: inputs · Strategy scans related markets for mispricing
- Market cache → Dep Graph: inputs · Strategy scans structural dependency relationships
- Spread Fade → Signal ranker: emits · Normalizes candidate arbitrage signals
- Cross Market → Signal ranker: emits · Normalizes candidate arbitrage signals
- Dep Graph → Signal ranker: emits · Normalizes candidate arbitrage signals
- Signal ranker → Kelly sizing: selects · Top-ranked signals are sized after dedupe and filters
- Kelly sizing → PaperAccount: executes · Paper-only trade updates positions and PnL
- PaperAccount → State file: persists · Engine writes the snapshot consumed by the UI
- engine.py → State file: writes · Publishes scan metrics, signals, trades, and positions
- Dashboard → State file: renders · Frontend displays the latest engine output indirectly through the API
- Procfile → app.py: starts · Deployment process launches the Flask app
- start.sh → app.py: boots · Shell startup script invokes the web process
- requirements.txt → app.py: supports · Declared dependencies enable the runtime stack
