# anasneji2002/backtesting-api architecture

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

- Interactive diagram: https://gitdiagram.com/anasneji2002/backtesting-api
- Repository: https://github.com/anasneji2002/backtesting-api

## Overview

1. **Top-level shape**
   - This is a single ASP.NET Core Web API project targeting .NET 10.
   - The app is organized as a request-driven backtesting pipeline rather than a multi-tenant web UI or database-backed system.

2. **Entry point and composition root**
   - `Program.cs` is the main bootstrapper.
   - It wires up dependency injection, configuration (`appsettings.json` / `appsettings.Development.json`), and likely registers the factories and singleton services described in the README.
   - The API key for Twelve Data is expected from user secrets/config, so external data access is configuration-driven.

3. **API boundary**
   - `Controllers/BackTestController.cs` exposes the single public backtesting endpoint: `GET /api/BackTest`.
   - This controller is the boundary between HTTP query parameters and the domain/backtesting workflow.
   - It accepts user-selected strategy and position-sizing options, then delegates orchestration to the service layer.

4. **Application orchestration layer**
   - `Services/BackTestService/BackTestService.cs` is the high-level use-case service.
   - It likely validates/normalizes inputs, coordinates data retrieval, builds the engine, and returns a `BackTestResult`.
   - This is the main application service that keeps the controller thin.

5. **Backtesting engine core**
   - `Services/BackTestEngine/BackTestEngine.cs` is the execution engine that simulates trading across historical data points.
   - It consumes market data, strategy decisions, position sizing, and order execution logic in a loop over the date range.
   - This is the central domain runtime where the portfolio evolves over time.

6. **Strategy subsystem**
   - `Services/Strategy/` contains pluggable trading rules behind `IStrategy`.
   - The built-in strategies are `MovingAverageStrategy`, `RsiStrategy`, `BreakoutStrategy`, and `BuyTheDipStrategy`.
   - These strategies are selected by `Enums/StrategyEnum.cs` and instantiated via `Factories/StrategyFactory.cs`.
   - They output trading intent using `Enums/Operation.cs` such as buy/sell/hold.

7. **Position sizing subsystem**
   - `Services/PositionSizer/` encapsulates how much capital to commit per trade.
   - Implementations are `AllInPositionSizer`, `FixedAmountPositionSizer`, and `PercentagePositionSizer`, selected by `PositionSizerEnum`.
   - `Factories/PositionSizerFactory.cs` isolates the engine from concrete sizing rules and keeps allocation logic replaceable.

8. **Order execution subsystem**
   - `Services/OrderManager/OrderManager.cs` applies strategy decisions and sizing outputs to the portfolio state.
   - It is the place where trades become state changes: quantity, cash, and trade count adjustments.
   - `Factories/OrderManagerFactory.cs` suggests the order manager can be swapped or configured differently if needed.

9. **Market data boundary**
   - `Services/HistoricalDataProvider/TwelveDataHistoricalDataProvider.cs` is the external data adapter.
   - It fetches historical candles/prices from Twelve Data, abstracted behind `IHistoricalDataProvider`.
   - This makes market data a clean integration boundary separate from strategy logic.

10. **Caching layer**
   - `Services/CacheService/CacheService.cs` is a supporting performance layer around repeated market-data access.
   - `Models/CacheValue.cs` indicates cached entries are modeled explicitly rather than hidden inside the provider.
   - In architecture terms, cache sits between the backtest workflow and the Twelve Data adapter to reduce API calls and latency.

11. **Domain models and result shape**
   - `Models/Portfolio.cs` captures state before/after simulation: symbol, quantity, capital, and unit price.
   - `Models/HistoricalDataPoint.cs` represents the time-series input used by the engine.
   - `Models/BackTestResult.cs` is the outward-facing response model with portfolio snapshots, net profit/loss, and trade count.

12. **Technical analysis support**
   - `Helpers/StocksIndicatorsHelper.cs` and the `FacioQuo.Stock.Indicators` dependency provide indicator calculations used by strategies.
   - This means strategies are not calculating all technical signals manually; they rely on shared indicator utilities.

13. **Factories and inversion of control**
   - `Factories/BackTestEngineFactory.cs`, `StrategyFactory.cs`, `PositionSizerFactory.cs`, and `OrderManagerFactory.cs` form the assembly layer for runtime selection.
   - The factories translate request enums into concrete implementations, which keeps the controller and service layer decoupled from specific strategy classes.

14. **Overall data flow**
   - HTTP request enters `BackTestController` → `BackTestService` validates and orchestrates → `HistoricalDataProvider` retrieves/caches price history → `BackTestEngine` iterates through data → `Strategy` decides → `PositionSizer` sizes trade → `OrderManager` updates `Portfolio` → `BackTestResult` returns to caller.
   - The system is essentially stateless per request, with caching as the main cross-request optimization.

15. **Architectural boundaries to show in a diagram**
   - External boundary: Twelve Data API.
   - Application boundary: controller and backtest service.
   - Domain/execution boundary: engine, strategies, sizers, order manager.
   - Infrastructure/support boundary: cache, indicator helper, configuration.
   - There is no evidence of a database, message queue, or background worker; the core workload is synchronous request/response backtesting.

Main entry points: [`Services/BackTestService/BackTestService.cs`](https://github.com/anasneji2002/backtesting-api/blob/master/Services/BackTestService/BackTestService.cs) (BackTest Service), [`Services/BackTestEngine/BackTestEngine.cs`](https://github.com/anasneji2002/backtesting-api/blob/master/Services/BackTestEngine/BackTestEngine.cs) (BackTest Engine), [`Services/HistoricalDataProvider/TwelveDataHistoricalDataProvider.cs`](https://github.com/anasneji2002/backtesting-api/blob/master/Services/HistoricalDataProvider/TwelveDataHistoricalDataProvider.cs) (Twelve Data), [`Models`](https://github.com/anasneji2002/backtesting-api/tree/master/Models) (Domain Models)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_g_external["External"]
  node_n_data_provider[("Twelve Data<br/>data adapter")]
end

subgraph group_g_api["API"]
  node_n_program["Program<br/>bootstrapper<br/>[Program.cs]"]
  node_n_controller["BackTest API<br/>controller"]
end

subgraph group_g_app["Application"]
  node_n_service["BackTest Service<br/>orchestrator<br/>[BackTestService.cs]"]
  node_n_engine_factory{{"Engine Factory"}}
  node_n_strategy_factory{{"Strategy Factory<br/>[StrategyFactory.cs]"}}
  node_n_sizer_factory{{"Sizer Factory"}}
  node_n_order_factory{{"Order Factory"}}
end

subgraph group_g_core["Core"]
  node_n_engine["BackTest Engine<br/>simulation engine<br/>[BackTestEngine.cs]"]
  node_n_strategy["Strategies<br/>trading rules"]
  node_n_sizer["Position Sizers<br/>allocation rules"]
  node_n_order["Order Manager<br/>trade execution<br/>[OrderManager.cs]"]
end

subgraph group_g_support["Support"]
  node_n_cache["Cache Service<br/>[CacheService.cs]"]
  node_n_indicators["Indicators<br/>technical analysis"]
  node_n_models["Domain Models<br/>result and state"]
  node_n_enums["Enums<br/>selection codes"]
end

node_n_program -->|"hosts"| node_n_controller
node_n_program -->|"registers"| node_n_service
node_n_program -->|"configures"| node_n_data_provider
node_n_controller -->|"calls"| node_n_service
node_n_service -->|"builds"| node_n_engine_factory
node_n_service -->|"requests data"| node_n_data_provider
node_n_service -->|"uses"| node_n_cache
node_n_service -->|"returns"| node_n_models
node_n_engine_factory -->|"creates"| node_n_engine
node_n_engine -->|"selects strategy"| node_n_strategy_factory
node_n_engine -->|"selects sizer"| node_n_sizer_factory
node_n_engine -->|"selects order mgr"| node_n_order_factory
node_n_engine -->|"reads/writes"| node_n_models
node_n_strategy_factory -->|"instantiates"| node_n_strategy
node_n_sizer_factory -->|"instantiates"| node_n_sizer
node_n_order_factory -->|"instantiates"| node_n_order
node_n_strategy -->|"uses"| node_n_indicators
node_n_order -->|"updates"| node_n_models
node_n_cache -->|"fronts"| node_n_data_provider
node_n_data_provider -->|"emits"| node_n_models
node_n_enums -->|"drives"| node_n_strategy_factory
node_n_enums -->|"drives"| node_n_sizer_factory
node_n_enums -->|"labels"| node_n_strategy

click node_n_program "https://github.com/anasneji2002/backtesting-api/blob/master/Program.cs"
click node_n_controller "https://github.com/anasneji2002/backtesting-api/blob/master/Controllers/BackTestController.cs"
click node_n_service "https://github.com/anasneji2002/backtesting-api/blob/master/Services/BackTestService/BackTestService.cs"
click node_n_engine_factory "https://github.com/anasneji2002/backtesting-api/blob/master/Factories/BackTestEngineFactory.cs"
click node_n_engine "https://github.com/anasneji2002/backtesting-api/blob/master/Services/BackTestEngine/BackTestEngine.cs"
click node_n_strategy_factory "https://github.com/anasneji2002/backtesting-api/blob/master/Factories/StrategyFactory.cs"
click node_n_strategy "https://github.com/anasneji2002/backtesting-api/tree/master/Services/Strategy"
click node_n_sizer_factory "https://github.com/anasneji2002/backtesting-api/blob/master/Factories/PositionSizerFactory.cs"
click node_n_sizer "https://github.com/anasneji2002/backtesting-api/tree/master/Services/PositionSizer"
click node_n_order_factory "https://github.com/anasneji2002/backtesting-api/blob/master/Factories/OrderManagerFactory.cs"
click node_n_order "https://github.com/anasneji2002/backtesting-api/blob/master/Services/OrderManager/OrderManager.cs"
click node_n_data_provider "https://github.com/anasneji2002/backtesting-api/blob/master/Services/HistoricalDataProvider/TwelveDataHistoricalDataProvider.cs"
click node_n_cache "https://github.com/anasneji2002/backtesting-api/blob/master/Services/CacheService/CacheService.cs"
click node_n_indicators "https://github.com/anasneji2002/backtesting-api/blob/master/Helpers/StocksIndicatorsHelper.cs"
click node_n_models "https://github.com/anasneji2002/backtesting-api/tree/master/Models"
click node_n_enums "https://github.com/anasneji2002/backtesting-api/tree/master/Enums"

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_n_data_provider toneBlue
class node_n_program,node_n_controller toneAmber
class node_n_service,node_n_engine_factory,node_n_strategy_factory,node_n_sizer_factory,node_n_order_factory toneMint
class node_n_engine,node_n_strategy,node_n_sizer,node_n_order toneRose
class node_n_cache,node_n_indicators,node_n_models,node_n_enums toneIndigo
```

## Components

### External

Third-party market data source

- [Twelve Data](https://github.com/anasneji2002/backtesting-api/blob/master/Services/HistoricalDataProvider/TwelveDataHistoricalDataProvider.cs): data adapter · Fetches historical market candles · `Services/HistoricalDataProvider/TwelveDataHistoricalDataProvider.cs`

### API

HTTP entrypoint and request boundary

- [Program](https://github.com/anasneji2002/backtesting-api/blob/master/Program.cs): bootstrapper · Wires DI, config, and app startup · `Program.cs`
- [BackTest API](https://github.com/anasneji2002/backtesting-api/blob/master/Controllers/BackTestController.cs): controller · HTTP endpoint for running backtests · `Controllers/BackTestController.cs`

### Application

Use-case orchestration and composition root

- [BackTest Service](https://github.com/anasneji2002/backtesting-api/blob/master/Services/BackTestService/BackTestService.cs): orchestrator · Coordinates the backtest use case · `Services/BackTestService/BackTestService.cs`
- [Engine Factory](https://github.com/anasneji2002/backtesting-api/blob/master/Factories/BackTestEngineFactory.cs): factory · Creates backtest engine instances · `Factories/BackTestEngineFactory.cs`
- [Strategy Factory](https://github.com/anasneji2002/backtesting-api/blob/master/Factories/StrategyFactory.cs): factory · Resolves strategy by enum · `Factories/StrategyFactory.cs`
- [Sizer Factory](https://github.com/anasneji2002/backtesting-api/blob/master/Factories/PositionSizerFactory.cs): factory · Resolves position sizing by enum · `Factories/PositionSizerFactory.cs`
- [Order Factory](https://github.com/anasneji2002/backtesting-api/blob/master/Factories/OrderManagerFactory.cs): factory · Resolves order manager implementation · `Factories/OrderManagerFactory.cs`

### Core

Backtesting execution and trade decision flow

- [BackTest Engine](https://github.com/anasneji2002/backtesting-api/blob/master/Services/BackTestEngine/BackTestEngine.cs): simulation engine · Runs the historical trading loop · `Services/BackTestEngine/BackTestEngine.cs`
- [Strategies](https://github.com/anasneji2002/backtesting-api/tree/master/Services/Strategy): trading rules · Pluggable entry/exit logic · `Services/Strategy`
- [Position Sizers](https://github.com/anasneji2002/backtesting-api/tree/master/Services/PositionSizer): allocation rules · Determines trade size per signal · `Services/PositionSizer`
- [Order Manager](https://github.com/anasneji2002/backtesting-api/blob/master/Services/OrderManager/OrderManager.cs): trade execution · Applies signals to portfolio state · `Services/OrderManager/OrderManager.cs`

### Support

Shared utilities, models, and configuration

- [Cache Service](https://github.com/anasneji2002/backtesting-api/blob/master/Services/CacheService/CacheService.cs): cache · Stores repeated market-data lookups · `Services/CacheService/CacheService.cs`
- [Indicators](https://github.com/anasneji2002/backtesting-api/blob/master/Helpers/StocksIndicatorsHelper.cs): technical analysis · Shared indicator calculations · `Helpers/StocksIndicatorsHelper.cs`
- [Domain Models](https://github.com/anasneji2002/backtesting-api/tree/master/Models): result and state · Portfolio, history points, cache values, and results · `Models`
- [Enums](https://github.com/anasneji2002/backtesting-api/tree/master/Enums): selection codes · Strategy, sizer, and operation choices · `Enums`

## Connections

- Program → BackTest API: hosts · Registers MVC endpoint pipeline
- Program → BackTest Service: registers · Composes application services
- Program → Twelve Data: configures · Injects external data adapter and secrets-driven settings
- BackTest API → BackTest Service: calls · Maps request parameters to the use case
- BackTest Service → Engine Factory: builds · Selects engine composition for the run
- BackTest Service → Twelve Data: requests data · Pulls historical prices for the symbol and date range
- BackTest Service → Cache Service: uses · Reuses cached market data when available
- BackTest Service → Domain Models: returns · Produces the backtest response model
- Engine Factory → BackTest Engine: creates · Constructs the simulation engine
- BackTest Engine → Strategy Factory: selects strategy · Resolves strategy implementation for the run
- BackTest Engine → Sizer Factory: selects sizer · Resolves trade sizing implementation
- BackTest Engine → Order Factory: selects order mgr · Resolves order execution behavior
- BackTest Engine → Domain Models: reads/writes · Consumes historical points and mutates portfolio/result state
- Strategy Factory → Strategies: instantiates · Maps strategy enum to rule set
- Sizer Factory → Position Sizers: instantiates · Maps sizing enum to allocation rule
- Order Factory → Order Manager: instantiates · Maps configuration to order manager
- Strategies → Indicators: uses · Relies on technical indicators for signals
- Order Manager → Domain Models: updates · Applies fills to portfolio state
- Cache Service → Twelve Data: fronts · Reduces repeated calls to the external API
- Twelve Data → Domain Models: emits · Produces historical data points
- Enums → Strategy Factory: drives · Chooses strategy implementation
- Enums → Sizer Factory: drives · Chooses position sizing implementation
- Enums → Strategies: labels · Signals buy, sell, or hold decisions
