# okeson453/ghost-grid architecture

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

- Interactive diagram: https://gitdiagram.com/okeson453/ghost-grid
- Repository: https://github.com/okeson453/ghost-grid

## Overview

#### Purpose and Entry Points
GHOST GRID is a Python 3.11+ MT5 FX scalping system for paper/live deployment on a Windows VPS. It ingests MT5 market events, builds multi-timeframe market state, scores trade confluence, gates/risk-checks orders, manages positions, and enforces portfolio-level emergency exits.

Primary runtime entry point: `main.py`. Operational entry points include `scripts/start.py`, `scripts/backtest_run.py`, and database migration runner `scripts/migrate_db.py`. MT5 hosts the companion Expert Advisor: `mt5_ea/GhostGrid.mq5`.

#### MT5 Bridge and Market-Data Pipeline
The MT5 EA communicates with Python through Windows Named Pipes. Python-side bridge components handle protocol framing, reads/writes, health, and reconnect behavior: `bridge/pipe_client.py`, `bridge/reader.py`, `bridge/protocol.py`, `bridge/writer.py`.

Incoming ticks are routed into OHLCV aggregation and immutable market snapshots. The data boundary is represented by schemas/snapshots before strategy logic consumes it: `data/feed_router.py`, `data/aggregator.py`, `data/snapshot_builder.py`, `data/schema.py`. Derived inputs include ATR, VWAP, CVD, and regime data in `data/atr.py`, `data/vwap.py`, and `data/cvd_engine.py`.

#### Regime and Confluence Scoring
Market regime classification provides context for decisions through `regime/classifier.py`, `regime/fingerprint.py`, and `regime/session.py`.

Three independent engines score a snapshot: HMP market structure (`scoring/hmp/engine.py`), HLCP liquidity/trend confluence (`scoring/hlcp/engine.py`), and MPP order-flow/projection inputs (`scoring/mpp/engine.py`). `scoring/fusion.py` combines these into the H_c composite, while `scoring/gate.py` applies hysteresis and produces actionable versus rejected/watch-only decisions. Score models form the contract between strategy and execution: `scoring/models.py`.

#### Risk, Execution, and Position Lifecycle
Approved signals cross a pre-trade risk boundary: `risk/governor.py`, `risk/validator.py`, and `risk/sizer.py` determine whether and how much may be traded. Risk constants/settings are centralized under `config/constants.py` and `config/settings.py`.

`execution/commander.py` converts approved actions into MT5 order/close commands through `execution/dispatcher.py`; `execution/paper.py` supplies paper-mode behavior and `execution/fill_handler.py` handles confirmations. Positions are registered and progressed through explicit lifecycle/exit logic in `positions/registry.py`, `positions/state_machine.py`, and `positions/exit_engine.py`, including trailing and CVD-based exits.

#### Portfolio Guardian and Emergency Controls
Portfolio state aggregates equity, PnL, correlation, and operating mode: `portfolio/state.py`, `portfolio/ledger.py`, `portfolio/equity_tracker.py`, `portfolio/mode_automaton.py`. This state feeds both trading permissions and safety systems.

The nuclear guardian polls portfolio conditions, identifies trigger conditions, concurrently closes positions, and imposes cooldown/day-halt behavior: `nuclear/controller.py`, `nuclear/triggers.py`, `nuclear/executor.py`, `nuclear/cooldown.py`. Separately, the watchdog is an OS thread intended to remain independent of the asyncio control loop and can directly issue emergency pipe commands: `watchdog/thread.py`, `watchdog/emergency.py`.

#### Persistence, Control Plane, and Observability
SQLite is the durable event/state boundary, managed by `db/connection.py`, `db/writer.py`, `db/reader.py`, with schema evolution in `db/migrations/001_initial_schema.sql`. Runtime artifacts are stored under `data_store/`.

Telegram is an external operator-control service, connected at orchestration level via `telegram/bot.py`, `telegram/commands.py`, and `telegram/alerts.py`; it supports status, pause/resume, position listing, and manual nuclear actions. Monitoring writes metrics/trade journals and evaluates drift through `observability/metrics.py`, `observability/trade_journal.py`, and `observability/drift_detector.py`.

#### Runtime and Deployment Boundaries
The main control plane uses asyncio for feed processing, scoring, execution, and nuclear polling; the watchdog uses a separate thread. External dependencies are MT5/MetaTrader named-pipe IPC, SQLite via async access, Telegram Bot API, and NumPy/Pandas. Docker assets exist in `Dockerfile` and `docker-compose.yml`, but the MT5 named-pipe integration makes Windows VPS deployment the material runtime target.

Main entry points: [`bridge/pipe_client.py`](https://github.com/okeson453/ghost-grid/blob/main/bridge/pipe_client.py) (Named-pipe bridge), [`execution/commander.py`](https://github.com/okeson453/ghost-grid/blob/main/execution/commander.py) (Order commander), [`data/snapshot_builder.py`](https://github.com/okeson453/ghost-grid/blob/main/data/snapshot_builder.py) (Market snapshots), [`portfolio/state.py`](https://github.com/okeson453/ghost-grid/blob/main/portfolio/state.py) (Portfolio state)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_mt5["MT5 boundary"]
  node_mt5_ea["MT5 Expert Advisor<br/>MQL5 EA<br/>[GhostGrid.mq5]"]
  node_pipe_bridge["Named-pipe bridge<br/>IPC bridge<br/>[pipe_client.py]"]
end

subgraph group_decision["Decision pipeline"]
  node_market_state["Market snapshots<br/>data pipeline"]
  node_derived_data["Derived indicators<br/>market analytics<br/>[atr.py]"]
  node_regime["Regime classifier<br/>regime engine<br/>[classifier.py]"]
  node_confluence["Confluence engines<br/>scoring engines<br/>[engine.py]"]
  node_fusion_gate{{"Fusion and gate<br/>signal decision<br/>[fusion.py]"}}
end

subgraph group_control["Risk and control"]
  node_risk{{"Pre-trade risk<br/>risk governor<br/>[governor.py]"}}
  node_portfolio["Portfolio state<br/>portfolio service<br/>[state.py]"]
  node_nuclear{{"Nuclear guardian<br/>emergency controller<br/>[controller.py]"}}
  node_watchdog["Independent watchdog<br/>OS thread<br/>[thread.py]"]
  node_telegram["Telegram control<br/>operator API<br/>[bot.py]"]
end

subgraph group_lifecycle["Execution lifecycle"]
  node_execution["Order commander<br/>execution service<br/>[commander.py]"]
  node_positions["Position lifecycle<br/>position service<br/>[state_machine.py]"]
end

subgraph group_durability["Durability and observability"]
  node_sqlite[("SQLite event state<br/>durable store<br/>[connection.py]")]
  node_observability["Metrics and journal<br/>monitoring<br/>[metrics.py]"]
end

node_main{{"Async control plane<br/>runtime<br/>[main.py]"}}

node_mt5_ea -->|"ticks, events, fills"| node_pipe_bridge
node_pipe_bridge -->|"incoming market events"| node_market_state
node_market_state -->|"OHLCV snapshots"| node_derived_data
node_market_state -->|"snapshot context"| node_regime
node_derived_data -->|"ATR, VWAP, CVD"| node_confluence
node_regime -->|"regime context"| node_confluence
node_market_state -->|"multi-timeframe state"| node_confluence
node_confluence -->|"component scores"| node_fusion_gate
node_fusion_gate -->|"actionable signal"| node_risk
node_portfolio -->|"trading permission"| node_risk
node_risk -->|"sized approved order"| node_execution
node_execution -->|"order and close commands"| node_pipe_bridge
node_pipe_bridge -->|"confirmations"| node_execution
node_execution -->|"fills"| node_positions
node_positions -->|"position and PnL state"| node_portfolio
node_portfolio -->|"equity and safety state"| node_nuclear
node_nuclear -->|"emergency close actions"| node_execution
node_watchdog -.->|"direct emergency command"| node_pipe_bridge
node_telegram -->|"operator commands"| node_main
node_main -->|"alerts and status"| node_telegram
node_main -->|"persist runtime state"| node_sqlite
node_positions -->|"durable position events"| node_sqlite
node_portfolio -->|"ledger and equity state"| node_sqlite
node_main -->|"runtime telemetry"| node_observability
node_sqlite -->|"trade journal data"| node_observability

click node_main "https://github.com/okeson453/ghost-grid/blob/main/main.py"
click node_mt5_ea "https://github.com/okeson453/ghost-grid/blob/main/mt5_ea/GhostGrid.mq5"
click node_pipe_bridge "https://github.com/okeson453/ghost-grid/blob/main/bridge/pipe_client.py"
click node_market_state "https://github.com/okeson453/ghost-grid/blob/main/data/snapshot_builder.py"
click node_derived_data "https://github.com/okeson453/ghost-grid/blob/main/data/atr.py"
click node_regime "https://github.com/okeson453/ghost-grid/blob/main/regime/classifier.py"
click node_confluence "https://github.com/okeson453/ghost-grid/blob/main/scoring/hmp/engine.py"
click node_fusion_gate "https://github.com/okeson453/ghost-grid/blob/main/scoring/fusion.py"
click node_risk "https://github.com/okeson453/ghost-grid/blob/main/risk/governor.py"
click node_portfolio "https://github.com/okeson453/ghost-grid/blob/main/portfolio/state.py"
click node_nuclear "https://github.com/okeson453/ghost-grid/blob/main/nuclear/controller.py"
click node_watchdog "https://github.com/okeson453/ghost-grid/blob/main/watchdog/thread.py"
click node_execution "https://github.com/okeson453/ghost-grid/blob/main/execution/commander.py"
click node_positions "https://github.com/okeson453/ghost-grid/blob/main/positions/state_machine.py"
click node_sqlite "https://github.com/okeson453/ghost-grid/blob/main/db/connection.py"
click node_telegram "https://github.com/okeson453/ghost-grid/blob/main/telegram/bot.py"
click node_observability "https://github.com/okeson453/ghost-grid/blob/main/observability/metrics.py"

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_mt5_ea,node_pipe_bridge toneBlue
class node_market_state,node_derived_data,node_regime,node_confluence,node_fusion_gate toneAmber
class node_risk,node_portfolio,node_nuclear,node_watchdog,node_telegram toneMint
class node_execution,node_positions toneRose
class node_sqlite,node_observability toneIndigo
class node_main toneNeutral
```

## Components

### MT5 boundary

Windows named-pipe integration with the EA.

- [MT5 Expert Advisor](https://github.com/okeson453/ghost-grid/blob/main/mt5_ea/GhostGrid.mq5): MQL5 EA · MT5-side market and order endpoint. · `mt5_ea/GhostGrid.mq5`
- [Named-pipe bridge](https://github.com/okeson453/ghost-grid/blob/main/bridge/pipe_client.py): IPC bridge · Frames messages and manages pipe health and reconnects. · `bridge/pipe_client.py`

### Decision pipeline

Market state through gated trade actions.

- [Market snapshots](https://github.com/okeson453/ghost-grid/blob/main/data/snapshot_builder.py): data pipeline · Aggregates ticks into immutable multi-timeframe OHLCV state. · `data/snapshot_builder.py`
- [Derived indicators](https://github.com/okeson453/ghost-grid/blob/main/data/atr.py): market analytics · Produces ATR, VWAP, CVD, and related inputs. · `data/atr.py`
- [Regime classifier](https://github.com/okeson453/ghost-grid/blob/main/regime/classifier.py): regime engine · Supplies market context and session state. · `regime/classifier.py`
- [Confluence engines](https://github.com/okeson453/ghost-grid/blob/main/scoring/hmp/engine.py): scoring engines · Independent HMP, HLCP, and MPP scoring. · `scoring/hmp/engine.py`
- [Fusion and gate](https://github.com/okeson453/ghost-grid/blob/main/scoring/fusion.py): signal decision · Combines scores into H_c and applies hysteresis. · `scoring/fusion.py`

### Risk and control

Portfolio safety and operator controls.

- [Pre-trade risk](https://github.com/okeson453/ghost-grid/blob/main/risk/governor.py): risk governor · Validates trade permission and sizes approved actions. · `risk/governor.py`
- [Portfolio state](https://github.com/okeson453/ghost-grid/blob/main/portfolio/state.py): portfolio service · Aggregates equity, PnL, correlation, and operating mode. · `portfolio/state.py`
- [Nuclear guardian](https://github.com/okeson453/ghost-grid/blob/main/nuclear/controller.py): emergency controller · Triggers concurrent closes and cooldown or day halts. · `nuclear/controller.py`
- [Independent watchdog](https://github.com/okeson453/ghost-grid/blob/main/watchdog/thread.py): OS thread · Can directly send emergency pipe commands outside asyncio. · `watchdog/thread.py`
- [Telegram control](https://github.com/okeson453/ghost-grid/blob/main/telegram/bot.py): operator API · Receives status and manual safety commands; sends alerts. · `telegram/bot.py`

### Execution lifecycle

Order dispatch, fills, and position exits.

- [Order commander](https://github.com/okeson453/ghost-grid/blob/main/execution/commander.py): execution service · Converts approved actions into MT5 order and close commands. · `execution/commander.py`
- [Position lifecycle](https://github.com/okeson453/ghost-grid/blob/main/positions/state_machine.py): position service · Registers fills and applies state-machine, trailing, and CVD exits. · `positions/state_machine.py`

### Durability and observability

SQLite-backed state and operational telemetry.

- [SQLite event state](https://github.com/okeson453/ghost-grid/blob/main/db/connection.py): durable store · Durable event and state boundary. · `db/connection.py`
- [Metrics and journal](https://github.com/okeson453/ghost-grid/blob/main/observability/metrics.py): monitoring · Records metrics and trades and evaluates drift. · `observability/metrics.py`

### Other components

- [Async control plane](https://github.com/okeson453/ghost-grid/blob/main/main.py): runtime · Coordinates feed processing, decisions, execution, and nuclear polling. · `main.py`

## Connections

- MT5 Expert Advisor → Named-pipe bridge: ticks, events, fills
- Named-pipe bridge → Market snapshots: incoming market events
- Market snapshots → Derived indicators: OHLCV snapshots
- Market snapshots → Regime classifier: snapshot context
- Derived indicators → Confluence engines: ATR, VWAP, CVD
- Regime classifier → Confluence engines: regime context
- Market snapshots → Confluence engines: multi-timeframe state
- Confluence engines → Fusion and gate: component scores
- Fusion and gate → Pre-trade risk: actionable signal
- Portfolio state → Pre-trade risk: trading permission
- Pre-trade risk → Order commander: sized approved order
- Order commander → Named-pipe bridge: order and close commands
- Named-pipe bridge → Order commander: confirmations
- Order commander → Position lifecycle: fills
- Position lifecycle → Portfolio state: position and PnL state
- Portfolio state → Nuclear guardian: equity and safety state
- Nuclear guardian → Order commander: emergency close actions
- Independent watchdog → Named-pipe bridge: direct emergency command
- Telegram control → Async control plane: operator commands
- Async control plane → Telegram control: alerts and status
- Async control plane → SQLite event state: persist runtime state
- Position lifecycle → SQLite event state: durable position events
- Portfolio state → SQLite event state: ledger and equity state
- Async control plane → Metrics and journal: runtime telemetry
- SQLite event state → Metrics and journal: trade journal data
