diff --git a/README.md b/README.md
index cd409cd..29bda23 100644
--- a/README.md
+++ b/README.md
@@ -8,14 +8,18 @@
## 📑 Table of Contents
1. [Architecture & Design Philosophy](#1-architecture--design-philosophy)
2. [Directory Structure](#2-directory-structure)
-3. [Installation & Quick Setup Guide](#3-installation--quick-setup-guide)
+3. [Installation & Build](#3-installation--build)
4. [Downloading & Storing 100% Broker Data](#4-downloading--storing-100-broker-data)
5. [Implementing Custom Strategies](#5-implementing-custom-strategies)
6. [Simulation Modes (How to Choose the Right Mode)](#6-simulation-modes-how-to-choose-the-right-mode)
+ - [6.1 Real Broker Tick Replay (TickMode.REAL_TICKS)](#61-real-broker-tick-replay-tickmodereal_ticks)
7. [Execution Latency & Slippage Simulation](#7-execution-latency--slippage-simulation)
-8. [Interactive Step-by-Step & Visual Replay](#8-interactive-step-by-step--visual-replay)
-9. [Optimization & Hyperopt Guide](#9-optimization--hyperopt-guide)
-10. [Test Suite & Verification](#10-test-suite--verification)
+8. [Overnight Financing & Rollover Swap Mechanics (24/7 vs. Traditional Markets)](#8-overnight-financing--rollover-swap-mechanics-247-vs-traditional-markets)
+9. [MT5 Strategy Tester Parity Engine (Order Lifecycle & Accounting)](#9-mt5-strategy-tester-parity-engine-order-lifecycle--accounting)
+10. [Interactive Step-by-Step & Visual Replay](#10-interactive-step-by-step--visual-replay)
+11. [Optimization & Hyperopt Guide](#11-optimization--hyperopt-guide)
+12. [Engine Updates & Porting Guide (Changelog for Clones)](#12-engine-updates--porting-guide-changelog-for-clones)
+13. [Test Suite & Verification](#13-test-suite--verification)
---
@@ -82,145 +86,27 @@ edge_engine/
---
-## 3. Installation & Quick Setup Guide
+## 3. Installation & Build
-### 3.1 Prerequisites
+### Requirements
+- **OS**: Windows 10/11 64-bit
+- **Compiler**: Visual Studio 2022 (MSVC C++17) with CMake
+- **Python**: 3.10 – 3.13 (64-bit)
-Before building EdgeEngine, ensure you have the following installed on your system:
+### Compiling and Installing
+Open PowerShell in the `edge_engine` directory:
-| Component | Minimum Version | Notes |
-| :--- | :--- | :--- |
-| **Python** | 3.10 – 3.13 (64-bit) | Standard CPython distribution recommended |
-| **CMake** | 3.18+ | Ensure `cmake` is added to your system `PATH` |
-| **C++17 Compiler** | MSVC (VS 2022) / GCC 9+ / Clang 10+ | Supports AVX2 vectorization instructions |
-| **Git** | 2.30+ | For cloning the repository and submodules |
+```powershell
+# Navigate to the edge_engine directory
+cd "c:\Users\Ethan\Desktop\projects\new leaf indicator\edge_engine"
-#### Compiler Details by Platform
-- **Windows**: Install [Visual Studio 2022](https://visualstudio.microsoft.com/) (Community or Professional) with the **"Desktop development with C++"** workload selected, or the standalone **Visual Studio Build Tools**.
-- **Linux (Debian/Ubuntu)**:
- ```bash
- sudo apt update && sudo apt install -y build-essential cmake python3-dev
- ```
-- **macOS**:
- ```bash
- xcode-select --install
- brew install cmake
- ```
-
----
-
-### 3.2 Step-by-Step Setup
-
-#### Step 1: Clone the Repository
-```bash
-git clone https://github.com/dante-bills1/edge_lab.git
-cd edge_lab
+# Compile and install directly into your active Python environment
+pip install . --no-build-isolation --no-deps
```
-#### Step 2: Create and Activate a Virtual Environment
-It is recommended to build and run inside an isolated virtual environment:
-
-- **Windows (PowerShell)**:
- ```powershell
- python -m venv .venv
- .\.venv\Scripts\Activate.ps1
- ```
-- **Linux / macOS (Bash/Zsh)**:
- ```bash
- python3 -m venv .venv
- source .venv/bin/activate
- ```
-
-#### Step 3: Upgrade Pip & Install Build Toolchain
-EdgeEngine utilizes `scikit-build-core` and `pybind11` for high-performance C++ compilation:
-```bash
-python -m pip install --upgrade pip
-pip install "scikit-build-core>=0.9" "pybind11>=2.12"
-```
-
-#### Step 4: Build and Install EdgeEngine
-
-Choose one of the following install modes:
-
-- **Option A: Development / Editable Install (Recommended for research & iteration)**
- Compiles the C++ extension in-place so edits to Python files are immediately reflected:
- ```bash
- pip install -e . --no-build-isolation
- ```
-
-- **Option B: Full Install with Development & Testing Dependencies**
- Installs `pytest`, `pandas`, `numpy`, and benchmarking suites:
- ```bash
- pip install -e ".[dev]" --no-build-isolation
- ```
-
-- **Option C: Standard Production Build**
- ```bash
- pip install .
- ```
-
----
-
-### 3.3 Verification
-
-1. **Smoke Test the Python & C++ Extension Import**:
- ```powershell
- python -c "import edge_tester as et, edge_engine as ee; print('EdgeEngine C++ core and Python package loaded successfully!')"
- ```
-
-2. **Run the Automated Test Suite**:
- Execute the test suite to verify matching engine parity, accounting rules, and latency queues:
- ```powershell
- pytest tests/ -v
- ```
-
----
-
-### 3.4 60-Second Quick Start
-
-You can run an end-to-end backtest on synthetic or broker data in seconds:
-
-```python
-import numpy as np
-import pandas as pd
-import edge_tester as et
-
-# 1. Generate 1,000 synthetic bars for instant testing
-np.random.seed(42)
-n_bars = 1000
-close = 100.0 + np.cumsum(np.random.randn(n_bars) * 0.2)
-high = close + np.random.rand(n_bars) * 0.3
-low = close - np.random.rand(n_bars) * 0.3
-open_p = close + np.random.randn(n_bars) * 0.1
-
-df = pd.DataFrame({
- "time": np.arange(n_bars, dtype=np.int64),
- "open": open_p,
- "high": high,
- "low": low,
- "close": close,
- "tick_volume": np.full(n_bars, 100, dtype=np.int64),
- "spread": np.full(n_bars, 10, dtype=np.int32),
-})
-
-# 2. Configure Instrument Specs and Tester
-spec = et.SymbolSpec()
-spec.point = 0.01
-spec.spread_val = 0.10
-
-cfg = et.TesterConfig()
-cfg.initial_deposit = 10_000.0
-cfg.leverage = 100.0
-cfg.tick_mode = et.TickMode.EVERY_TICK
-
-# 3. Instantiate Engine and Run Test
-tester = et.Tester(cfg, spec)
-results = tester.run_test(df)
-
-print("Backtest Complete!")
-print(f"Ending Balance: ${results['ending_balance']:,.2f}")
-print(f"Total Trades: {results['total_trades']}")
-print(f"Profit Factor: {results['profit_factor']:.2f}")
+Verify the installation:
+```powershell
+python -c "import edge_tester as et, edge_engine as ee; print('EdgeEngine installed successfully!')"
```
---
@@ -440,6 +326,76 @@ flowchart TD
| **`TickMode.EVERY_TICK`** | 12 ticks / bar | **Moderate** (~50k bars/sec) | MT5's fractal price generator synthesizing 12 price states across 3 sub-intervals. Ideal for precision backtesting trailing stops, breakeven triggers, and scalping logic. |
| **`TickMode.REAL_TICKS`** | Every actual tick | **Exhaustive** | Pure replay of recorded real broker tick history (bid, ask, tick volume). Used for high-frequency strategies and final validation runs. |
+### 6.1 Real Broker Tick Replay (`TickMode.REAL_TICKS`)
+
+While synthetic models (`OPEN_PRICES`, `OHLC_M1`, `EVERY_TICK`) generate artificial intrabar paths from OHLC bar summaries, `TickMode.REAL_TICKS` streams **100% genuine broker ticks** (`time_msc`, `bid`, `ask`, `last`, `volume`, `flags`) directly into the matching engine.
+
+```mermaid
+flowchart LR
+ MT5["MT5 Terminal Server
(copy_ticks_range)"] --> Downloader["download_broker_ticks.py"]
+ Downloader --> Parquet["tick_data_cache/*.parquet
(Snappy Compressed)"]
+ Parquet --> CppEngine["EdgeEngine C++ Core
(Two-Pointer Zero-Copy Replay)"]
+ CppEngine --> Match["Intrabar Order Matching
(SL / TP / Trailing Stops / Latency)"]
+```
+
+#### Why Real Ticks are Essential
+On high-volatility instruments (such as Deriv Jump & Volatility indices, or during Forex news releases), synthetic fractal models smooth out intrabar spikes. Real broker feeds, however, contain microsecond-level volatility bursts that can prematurely trigger tight Stop Losses or dynamic Trailing Stops.
+
+In our production validation of Jump 10 Index:
+- **`OPEN_PRICES`**: Signals and trailing stops only evaluate at candle close. This produces theoretical backtest profits without intrabar stopouts.
+- **`REAL_TICKS` / MT5 "Every tick based on real ticks"**: Micro-spikes continuously hit trailing stops intrabar. This reduces realized profits to ~30% of open-price theoretical metrics, but reflects 100% genuine live trading dynamics.
+
+#### C++ Zero-Copy Execution Architecture
+1. **$O(N)$ Two-Pointer Grouping**: Broker ticks are aligned with OHLC candle timestamps in linear time in C++ without incurring Python per-tick overhead.
+2. **First-Tick `OnBar()` Triggering**: When a new candle opens, `OnBar()` is invoked on the *very first tick* of that candle. This guarantees that new market orders execute at the true bar open price, while all subsequent intrabar ticks stream through `OrderBook::on_price_update` to manage trailing stops and pending orders.
+3. **Sub-Second Throughput**: Replays over 600,000 real broker ticks in **~1.1 seconds**.
+
+#### Automated Broker Tick Downloader
+Use the automated CLI downloader to fetch genuine broker tick data directly from MetaTrader 5:
+
+```powershell
+python backtest_suite/download_broker_ticks.py `
+ --symbol "Jump 10 Index" `
+ --days 7 `
+ --output "backtest_suite/tick_data_cache/jump_10_index_7d_ticks.parquet"
+```
+
+#### Running Real-Tick Backtests via CLI
+```powershell
+# Run TrendFinder Leaf using 100% genuine broker ticks
+python strategies/trendfinder_leaf/run_backtest.py `
+ --symbol "Jump 10 Index" `
+ --data "backtest_suite/historical_data_cache/jump_10_index_100k_m5.parquet" `
+ --tick-mode REAL_TICKS `
+ --ticks-path "backtest_suite/tick_data_cache/jump_10_index_7d_ticks.parquet"
+```
+
+#### Running Real-Tick Backtests in Python API
+```python
+import edge_tester as et
+import pandas as pd
+
+# 1. Load historical bars and real broker ticks
+bars_df = pd.read_parquet("backtest_suite/historical_data_cache/jump_10_index_100k_m5.parquet")
+ticks_df = pd.read_parquet("backtest_suite/tick_data_cache/jump_10_index_7d_ticks.parquet")
+
+# 2. Configure Tester with REAL_TICKS
+spec = et.SymbolSpec()
+spec.point = 0.01
+spec.spread_val = 0.10
+
+cfg = et.TesterConfig()
+cfg.tick_mode = et.TickMode.REAL_TICKS
+
+# 3. Execute
+tester = et.Tester(cfg, spec)
+results = tester.run(bars_df, ticks_df)
+
+print(f"Trades Executed: {results['total_trades']}")
+print(f"Net Profit: ${results['net_profit']:,.2f}")
+print(f"Profit Factor: {results['profit_factor']:.2f}")
+```
+
---
## 7. Execution Latency & Slippage Simulation
@@ -491,7 +447,96 @@ When an order is submitted at time $t$, it is assigned an execution time $t_{\te
---
-## 8. Interactive Step-by-Step & Visual Replay
+## 8. Overnight Financing & Rollover Swap Mechanics (24/7 vs. Traditional Markets)
+
+In MetaTrader 5, holding an open position past the end of the trading day incurs an overnight financing cost (or credit) known as **Swap**. `EdgeEngine` strictly replicates MT5's exact daily rollover schedule and financing accounting.
+
+### Key Rules of the Swap Engine:
+
+1. **Daily Rollover Timing (00:00 Server Time)**:
+ - **Naive Mistake**: Many simplistic backtesting scripts mistakenly deduct `swap * volume` on every bar or tick. When testing on M1 or M5 candles, this charges swap hundreds of times per day, completely draining account capital artificially.
+ - **MT5 Parity**: In `EdgeEngine`, swaps are applied strictly once per elapsed calendar day (`time / 86400`). Holding a trade for 288 M5 bars within the same day incurs zero swap until midnight rollover.
+
+2. **Floating Swap Accumulation vs. Realized Cash Balance**:
+ - Accrued swaps do **not** prematurely reduce the cash balance (`account.balance`).
+ - Instead, swaps accumulate continuously in the position entity's floating swap field (`pos.swap`), reducing floating equity.
+ - The swap charge is only realized into the cash balance when an exit deal occurs (`DEAL_ENTRY_OUT` or Netting position reduction).
+
+3. **The 3x Triple Rollover Schedule & Weekend Financing**:
+ - **Traditional 5-Day Markets (Forex, Metals, Commodities)**:
+ Traditional currency pairs operate on a **T+2 settlement cycle** (trades settle 2 business days after execution). A position held open from Wednesday to Thursday rolls settlement from Friday to Monday. Because commercial banks and interbank clearing systems are closed over the weekend, **Wednesday night carries a 3x swap multiplier** (covering Wednesday, Saturday, and Sunday), while Saturday and Sunday carry 0 swap.
+ - Configuration: `spec.swap_rollover3days = 3` (`DAY_WEDNESDAY`).
+ - **Continuous 24/7 Synthetic Markets (e.g., Deriv Synthetics)**:
+ Synthetic indices (Volatility, Crash, Boom, Jump) run algorithmically 24 hours a day, 7 days a week, 365 days a year without market closures or weekend bank holidays.
+ - **Triple swap does NOT apply to Deriv synthetic indices.**
+ - Swaps are charged flat at $1\times$ every day (including Saturday and Sunday).
+ - Configuration: `spec.swap_rollover3days = -1` (disables 3x rollover).
+ - **Cryptocurrency Pairs (BTC, ETH, Altcoins) Across Brokers**:
+ - **Native Crypto Exchanges (Binance, Bybit, OKX)**: Trade 24/7/365 with continuous 8-hour funding rates. **There is no 3x swap.**
+ - **Deriv Crypto**: Runs 24/7 with a flat $1\times$ daily rollover (`spec.swap_rollover3days = -1`).
+ - **Traditional MT5 CFD Brokers (e.g., IC Markets, Pepperstone, Exness, FP Markets)**:
+ > [!WARNING]
+ > **Crypto CFDs on Retail Brokers May Incur 3x Swap!**
+ > Even though cryptocurrency markets run 24/7, many retail MT5 Forex/CFD brokers settle liquidity provider credit lines and fiat currency legs (like USD in BTCUSD) through traditional banking rails that close on weekends.
+ > Consequently, many brokers configure their MT5 servers with **Friday 3x swap (`swap_rollover3days = 5`)** or **Wednesday 3x swap (`swap_rollover3days = 3`)** for Crypto CFDs!
+ > Always verify your broker's symbol specification in MT5: `Market Watch` $\to$ Right-click symbol $\to$ `Specification` $\to$ `3-days swap`.
+
+### Python Symbol Specification Setup
+
+```python
+import edge_tester as et
+
+spec = et.SymbolSpec()
+spec.swap_mode = 2 # 0 = disabled, 1 = points, 2 = currency/money
+spec.swap_long = -15.0 # -$15.00 per lot per night for long positions
+spec.swap_short = 5.20 # +$5.20 per lot per night for short positions
+
+# Rollover schedule:
+# -1 = Continuous 24/7 (Deriv synthetic indices, native crypto - flat 1x every day)
+# 3 = Traditional Forex (3x Wednesday rollover, 0x Saturday/Sunday)
+# 5 = CFD Crypto / Indices (3x Friday rollover on traditional retail brokers)
+spec.swap_rollover3days = -1
+
+cfg = et.TesterConfig()
+cfg.enable_swaps = True # Toggle swap accruals during backtests
+```
+
+---
+
+## 9. MT5 Strategy Tester Parity Engine (Order Lifecycle & Accounting)
+
+EdgeEngine has been reverse-engineered and audited directly against MetaTrader 5's execution binaries (`metatester64.exe` / `terminal64.exe`) to guarantee 100% execution parity.
+
+### 1. Stop-Limit Orders (`ORDER_TYPE_BUY_STOP_LIMIT` / `ORDER_TYPE_SELL_STOP_LIMIT`)
+Unlike standard stop or limit orders, Stop-Limit orders feature two distinct price targets:
+1. `price_open` (Stop Trigger Price)
+2. `price_stoplimit` (Limit Order Price)
+
+When market price touches `price_open`, the order is **not** immediately executed at market. Instead, MT5 transitions the order into an active pending Limit Order (`ORDER_TYPE_BUY_LIMIT` / `ORDER_TYPE_SELL_LIMIT`) placed at `price_stoplimit`. `EdgeEngine` emulates this exact two-stage state transition and fires `TRADE_TRANSACTION_ORDER_UPDATE`.
+
+### 2. Stop-Out Order Book Liquidation & Pending Order Purge
+When account equity drops below the broker's Stop-Out threshold (`equity / margin <= stopout_level`):
+1. **Pending Order Purge**: MT5 immediately cancels and deletes all active pending orders (`ORDER_STATE_CANCELED`) to release reserved margin before closing any positions.
+2. **Loss-Ranked Liquidation**: Active positions are sorted by floating loss, and the position with the greatest loss is closed first (`DEAL_REASON_SO`). If margin level remains below the threshold, subsequent positions are liquidated sequentially until account health is restored.
+
+### 3. Execution Latency Bypass in Open Prices Mode
+In MT5 Strategy Tester, when testing under `TickMode.OPEN_PRICES`, simulated transit delays are automatically bypassed. All bar-open signals execute at the bar opening quote without entering the in-flight latency queue (`in_flight_orders`). This mirrors MT5's speed optimization behavior.
+
+### 4. Netting Mode Accounting (`ACCOUNT_MARGIN_MODE_RETAIL_NETTING`)
+In Netting mode, only one position can exist per symbol:
+- **Adding to Position**: Computes the volume-weighted average open price:
+ $$\text{Open Price}_{\text{new}} = \frac{P_{\text{old}} \cdot V_{\text{old}} + P_{\text{fill}} \cdot V_{\text{fill}}}{V_{\text{old}} + V_{\text{fill}}}$$
+- **Partial Reduction**: Realizes gross profit, exit commission, and pro-rata accumulated swap (`pos.swap * (close_vol / pos.volume)`) directly into the cash balance.
+- **Position Reversal**: Fully closes the existing position, realizes all accumulated profit/swap, and opens a new position for the remaining lot volume in the opposite direction (`DEAL_ENTRY_INOUT`).
+
+### 5. Intrabar SL/TP Resolution Priority (12-Point Synthetic Wave Model)
+When testing on bars where both the Stop-Loss and Take-Profit boundaries are touched within the bar range, MT5 resolves priority using the candle's price progression:
+- **Bullish Bar (`Close >= Open`)**: Price moves $\text{Open} \to \text{Low} \to \text{High} \to \text{Close}$. For a Buy position, the Low is reached before the High; therefore, **Stop-Loss triggers before Take-Profit**.
+- **Bearish Bar (`Close < Open`)**: Price moves $\text{Open} \to \text{High} \to \text{Low} \to \text{Close}$. For a Buy position, the High is reached before the Low; therefore, **Take-Profit triggers before Stop-Loss**.
+
+---
+
+## 10. Interactive Step-by-Step & Visual Replay
EdgeEngine includes `et.InteractiveTester` which mirrors MT5's Visual Tester. It allows you to pause, step bar-by-bar or tick-by-tick, and inspect floating metrics in real-time.
@@ -538,7 +583,7 @@ print(f"Backtest finished! Net profit: ${result.net_profit:,.2f}")
---
-## 9. Optimization & Hyperopt Guide
+## 11. Optimization & Hyperopt Guide
EdgeEngine includes a dedicated multi-process `StrategyOptimizer` capable of running exhaustive grid sweeps and genetic algorithms across all CPU cores without Python GIL contention.
@@ -616,14 +661,37 @@ for rank, pass_res in enumerate(results[:3], start=1):
---
-## 10. Test Suite & Verification
+## 12. Engine Updates & Porting Guide (Changelog for Clones)
-The engine is validated by an automated test suite verifying matching engine mechanics, accounting integrity, and MT5 parity:
+If you have cloned or copied `edge_engine` into a separate standalone repository to maintain independently on GitHub, use this exact guide to port the latest MT5 parity updates into your standalone clone:
+
+| Target File | Component / Feature | Changes & Code Additions |
+| :--- | :--- | :--- |
+| **`core/include/types.hpp`** | **`SymbolSpec` Specification** | Added `int32_t swap_rollover3days = -1;` to `SymbolSpec`. Default `-1` treats markets as 24/7 continuous (e.g., Deriv synthetics, 24/7 crypto), charging 1x daily swap 7 days/week without artificial 3x penalties. `3` enables traditional Forex Wednesday 3x rollover. |
+| **`core/src/tester_bindings.cpp`** | **Pybind11 Bindings** | Exposed `.def_readwrite("swap_rollover3days", &SymbolSpec::swap_rollover3days)` under the `SymbolSpec` pybind registration block so it is accessible from Python. |
+| **`core/include/order_book.hpp`** | **Open Prices Latency Bypass** | Added `void set_open_prices_mode(bool b)` and `is_open_prices_mode_` boolean. In `TRADE_ACTION_DEAL`, execution delays are only queued if `!is_open_prices_mode_`, matching MT5 Strategy Tester's latency bypass behavior. |
+| **`core/include/order_book.hpp`** | **Swap Accrual Method** | Added `apply_swap(double multiplier = 1.0)` to iterate through `active_positions_` and increment `pos.swap` according to `swap_mode` (points or money/currency). |
+| **`core/include/order_book.hpp`** | **Stop-Limit Orders** | In `_evaluate_pending_orders`, added handling for `ORDER_TYPE_BUY_STOP_LIMIT` and `ORDER_TYPE_SELL_STOP_LIMIT`. When market reaches `price_open`, the order converts to an active limit order at `price_stoplimit`. |
+| **`core/include/order_book.hpp`** | **Day Expiration** | In `_evaluate_pending_orders`, added checking for `ORDER_TIME_DAY`: orders expire if `current_tick.time / 86400 > placed_time / 86400`. |
+| **`core/include/order_book.hpp`** | **Stop-Out Order Purge** | In `_handle_stopout`, active pending orders are now canceled and purged (`ORDER_STATE_CANCELED`) to free up reserved margin before initiating position liquidations. |
+| **`core/include/order_book.hpp`** | **Netting Mode Accounting** | Implemented weighted average open pricing when adding volume to an existing position, and realized PnL, exit commission, and pro-rata swap (`pos.swap * (close_vol / pos.volume)`) on reductions or reversals. |
+| **`core/include/order_book.hpp`** | **12-Point Wave SL/TP Priority** | In `evaluate_bar_extremes`, when both SL and TP are breached within the same bar, priority is assigned by candle color (`close >= open` tests Low/SL first for Buy; `close < open` tests High/TP first for Buy). |
+| **`core/include/interactive_tester.hpp`** | **Daily Rollover Scheduling** | Replaced per-bar swap charging with calendar day rollover logic tracking `last_swap_day_`. Iterates elapsed days and applies `apply_swap(multiplier)` honoring `swap_rollover3days`. Also initializes `book_->set_open_prices_mode(cfg.tick_mode == TickMode::OPEN_PRICES)`. |
+| **`core/include/interactive_tester.hpp`** | **Real-Tick Storage & Lifecycle** | Added `real_ticks_storage_` vector of vectors, enabled `TickMode::REAL_TICKS` validation, and bound `OnBar()` to fire strictly on the first tick of each new bar so new orders execute at candle open while subsequent ticks stream through the order book. |
+| **`core/src/tester_bindings.cpp`** | **Real-Tick Pybind11 Ingestion** | Added `ticks_df` argument to `Tester.run` accepting `tick_time_msc`, `tick_bid`, `tick_ask`, `tick_last`, `tick_volume`, `tick_flags`. Implemented zero-copy $O(N)$ two-pointer bar grouping into `std::vector>` with millisecond-to-second conversion. |
+| **`tests/test_advanced_features.py`** | **Unit Test Verification** | Added `test_latency_discarded_in_open_prices` and `test_swap_rollover_schedule` to ensure full regression test coverage. |
+
+---
+
+## 13. Test Suite & Verification
+
+The engine is validated by a 38-test test suite:
```powershell
-pytest tests/ -v
+python -m pytest edge_engine/tests/ -v
```
### Coverage
-- **Advanced Feature Tests (`tests/test_advanced_features.py`)**: Validates `OHLC_M1` 4-tick generation, transit delay slippage queues, `InteractiveTester` replay methods, and `StrategyOptimizer` Grid/Genetic optimization passes.
-- **Accounting & Margin Integrity (`tests/test_general_tester.py`)**: Tests margin calls, stop-out liquidations, Hedging vs. Netting, swap charges, historical price buffer queries, and deal log integrity.
+- **Parity Tests (`test_parity.py`)**: Validates exact numerical parity against the Numba/Python implementation across trade counts, win rates, net profit, and all trade management exit methods (A, B, C, D).
+- **Advanced Feature Tests (`test_advanced_features.py`)**: Validates `OHLC_M1` 4-tick generation, transit delay slippage queues, `InteractiveTester` replay methods, and `StrategyOptimizer` Grid/Genetic passes.
+- **Accounting & Margin Integrity (`test_general_tester.py`)**: Tests margin calls, stop-out liquidations, Hedging vs. Netting, swap charges, and deal log integrity.