# nkastelan/ed architecture

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

- Interactive diagram: https://gitdiagram.com/nkastelan/ed
- Repository: https://github.com/nkastelan/ed

## Overview

##### Project type & purpose (what you’re diagramming)
This is a **single-process C++ event-driven backtesting engine** for trading strategies (“Ed”). The architecture is built around an **event loop + event queue** that routes market data updates through:

**DataHandler → Strategy → Portfolio → ExecutionHandler**, with **events** as the coupling mechanism.

It’s not a microservice system; it’s a **modular in-process system** where “components” are C++ classes/modules and “integration points” are events and data structures.

##### Read the file tree as architecture (map folders/files to components)
From the tree:

- **Core engine / orchestration**
- `src/main.cpp` (entrypoint; wires everything)
- `src/backtest.hpp/.cpp` (the backtest “engine” / coordinator; likely owns the event loop)
- **Event system**
- `src/event.hpp/.cpp` (event base types; probably MarketEvent, SignalEvent, OrderEvent, FillEvent etc.)
- **Market data ingestion**
- `src/dataHandler.hpp/.cpp` (reads CSV, emits market events)
- `data/Binance_ETHUSDT_day.csv` (example historical dataset input)
- **Strategy layer**
- `src/strategies/strategy.hpp` (interface/abstract base)
- `src/strategies/tradingStrategy.cpp` (actual strategy implementation)
- `src/strategies/benchmark.cpp` (baseline strategy; buy-and-hold / benchmark logic)
- **Portfolio / risk / PnL**
- `src/portfolio.hpp/.cpp` (positions, holdings, equity curve; turns signals into orders)
- **Execution simulation**
- `src/executionHandler.hpp/.cpp` (simulated broker/exchange; turns orders into fills)
- **External/native dependency**
- `Dependencies/ta-lib/...` (TA-Lib headers/lib; technical indicators; used by strategies)

##### CLI / App Entrypoint
- `main.cpp`
##### Backtest Engine / Event Loop
- `backtest.*`
- responsibilities: initialize components, maintain simulation time, pop/push events, stop conditions
##### Event Queue / Event Bus (in-process)
- could be a `std::queue<Event>` owned by backtest engine
##### Event Types
- `event.*` (define event hierarchy and payloads)
##### Data Handler
- `dataHandler.*`
- input: CSV in `data/`
- output: `MarketEvent`s
##### Strategy (interface)
- `strategies/strategy.hpp`
##### Strategy Implementations
- `strategies/tradingStrategy.cpp`
- `strategies/benchmark.cpp`
##### Indicator Library (TA-Lib)
- `Dependencies/ta-lib`
- used by strategy implementation(s)
##### Portfolio
- `portfolio.*`
- tracks positions/holdings/cash; produces orders; updates on fills
##### Execution Handler
- `executionHandler.*`
- simulates fills, slippage/commission (if present), produces fill events
##### Outputs / Reporting (current + planned)
- currently may be stdout/logs; future: PDF reports, Monte Carlo, visualizations (from README)

##### Historical Data → DataHandler
- `CSV (data/Binance_ETHUSDT_day.csv)` → `DataHandler`

##### DataHandler emits Market events
- `DataHandler` → `EventQueue`: `MarketEvent`

##### Strategy consumes Market events and emits Signals
- `EventQueue` → `Strategy`: `MarketEvent`
- `Strategy` → `EventQueue`: `SignalEvent`

##### Portfolio consumes Signals and emits Orders
- `EventQueue` → `Portfolio`: `SignalEvent`
- `Portfolio` → `EventQueue`: `OrderEvent`

##### ExecutionHandler consumes Orders and emits Fills
- `EventQueue` → `ExecutionHandler`: `OrderEvent`
- `ExecutionHandler` → `EventQueue`: `FillEvent`

##### Portfolio consumes Fills and updates state
- `EventQueue` → `Portfolio`: `FillEvent`
- Portfolio updates: cash/positions/equity curve (internal state)

##### Backtest engine controls the loop
- `Backtest` repeatedly:
- asks `DataHandler` for next bar (or data tick)
- pushes events
- dispatches events until queue is empty
- advances time / terminates when data exhausted

- **Event-Driven Architecture (EDA), in-process**
- Queue-based dispatch loop
- **Strategy Pattern**
- `strategy.hpp` defines interface; multiple implementations (`benchmark`, `tradingStrategy`)
- **Separation of concerns**
- market data vs signal generation vs portfolio construction vs execution simulation
- **Pluggability**
- strategies interchangeable; execution handler can be swapped to model different fills; data handler can be extended for new sources

##### “Don’t overthink it” decomposition checklist (ensure you didn’t miss anything)
- Where the **event queue lives** (likely inside Backtest engine)
- Who **creates** and who **consumes** each event type
- The **source of truth** for portfolio state (Portfolio)
- The **data source** (CSV) and ingestion boundary (DataHandler)
- The **indicator dependency** (TA-Lib) and which module calls it (Strategy impl)
- The **entrypoint wiring** (main constructs the concrete strategy + handlers)

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% =========================
  %% Diagram 1: Component Architecture (vertical)
  %% =========================
  subgraph D1["Diagram 1: In-Process Event-Driven Backtesting Engine (Components)"]
    direction TB

    subgraph L0["Application"]
      direction TB
      Main["CLI / App Entrypoint\n(main.cpp)\n- wires components"]:::core
    end

    subgraph L1["Core Engine / Orchestration"]
      direction TB
      Backtest["Backtest Engine / Event Loop\n(backtest.*)\n- owns simulation time\n- drives dispatch loop"]:::core
      EventQueue["Event Queue / Event Bus (in-process)\n- std::queue<Event>\n- routes events between modules"]:::eventsys
      EventTypes["Event Types\n(event.*)\n- MarketEvent\n- SignalEvent\n- OrderEvent\n- FillEvent"]:::eventsys
    end

    subgraph L2["Market Data Layer"]
      direction TB
      CSV["Historical Dataset (CSV)\nBinance_ETHUSDT_day.csv"]:::data
      DataHandler["DataHandler (CSV reader)\n(dataHandler.*)\nEmits: MarketEvent"]:::core
    end

    subgraph L3["Strategy Layer (Strategy Pattern)"]
      direction TB
      StrategyI["Strategy Interface\n(strategy.hpp)\nConsumes: MarketEvent\nEmits: SignalEvent"]:::strategy
      StrategyImpl["Trading Strategy (impl)\n(tradingStrategy.cpp)\n- signal generation"]:::strategy
      Benchmark["Benchmark Strategy (impl)\n(benchmark.cpp)\n- baseline logic"]:::strategy
      TALib["TA-Lib (native dependency)\n- indicators"]:::library
    end

    subgraph L4["Portfolio / Risk / PnL"]
      direction TB
      Portfolio["Portfolio\n(portfolio.*)\nConsumes: SignalEvent, FillEvent\nEmits: OrderEvent\nState: cash/positions/PnL/equity"]:::core
    end

    subgraph L5["Execution Simulation"]
      direction TB
      Execution["ExecutionHandler\n(executionHandler.*)\nConsumes: OrderEvent\nEmits: FillEvent"]:::core
    end

    subgraph L6["Outputs / Reporting"]
      direction TB
      Reports["Outputs / Reporting\n- stdout/logs today\n- planned reports/visuals"]:::output
    end

    %% Wiring / ownership
    Main -->|"constructs+configures"| Backtest
    Backtest -->|"owns"| EventQueue
    Backtest -->|"uses"| EventTypes

    %% Data ingestion
    CSV -->|"readbars"| DataHandler
    Backtest -->|"calls next_bar()"| DataHandler

    %% Runtime event flow (solid)
    DataHandler -->|"MarketEvent"| EventQueue
    EventQueue -->|"MarketEvent"| StrategyI
    StrategyI -->|"SignalEvent"| EventQueue
    EventQueue -->|"SignalEvent"| Portfolio
    Portfolio -->|"OrderEvent"| EventQueue
    EventQueue -->|"OrderEvent"| Execution
    Execution -->|"FillEvent"| EventQueue
    EventQueue -->|"FillEvent"| Portfolio

    %% Reporting (conceptual)
    Portfolio -->|"equity+PnL"| Reports

    %% Strategy pattern bindings
    Backtest -->|"uses Strategy* (pluggable)"| StrategyI
    StrategyI -->|"implemented_by"| StrategyImpl
    StrategyI -->|"implemented_by"| Benchmark

    %% Compile-time / "uses" dependencies (dashed)
    StrategyImpl -.->|"uses indicators"| TALib
    Benchmark -.->|"optional indicators"| TALib
    DataHandler -.->|"creates"| EventTypes
    StrategyI -.->|"creates/consumes"| EventTypes
    Portfolio -.->|"creates/consumes"| EventTypes
    Execution -.->|"creates/consumes"| EventTypes

    %% Annotations (architectural intent)
    NoteEDA["Pattern: Event-Driven Architecture (in-process)\n- queue-mediated dispatch loop\n- loose coupling via events"]:::note
    NotePlug["Pluggability:\n- swap Strategy implementations\n- extend DataHandler sources\n- change Execution fill model"]:::note

    Backtest --- NoteEDA
    StrategyI --- NotePlug
  end

  %% =========================
  %% Diagram 2: One Bar/Timestep Sequence (vertical)
  %% =========================
  subgraph D2["Diagram 2: Runtime Sequence (Single Bar/Timestep)"]
    direction TB

    subgraph SQ["Event Dispatch Loop"]
      direction TB
      S1["1) Backtest asks DataHandler for next bar"]:::seq
      S2["2) DataHandler enqueues MarketEvent"]:::seq
      S3["3) EventQueue dequeues MarketEvent -> Strategy"]:::seq
      S4["4) Strategy enqueues SignalEvent"]:::seq
      S5["5) EventQueue dequeues SignalEvent -> Portfolio"]:::seq
      S6["6) Portfolio enqueues OrderEvent"]:::seq
      S7["7) EventQueue dequeues OrderEvent -> ExecutionHandler"]:::seq
      S8["8) ExecutionHandler enqueues FillEvent"]:::seq
      S9["9) EventQueue dequeues FillEvent -> Portfolio updates state"]:::seq
      S10["10) Loop continues until data exhausted + queue empty"]:::seq
    end

    S1 --> S2 --> S3 --> S4 --> S5 --> S6 --> S7 --> S8 --> S9 --> S10
  end

  %% =========================
  %% Diagram 3: Portfolio State Model (compact)
  %% =========================
  subgraph D3["Diagram 3: Portfolio State (Source of Truth)"]
    direction TB
    PState["Portfolio State\n- cash\n- positions\n- holdings\n- equity curve\n- realized/unrealized PnL"]:::state
    PInputs["Consumes\n- SignalEvent\n- FillEvent"]:::state
    POutputs["Emits\n- OrderEvent"]:::state
    PState --> POutputs
    PInputs --> PState
  end

  %% =========================
  %% Click Events (from component mapping)
  %% =========================
  click Main "https://github.com/nkastelan/ed/blob/main/src/main.cpp"
  click Backtest "https://github.com/nkastelan/ed/blob/main/src/backtest.cpp"
  click EventTypes "https://github.com/nkastelan/ed/blob/main/src/event.hpp"
  click EventQueue "https://github.com/nkastelan/ed/blob/main/src/event.cpp"
  click DataHandler "https://github.com/nkastelan/ed/blob/main/src/dataHandler.cpp"
  click CSV "https://github.com/nkastelan/ed/blob/main/data/Binance_ETHUSDT_day.csv"
  click StrategyI "https://github.com/nkastelan/ed/blob/main/src/strategies/strategy.hpp"
  click StrategyImpl "https://github.com/nkastelan/ed/blob/main/src/strategies/tradingStrategy.cpp"
  click Benchmark "https://github.com/nkastelan/ed/blob/main/src/strategies/benchmark.cpp"
  click Portfolio "https://github.com/nkastelan/ed/blob/main/src/portfolio.cpp"
  click Execution "https://github.com/nkastelan/ed/blob/main/src/executionHandler.cpp"
  click TALib "https://github.com/nkastelan/ed/tree/main/Dependencies/ta-lib/include"

  %% =========================
  %% Styles
  %% =========================
  classDef core fill:#1f77b4,stroke:#0b2d4d,stroke-width:1.2px,color:#ffffff
  classDef strategy fill:#2ca02c,stroke:#0d3d0d,stroke-width:1.2px,color:#ffffff
  classDef data fill:#ff7f0e,stroke:#7a3a00,stroke-width:1.2px,color:#ffffff
  classDef library fill:#7b2cbf,stroke:#2c0a4d,stroke-width:1.2px,color:#ffffff
  classDef output fill:#17becf,stroke:#0a4f56,stroke-width:1.2px,color:#ffffff
  classDef eventsys fill:#6c757d,stroke:#343a40,stroke-width:1.2px,color:#ffffff
  classDef note fill:#f1f3f5,stroke:#adb5bd,stroke-width:1px,color:#111827
  classDef seq fill:#ffe8cc,stroke:#d9480f,stroke-width:1px,color:#111827
  classDef state fill:#e7f5ff,stroke:#1c7ed6,stroke-width:1px,color:#111827
```
