Metadata-Version: 2.4
Name: forex-precision-backtester
Version: 1.0.2
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: duckdb>=1.0.0
Requires-Dist: numba>=0.58.0
Requires-Dist: plotly>=5.0.0
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. How to Provide Market Data (3 Ingestion Pathways)](#7-how-to-provide-market-data-3-ingestion-pathways)
- [8. Command-Line Interface (CLI) Usage](#8-command-line-interface-cli-usage)
- [9. Institutional Ledgers & Audit DataFrames](#9-institutional-ledgers--audit-dataframes)
- [10. Interactive HTML Visualizer Report](#10-interactive-html-visualizer-report)
- [11. Sub-Tick & High-Frequency Scheduling (1ms / 1μs)](#11-sub-tick--high-frequency-scheduling-1ms--1μs)
- [12. Current Limitations & Architectural Boundary Conditions](#12-current-limitations--architectural-boundary-conditions)
- [13. File Directory Map](#13-file-directory-map)
- [14. Test Suite Verification](#14-test-suite-verification)
- [15. Standalone Packaging & Publishing Guide](#15-standalone-packaging--publishing-guide)

---

## 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.
5. **Mandatory Structured BBO Market Data Invariant**:
   - The matching engine operates strictly on two-sided Best Bid & Offer (BBO) market data (`timestamp`, `bid`, `ask`, `bid_volume`, `ask_volume`). Single-price trades, interpolated ticks, or OHLC bar data are structurally prohibited because real-world execution physics (Buy on Ask, Sell on Bid), continuous MTM valuation, spread friction, and gap slippage cannot exist without genuine BBO quotes.
   - **Complete Strategy Decoupling**: A trading strategy may be driven by ML models, order-flow indicators, or completely random coin flips without market data (e.g. Monte Carlo placebo tests). However, **the Engine strictly requires the underlying structured BBO stream** to act as the reality substrate that validates, fills, slips, taxes, and marks those actions.

---

## 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:/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:/backtester/models.py#L150-L188): Discrete exchange execution fills (IN/OUT).
  3. [`OrderEventRecord`](file:///D:/backtester/models.py#L191-L231): Order lifecycle events (`SUBMIT`, `ACCEPT`, `FILL`, `MODIFY`, `CANCEL`, `REJECT`).
  4. [`AccountSnapshot`](file:///D:/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 is published on PyPI as `forex-precision-backtester` (under the import namespace `backtester`). It requires Python 3.9+ and standard numerical libraries:

```bash
# Standard installation from PyPI
pip install forex-precision-backtester

# Installation with test suite dependencies
pip install "forex-precision-backtester[test]"
```

For local or editable installation from source:
```bash
git clone <repo-url> backtester
cd backtester
pip install -e ".[test]"
```

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


---

## 6. Quickstart: Building a Strategy

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

```python
from backtester.models import Tick, TradeRecord, OrderEventRecord
from backtester.strategy_base import BaseStrategy
from backtester.engine import UniversalTickEngine
from backtester.instrument import Instrument
from backtester.commission import PerLotCommission
from backtester.slippage import NaturalGapSlippage
from backtester.latency import FixedLatency
from 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="data/xauusd",
        symbol="xauusd",
        max_ticks=200_000
    )
    results = runner.run()

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

---

## 7. How to Provide Market Data (3 Ingestion Pathways)

The backtester is an institutional exchange matching engine that sits strictly between **historical market data** and your **trading strategy**. The engine requires **two-sided BBO (Best Bid & Offer)** market data to calculate fill prices, spreads, slippage, and continuous mark-to-market equity.

You can provide market data through three distinct pathways:

### Pathway 1: High-Performance Parquet Streaming (Recommended)
This is the fastest, institutional-grade pathway. It streams hundreds of millions of ticks directly from disk using Apache Parquet zero-copy row-group chunking (>420,000 ticks/sec with minimal RAM usage).

You pass `data_source` into [`TickStreamRunner`](file:///D:/backtester/runner.py):

```python
from backtester.runner import TickStreamRunner

# Option A: Point to a directory containing one or more .parquet files
runner = TickStreamRunner(
    strategy=strat,
    data_source="path/to/parquet_folder/",  # Auto-discovers all matching *.parquet files
    symbol="xauusd",
    start_date="2024-01-01",               # Optional UTC date filter (YYYY-MM-DD)
    end_date="2024-06-30"
)

# Option B: Point directly to a single .parquet file
runner = TickStreamRunner(
    strategy=strat,
    data_source="path/to/xauusd_ticks_2024.parquet"
)

# Option C: Provide an explicit list of .parquet file paths
runner = TickStreamRunner(
    strategy=strat,
    data_source=[
        "data/xauusd_jan.parquet",
        "data/xauusd_feb.parquet"
    ]
)

# Launch high-speed simulation
audit_results = runner.run()
```

### Pathway 2: Direct In-Memory Tick Feeding (`engine.on_tick`)
If you have ticks in a pandas DataFrame, a CSV iterator, a WebSocket stream, or custom memory arrays, you can bypass `TickStreamRunner` and feed ticks directly into the engine's event loop:

```python
from backtester.models import Tick
from backtester.metrics import PerformanceAuditor

# Example: Iterating over your own data structure or DataFrame
for row in my_ticks_iterable:
    # Construct canonical BBO Tick
    tick = Tick(
        timestamp=int(row["timestamp"]),  # POSIX epoch integer in ms (or us)
        bid=float(row["bid"]),            # Best Bid price
        ask=float(row["ask"]),            # Best Ask price
        bid_volume=float(row.get("bid_volume", 1.0)),
        ask_volume=float(row.get("ask_volume", 1.0))
    )
    
    # 1. Advance engine exchange matching state (processes pending orders & MTM)
    engine.on_tick(tick)
    
    # 2. Forward tick to strategy for signal evaluation
    strategy.on_tick(tick)

# Settle final state and audit
engine.flush_completed_state()
audit = PerformanceAuditor.audit(engine)
```

### Pathway 3: Command-Line Interface (`--data`)
Feed custom data files or folders directly via CLI arguments:

```bash
# Point to a specific Parquet archive
forex-precision-backtester --symbol xauusd --data path/to/my_ticks.parquet

# Point to a directory of partitioned tick files
fpb --symbol eurusd --data C:/market_data/forex/ --start 2024-01-01 --end 2024-03-31
```

---

### Mandatory BBO Schema & Column Auto-Detection

The runner inspects incoming Parquet schemas and **automatically maps** common column naming conventions without requiring manual data restructuring:

| Canonical BBO Field | Expected Type | Auto-Detected Column Aliases |
|---|---|---|
| `timestamp` | `int64` (ms/μs) or `datetime64[ns]` | `timestamp`, `time`, `datetime`, `ts` |
| `bid` | `float64` | `bid`, `bid_price`, `bidprice`, `bp` |
| `ask` | `float64` | `ask`, `ask_price`, `askprice`, `ap` |
| `bid_volume` | `float64` / `int64` | `bid_volume`, `bid_vol`, `bidvol`, `bvol`, `volume`, `vol` |
| `ask_volume` | `float64` / `int64` | `ask_volume`, `ask_vol`, `askvol`, `avol`, `volume`, `vol` |

*(If `bid_volume` or `ask_volume` are missing from the file, the runner automatically assigns a default depth of `1.0` lot).*

---

### Data Conversion Recipe: Converting Raw CSV to Parquet

If you have raw CSV tick data from Dukascopy, MetaTrader 5, TrueFX, or Databento, convert it into compressed, high-performance Parquet in seconds using pandas:

```python
import pandas as pd

# 1. Read raw CSV
df = pd.read_csv("raw_ticks_xauusd.csv")

# 2. Ensure timestamps are integer milliseconds (or parse datetime strings)
if not pd.api.types.is_integer_dtype(df["timestamp"]):
    df["timestamp"] = pd.to_datetime(df["timestamp"]).astype("int64") // 10**6

# 3. Save as Snappy-compressed Parquet with high-speed row-groups
df[["timestamp", "bid", "ask", "bid_volume", "ask_volume"]].to_parquet(
    "xauusd_ticks_clean.parquet",
    compression="snappy",
    row_group_size=500_000,
    index=False
)
print("Successfully generated high-speed Parquet tick archive!")
```

---

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

The package installs console command entry points (`backtester`, `forex-precision-backtester`, and `fpb`) and can also be run directly as a module:

### Basic Backtest
```bash
# Using installed console script:
backtester --symbol xauusd --max-ticks 500000

# Or via Python module:
python -m backtester.run_backtest --symbol xauusd --max-ticks 500000
```

### Full Institutional Backtest with Visualizer & CSV Exports
```bash
backtester \
  --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). |

---

## 9. 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.

---

## 10. Interactive HTML Visualizer Report

The framework natively outputs a self-contained, responsive, dark-themed HTML dashboard ([`BacktestHTMLReporter`](file:///D:/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).

---

## 11. 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.

---

## 12. 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:/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.

---

## 13. File Directory Map

```
backtester/
├── __init__.py          # Module exports (universal high-level API)
├── commission.py        # PerLot, Percentage, PerContract, and Zero commission models
├── config.py            # Global symbol registry, FTMO specifications, and presets
├── engine.py            # UniversalTickEngine: discrete-event matching and MTM ledger
├── instrument.py        # Instrument class: contract size, tick value, sizing math
├── jit_engine.py        # JITTickEngine: Numba compiled vectorized execution wrapper
├── jit_kernel.py        # Numba @njit matching engine core
├── 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 & DuckDB runner
├── slippage.py          # NaturalGapSlippage, FixedSlippage, ZeroSlippage models
├── strategy_base.py     # BaseStrategy: abstract strategy interface and trading API
├── tests/               # 28-test automated verification suite
├── pyproject.toml       # PEP 517/621 packaging metadata and CLI scripts
├── LICENSE              # MIT License
└── README.md            # Comprehensive documentation & API manual
```

---

## 14. Test Suite Verification

All engine components, execution physics, and JIT parity are verified by the automated pytest suite:

```bash
pytest tests/ -v
```

```text
tests/test_causality.py ....                                             [ 14%]
tests/test_dual_drawdown.py ..                                           [ 21%]
tests/test_instrument.py .......                                         [ 46%]
tests/test_jit_parity.py ....                                            [ 60%]
tests/test_models.py ......                                              [ 82%]
tests/test_runner_and_cli.py .                                           [ 85%]
tests/test_slippage_commissions.py ....                                  [100%]

============================= 28 passed in 12.99s =============================
```

Tests cover zero-lookahead causality, sub-tick time synchronization, dual drawdown accounting, natural gap slippage, broker commissions, JIT / OOP parity, order lifecycle audits, Sortino LPM semi-deviation, and IEEE 754 floating-point sizing precision.

---

## 15. Standalone Packaging & Publishing Guide

### Building Distribution Packages
```bash
python -m build
```
This produces PEP 517 compliant source distribution (`.tar.gz`) and binary wheel (`.whl`) archives in `dist/`.

### Verifying Distribution Integrity
```bash
python -m twine check dist/*
```

### Publishing to PyPI
```bash
# Upload to TestPyPI (Staging)
python -m twine upload --repository testpypi dist/*

# Upload to Production PyPI
python -m twine upload dist/*
```



