How anasneji2002/backtesting-api works
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: BackTestService.cs BackTest Service · BackTestEngine.cs BackTest Engine · TwelveDataHistoricalDataProvider.cs Twelve Data · Models Domain Models
Components 16
External
Third-party market data source
- Twelve Data · Fetches historical market candles
Services/HistoricalDataProvider/TwelveDataHistoricalDataProvider.cs
API
HTTP entrypoint and request boundary
- Program · Wires DI, config, and app startup
Program.cs - BackTest API · HTTP endpoint for running backtests
Controllers/BackTestController.cs
Application
Use-case orchestration and composition root
- BackTest Service · Coordinates the backtest use case
Services/BackTestService/BackTestService.cs - Engine Factory · Creates backtest engine instances
Factories/BackTestEngineFactory.cs - Strategy Factory · Resolves strategy by enum
Factories/StrategyFactory.cs - Sizer Factory · Resolves position sizing by enum
Factories/PositionSizerFactory.cs - Order Factory · Resolves order manager implementation
Factories/OrderManagerFactory.cs
Core
Backtesting execution and trade decision flow
- BackTest Engine · Runs the historical trading loop
Services/BackTestEngine/BackTestEngine.cs - Strategies · Pluggable entry/exit logic
Services/Strategy - Position Sizers · Determines trade size per signal
Services/PositionSizer - Order Manager · Applies signals to portfolio state
Services/OrderManager/OrderManager.cs
Support
Shared utilities, models, and configuration
- Cache Service · Stores repeated market-data lookups
Services/CacheService/CacheService.cs - Indicators · Shared indicator calculations
Helpers/StocksIndicatorsHelper.cs - Domain Models · Portfolio, history points, cache values, and results
Models - Enums · Strategy, sizer, and operation choices
Enums
Connections 23
- 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