Metadata-Version: 2.4
Name: forex-precision-backtester
Version: 1.0.0
Summary: Institutional-grade discrete-event tick backtesting engine and execution simulation framework in 100% native Python.
Author: Quantitative Systems DevOps
License-Expression: MIT
Keywords: quantitative-finance,backtesting,tick-data,hft,forex,market-microstructure,trading,discrete-event,parquet
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: pyarrow>=10.0.0
Requires-Dist: plotly>=5.0.0
Provides-Extra: docs
Requires-Dist: sphinx>=7.0.0; extra == "docs"
Requires-Dist: sphinx-rtd-theme>=2.0.0; extra == "docs"
Requires-Dist: myst-parser>=2.0.0; extra == "docs"
Provides-Extra: test
Requires-Dist: pytest>=7.0.0; extra == "test"
Dynamic: license-file

# Universal Discrete-Event Tick Backtester Framework

A sovereign, institutional-grade, asset-agnostic discrete-event tick backtesting engine architected from first principles in 100% native Python. Designed specifically for quantitative hedge fund research, high-frequency tick simulations, and strict prop firm evaluation standards (e.g. FTMO 2-Step Challenge).

---

## Table of Contents
- [1. Core Architectural Pillars](#1-core-architectural-pillars)
- [2. Key Features](#2-key-features)
- [3. Architecture & Microstructure Pipeline](#3-architecture--microstructure-pipeline)
- [4. Performance & Microsecond Benchmark](#4-performance--microsecond-benchmark)
- [5. Installation & Prerequisites](#5-installation--prerequisites)
- [6. Quickstart: Building a Strategy](#6-quickstart-building-a-strategy)
- [7. Command-Line Interface (CLI) Usage](#7-command-line-interface-cli-usage)
- [8. Institutional Ledgers & Audit DataFrames](#8-institutional-ledgers--audit-dataframes)
- [9. Interactive HTML Visualizer Report](#9-interactive-html-visualizer-report)
- [10. Sub-Tick & High-Frequency Scheduling (1ms / 1μs)](#10-sub-tick--high-frequency-scheduling-1ms--1μs)
- [11. Current Limitations & Architectural Boundary Conditions](#11-current-limitations--architectural-boundary-conditions)
- [12. File Directory Map](#12-file-directory-map)
- [13. Test Suite Verification](#13-test-suite-verification)
- [14. Full Sphinx & ReadTheDocs Documentation](#14-full-sphinx--readthedocs-documentation)

---

## 1. Core Architectural Pillars

1. **Zero MT5 Dependency**:
   - Completely disconnected from MetaTrader 5 Strategy Tester, MetaEditor, and MT5 MCP wrappers.
   - Eliminates MT5 closed-source interpolation artifacts, single-threaded bottlenecks, and optimistic wick fills.
2. **Zero Lookahead Bias & Strict Next-Quote Causality**:
   - In accordance with market microstructure physics, a trading signal generated at time $t$ or tick $T_i$ is **strictly prohibited from executing on the quote that triggered it**.
   - All orders queue into an in-flight latency pipeline and execute strictly on incoming subsequent quotes at:
     $$t_{\text{execution}} \ge t_{\text{next\_quote}} + l$$
     where $l$ is the simulated network latency delay.
3. **Execution Reality & Microstructure Friction**:
   - **Spread-Aware Fills**: Market BUYs and Short exits execute on **Ask** ($P_a$); Market SELLs and Long exits execute on **Bid** ($P_b$).
   - **Asymmetric Natural Gap Slippage**: Stop Losses suffer negative gap slippage (worst of trigger vs prevailing quote). Take Profits fill at the designated limit target price without artificial windfall assumptions.
   - **Broker Commissions**: Hardcoded institutional commission models (e.g. FTMO $\$11.00$/lot on Gold, $\$3.00$/lot on FX & Indices).
4. **Sub-Tick Universal Timeline Synchronization**:
   - Provides native physical time progression hooks (`on_time`, `on_every_1ms`, `on_every_1us`, `step_ms`, `step_us`) allowing strategies to process off-tick queue dynamics, depth-of-market signals, and sub-tick schedule states.

---

## 2. Key Features

- **Extreme Throughput (>420,000 Ticks/Second)**:
  Memory-safe Parquet streaming with zero-copy PyArrow table slicing and column statistics metadata skipping. Processes 100+ million ticks without RAM exhaustion.
- **Dual Drawdown Accounting**:
  Maintains strict separation between **Closed Cash Balance Drawdown** and **Continuous Tick-by-Tick Mark-to-Market (MTM) Floating Equity Drawdown**.
- **Complete Audit Trail**:
  Every simulation produces 4 immutable transaction ledgers:
  1. [`TradeRecord`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L234-L294): Round-turn trades with entry/exit timestamps, PnL, slippage, MAE/MFE, return %, and dual order lineage (`order_id`, `exit_order_id`, `entry_deal_id`, `exit_deal_id`).
  2. [`DealRecord`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L150-L188): Discrete exchange execution fills (IN/OUT).
  3. [`OrderEventRecord`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L191-L231): Order lifecycle events (`SUBMIT`, `ACCEPT`, `FILL`, `MODIFY`, `CANCEL`, `REJECT`).
  4. [`AccountSnapshot`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L298-L322): Periodic and milestone balance/equity snapshots.
- **Microstructure Strategy Callbacks**:
  Strategies receive real-time notifications via `on_position_closed(trade)` and `on_order_event(event)`.
- **IEEE 754 Floating-Point Protection**:
  Sizing formulas include epsilon guards (`+ 1e-9`) preventing floating-point division truncation (e.g. `0.29 / 0.01` dropping an entire lot step).
- **Frank Sortino Lower Partial Moment (LPM) Accuracy**:
  Sortino ratio calculated across all calendar periods using true downside semi-deviation ($\text{DR} = \sqrt{\frac{1}{N}\sum_{t=1}^N \min(0, R_t)^2}$), eliminating day-omission bias.
- **Asset-Agnostic Presets**:
  Pre-configured specifications for Spot Metals (Gold, Silver), Equity Index CFDs (Nasdaq 100, S&P 500, Dow 30), Forex Majors, Crypto CFDs, and CME Futures.

---

## 3. Architecture & Microstructure Pipeline

```
                              [ Parquet Tick Stream ]
                                         │
                                         ▼
                     ┌───────────────────────────────────────┐
                     │           TickStreamRunner            │
                     │  - Zero-cost row-group skipping       │
                     │  - Column auto-detection              │
                     │  - Vectorized pre-processing hook     │
                     └───────────────────┬───────────────────┘
                                         │
                   ┌─────────────────────┴─────────────────────┐
                   │                                           │
                   ▼                                           ▼
      ┌─────────────────────────┐                 ┌─────────────────────────┐
      │   UniversalTickEngine   │                 │      BaseStrategy       │
      │   - Clock State (t)     │                 │   - User Trading Alpha  │
      │   - Pending Queue       │                 │   - Indicators          │
      │   - Resting Order Book  │◄────────────────│   - Signals             │
      │   - MTM & SL/TP Triggers│  Submit Orders  │   - Time Hooks          │
      │   - Deal/Trade Ledgers  │                 └─────────────────────────┘
      └────────────┬────────────┘
                   │
                   ▼
      ┌─────────────────────────────────────────────────────────┐
      │                   PerformanceAuditor                    │
      │   - Dual Drawdown (Balance vs MTM Equity)               │
      │   - Continuous 252-Day Annualized Sharpe & Sortino (LPM)│
      │   - Profit Factor, Expected Value, Win Rate             │
      │   - MAE / MFE Edge Ratio & Slippage Points              │
      └────────────────────────────┬────────────────────────────┘
                                   │
                                   ▼
      ┌─────────────────────────────────────────────────────────┐
      │                  BacktestHTMLReporter                   │
      │   - Responsive Dark-Themed Quantitative Visualizer      │
      │   - Dual-Pane Plotly Equity & Drawdown Curves           │
      │   - Tabbed Searchable Logs (Trades, Deals, Events)      │
      └─────────────────────────────────────────────────────────┘
```

---

## 4. Performance & Microsecond Benchmark

Simulated over real Dukascopy millisecond tick datasets on standard desktop hardware:

| Benchmark Test | Symbol | Ticks Processed | Elapsed Time | Simulation Speed |
|---|---|---|---|---|
| **Spot Gold (XAUUSD)** | `xauusd` | 500,000 ticks | 1.18 sec | **424,451 ticks/sec** |
| **Nasdaq 100 CFD (NQ)** | `usatechidxusd`| 500,000 ticks | 1.18 sec | **422,271 ticks/sec** |

---

## 5. Installation & Prerequisites

The framework requires Python 3.10+ and standard numerical libraries:

```powershell
pip install numpy pandas pyarrow
```

*(No MetaTrader 5, proprietary DLLs, or C++ compilers required.)*

---

## 6. Quickstart: Building a Strategy

Inherit from [`BaseStrategy`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/strategy_base.py#L13-L188) and implement `on_tick`:

```python
from research.backtester.models import Tick, TradeRecord, OrderEventRecord
from research.backtester.strategy_base import BaseStrategy
from research.backtester.engine import UniversalTickEngine
from research.backtester.instrument import Instrument
from research.backtester.commission import PerLotCommission
from research.backtester.slippage import NaturalGapSlippage
from research.backtester.latency import FixedLatency
from research.backtester.runner import TickStreamRunner

class SimpleBreakoutStrategy(BaseStrategy):
    def __init__(self, engine: UniversalTickEngine, lookback: int = 50):
        super().__init__(engine)
        self.lookback = lookback
        self.prices = []

    def on_tick(self, tick: Tick) -> None:
        self.prices.append(tick.mid)
        if len(self.prices) > self.lookback:
            self.prices.pop(0)
        else:
            return

        # Single-position check
        if self.position is not None:
            return

        high = max(self.prices[:-1])
        low = min(self.prices[:-1])

        # Risk-based lot sizing (0.5% risk, 200 ticks SL)
        sl_dist = 200 * self.instrument.tick_size
        tp_dist = 400 * self.instrument.tick_size # 1:2.0 RR
        lots = self.instrument.calc_lots_from_risk(self.balance, 0.005, sl_dist)

        if tick.mid > high:
            self.buy(quantity=lots, sl=tick.ask - sl_dist, tp=tick.ask + tp_dist, tag="BREAKOUT_LONG")
        elif tick.mid < low:
            self.sell(quantity=lots, sl=tick.bid + sl_dist, tp=tick.bid - tp_dist, tag="BREAKOUT_SHORT")

    def on_position_closed(self, trade: TradeRecord) -> None:
        print(f"Trade #{trade.trade_id} closed: Net PnL = ${trade.net_pnl:.2f} via {trade.exit_reason}")

    def on_order_event(self, event: OrderEventRecord) -> None:
        # Real-time lifecycle logging
        if event.event_type.name == "REJECT":
            print(f"Order #{event.order_id} REJECTED: {event.details}")


if __name__ == "__main__":
    # 1. Setup Instrument & Execution Physics
    gold = Instrument.gold()
    engine = UniversalTickEngine(
        instrument=gold,
        initial_balance=100_000.0,
        commission_model=PerLotCommission(11.00), # FTMO Gold $11/lot
        slippage_model=NaturalGapSlippage(),
        latency_model=FixedLatency(50)            # 50ms execution delay
    )

    # 2. Instantiate Strategy
    strat = SimpleBreakoutStrategy(engine, lookback=100)

    # 3. Stream Parquet Ticks
    runner = TickStreamRunner(
        strategy=strat,
        data_source="D:/Developing_quant_system_for_FTMO/data/dukascopy_ticks",
        symbol="xauusd",
        max_ticks=200_000
    )
    results = runner.run()

    # 4. Generate Interactive HTML Report
    engine.generate_html_report("gold_breakout_report.html")
```

---

## 7. Command-Line Interface (CLI) Usage

The framework includes a standalone CLI runner: [`run_backtest.py`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/run_backtest.py).

### Basic Backtest
```powershell
python research/backtester/run_backtest.py --symbol xauusd --max-ticks 500000
```

### Full Institutional Backtest with Visualizer & CSV Exports
```powershell
python research/backtester/run_backtest.py `
  --symbol usatechidxusd `
  --balance 100000 `
  --risk 0.005 `
  --sl-ticks 300 `
  --rr 2.0 `
  --latency 50 `
  --slippage natural `
  --html nq_audit_report.html `
  --show-trades `
  --show-deals `
  --show-events
```

### Key CLI Parameters
| Flag | Default | Description |
|---|---|---|
| `--symbol` | `xauusd` | Traded instrument symbol (`xauusd`, `usatechidxusd`, `eurusd`, `btcusd`). |
| `--balance` | `100000.0` | Starting cash balance in USD. |
| `--risk` | `0.005` | Risk per trade fraction (e.g. `0.005` = $0.5\%$). |
| `--sl-ticks` | `200.0` | Stop loss distance in discrete price ticks. |
| `--rr` | `2.0` | Reward-to-risk ratio. |
| `--latency` | `50` | In-flight network routing delay in milliseconds. |
| `--commission` | Auto | Round-trip commission override in USD per lot. |
| `--slippage` | `natural` | Slippage physics: `natural` (gap), `fixed` (penalty), or `zero`. |
| `--html` | `None` | Filepath to output interactive HTML report. |
| `--pulse` | `None` | Sub-tick time progression mode (`1ms` or `1us`). |
| `--export-csv` | `None` | Prefix to export 4 complete CSV ledgers (trades, deals, events, equity). |

---

## 8. Institutional Ledgers & Audit DataFrames

At any point during or after simulation, audit ledgers can be extracted as standard pandas DataFrames:

```python
# Completed Round-Turn Trades (TradeRecord)
trades_df = engine.get_trades_df()

# Individual Execution Deals (DealRecord - Entries and Exits)
deals_df = engine.get_deals_df()

# Order Event Lifecycle Audit (OrderEventRecord - Submit, Accept, Fill, Cancel, Reject)
events_df = engine.get_order_events_df()

# Periodic Floating Equity & Drawdown Snapshots
equity_df = engine.get_equity_df()
```

### Printable ASCII Tables
- `engine.print_trade_log(limit=20)`: Formatted executed trades table.
- `engine.print_deals_log(limit=20)`: Formatted fills/deals ledger.
- `engine.print_order_events_log(limit=20)`: Formatted order lifecycle transitions.
- `PerformanceAuditor.print_performance_card(audit_results)`: Institutional KPI card.

---

## 9. Interactive HTML Visualizer Report

The framework natively outputs a self-contained, responsive, dark-themed HTML dashboard ([`BacktestHTMLReporter`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/report.py#L19-L893)):

- **Dual Plotly Timeseries**:
  - Top: Continuous Mark-to-Market Floating Equity vs. Closed Balance vs. High-Water Mark.
  - Bottom: Underwater Drawdown Curve (% Peak-to-Trough) with shaded risk zones.
- **Institutional Statistical Matrix**:
  - Annualized Sharpe Ratio (continuous 252-day basis, zero day-omission bias).
  - Annualized Sortino Ratio (exact Lower Partial Moment semi-deviation).
  - Calmar Ratio, Profit Factor, Realized RR, Expectancy ($).
  - Dual Drawdown figures (Max Balance DD vs Max MTM Equity DD).
  - Microstructure Execution Analytics (MAE, MFE, Edge Ratio, Entry/Exit Slippage Points).
- **Searchable Tabbed Ledgers**:
  - Tab 1: Completed Trades (with duration, PnL, return %, SL/TP, slippage, MAE/MFE).
  - Tab 2: Execution Deals (individual IN/OUT fills with commissions and realized PnL).
  - Tab 3: Order Events Lifecycle (audit trail with timestamps, prices, and rejection reasons).

---

## 10. Sub-Tick & High-Frequency Scheduling (1ms / 1μs)

For quantitative strategies requiring off-tick clock advancement (e.g. L2 order book queues, depth updates, or microsecond timers), the runner supports continuous pulse scheduling:

```python
runner = TickStreamRunner(
    strategy=strat,
    data_source="data/ticks",
    pulse_interval="1ms" # or "1us"
)
```

During pulses, the following lifecycle hooks trigger synchronously:
- `on_every_1ms(timestamp)`: 1-millisecond clock interval.
- `on_every_1us(timestamp)`: 1-microsecond clock interval.
- `on_time(timestamp)`: Generic time advancement hook.

---

## 11. Current Limitations & Architectural Boundary Conditions

To maintain absolute quantitative honesty and transparency, the following design boundaries are intentionally enforced:

1. **Single-Position Netting Architecture (No Hedging)**:
   - The engine operates under an institutional netting model. Only one active position per symbol can exist at a time.
   - Submitting an entry order while a position is already open (or while an entry order is pending) results in an immediate [`OrderEventType.REJECT`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L68). Hedging (holding simultaneous Long and Short positions in the same instrument) is strictly prohibited.
2. **Top-of-Book (L1 / BBO) Liquidity Model**:
   - Market orders fill against the Best Bid / Best Ask quote.
   - For standard retail and prop firm sizing ($\le 50$ lots), fills are assumed to be absorbed at the Top of the Book. Multi-level L2/L3 order book depth walking (partial fill fragmentation across deep price ladders) is not modeled in the core L1 engine.
3. **Single-Instrument Execution Engine**:
   - Each `UniversalTickEngine` instance simulates a single symbol's matching mechanics.
   - Multi-asset portfolio backtesting is accomplished by coordinating multiple engine instances at the strategy/orchestrator level, rather than through a cross-asset centralized order book.
4. **Weekend & Holiday Gap Handling**:
   - In periods where data contains gaps (e.g. weekend closures), pending limit/stop orders execute on the first incoming quote of the new session ($t_{\text{next}}$) with natural gap slippage.

---

## 12. File Directory Map

```
research/backtester/
├── __init__.py          # Module exports
├── config.py            # Global symbol registry, FTMO specifications, and presets
├── commission.py        # PerLot, Percentage, PerContract, and Zero commission models
├── engine.py            # UniversalTickEngine: discrete-event matching and MTM ledger
├── instrument.py        # Instrument class: contract size, tick value, sizing math
├── latency.py           # FixedLatency, JitterLatency, ZeroLatency models
├── metrics.py           # PerformanceAuditor: Sharpe, Sortino (LPM), Dual DD, MAE/MFE
├── models.py            # Tick, Order, Position, DealRecord, OrderEventRecord, TradeRecord
├── report.py            # BacktestHTMLReporter: interactive Plotly HTML visualizer
├── run_backtest.py      # CLI execution entry point
├── runner.py            # TickStreamRunner: high-speed streaming Parquet runner
├── slippage.py          # NaturalGapSlippage, FixedSlippage, ZeroSlippage models
├── strategy_base.py     # BaseStrategy: abstract strategy interface and trading API
└── docs/                # Sphinx & ReadTheDocs technical documentation
    ├── conf.py          # Sphinx build configuration
    ├── requirements.txt # Documentation dependencies
    ├── index.rst        # Master documentation index
    ├── architecture.rst # Discrete-event architecture
    ├── microstructure.rst # Causality & execution physics
    ├── sub_tick_engine.rst # Sub-tick & high-frequency scheduling
    ├── quickstart.rst   # Strategy authoring guide
    ├── cli.rst          # CLI execution manual
    ├── api_reference.rst# Python API reference (autodoc)
    └── limitations.rst  # Architectural boundaries
```

---

## 13. Test Suite Verification

All engine components are verified by a 36-test automated regression suite:

```powershell
python -m unittest discover -s research/tests -p "test_*.py" -v
```
```
Ran 36 tests in 2.441s
OK
```
Tests cover zero-lookahead causality, sub-tick time synchronization, dual drawdown accounting, natural gap slippage, order lifecycle audits, Sortino LPM semi-deviation, and IEEE 754 floating-point sizing precision.

---

## 14. Full Sphinx & ReadTheDocs Documentation

Complete institutional documentation for the framework is built using Sphinx and configured for **ReadTheDocs** (v2 configuration at [`.readthedocs.yaml`](file:///D:/Developing_quant_system_for_FTMO/.readthedocs.yaml)):

- **Root Config**: [`.readthedocs.yaml`](file:///D:/Developing_quant_system_for_FTMO/.readthedocs.yaml)
- **Sphinx Documentation Root**: [`research/backtester/docs/`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/)
  - [`research/backtester/docs/conf.py`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/conf.py): Sphinx configuration (`sphinx_rtd_theme`, autodoc, napoleon, mathjax, viewcode)
  - [`research/backtester/docs/requirements.txt`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/requirements.txt): Build dependencies
  - [`research/backtester/docs/index.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/index.rst): Master documentation index
  - [`research/backtester/docs/architecture.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/architecture.rst): Discrete-event matching engine architecture & streaming pipeline
  - [`research/backtester/docs/microstructure.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/microstructure.rst): Next-quote causality invariant, BBO spreads, gap slippage & commissions
  - [`research/backtester/docs/sub_tick_engine.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/sub_tick_engine.rst): Sub-tick time progression (1ms / 1μs) and L2/L3 queue hooks
  - [`research/backtester/docs/quickstart.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/quickstart.rst): Quickstart tutorial for strategy authors
  - [`research/backtester/docs/cli.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/cli.rst): Command-Line Interface (CLI) manual & options
  - [`research/backtester/docs/api_reference.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/api_reference.rst): Python API reference with full autodoc extraction
  - [`research/backtester/docs/limitations.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/limitations.rst): Architectural boundary conditions & netting specifications

To build the HTML documentation locally:
```powershell
python -m sphinx -b html research/backtester/docs research/backtester/docs/_build/html
```
The compiled HTML site is generated at [`research/backtester/docs/_build/html/index.html`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/_build/html/index.html).

