forex-precision-backtester 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. forex_precision_backtester-1.0.0/LICENSE +21 -0
  2. forex_precision_backtester-1.0.0/MANIFEST.in +8 -0
  3. forex_precision_backtester-1.0.0/PKG-INFO +444 -0
  4. forex_precision_backtester-1.0.0/README.md +411 -0
  5. forex_precision_backtester-1.0.0/__init__.py +43 -0
  6. forex_precision_backtester-1.0.0/commission.py +82 -0
  7. forex_precision_backtester-1.0.0/config.py +347 -0
  8. forex_precision_backtester-1.0.0/engine.py +1153 -0
  9. forex_precision_backtester-1.0.0/forex_precision_backtester.egg-info/PKG-INFO +444 -0
  10. forex_precision_backtester-1.0.0/forex_precision_backtester.egg-info/SOURCES.txt +36 -0
  11. forex_precision_backtester-1.0.0/forex_precision_backtester.egg-info/dependency_links.txt +1 -0
  12. forex_precision_backtester-1.0.0/forex_precision_backtester.egg-info/entry_points.txt +3 -0
  13. forex_precision_backtester-1.0.0/forex_precision_backtester.egg-info/requires.txt +12 -0
  14. forex_precision_backtester-1.0.0/forex_precision_backtester.egg-info/top_level.txt +1 -0
  15. forex_precision_backtester-1.0.0/instrument.py +179 -0
  16. forex_precision_backtester-1.0.0/latency.py +61 -0
  17. forex_precision_backtester-1.0.0/metrics.py +226 -0
  18. forex_precision_backtester-1.0.0/models.py +326 -0
  19. forex_precision_backtester-1.0.0/pyproject.toml +56 -0
  20. forex_precision_backtester-1.0.0/report.py +900 -0
  21. forex_precision_backtester-1.0.0/run_backtest.py +235 -0
  22. forex_precision_backtester-1.0.0/runner.py +349 -0
  23. forex_precision_backtester-1.0.0/setup.cfg +4 -0
  24. forex_precision_backtester-1.0.0/slippage.py +99 -0
  25. forex_precision_backtester-1.0.0/strategy_base.py +194 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Quantitative Research & Systems DevOps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,8 @@
1
+ include LICENSE
2
+ include README.md
3
+ include pyproject.toml
4
+ prune docs
5
+ prune _build
6
+ global-exclude *.pyc
7
+ global-exclude __pycache__
8
+ global-exclude *.parquet
@@ -0,0 +1,444 @@
1
+ Metadata-Version: 2.4
2
+ Name: forex-precision-backtester
3
+ Version: 1.0.0
4
+ Summary: Institutional-grade discrete-event tick backtesting engine and execution simulation framework in 100% native Python.
5
+ Author: Quantitative Systems DevOps
6
+ License-Expression: MIT
7
+ Keywords: quantitative-finance,backtesting,tick-data,hft,forex,market-microstructure,trading,discrete-event,parquet
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Financial and Insurance Industry
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Topic :: Office/Business :: Financial :: Investment
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Operating System :: OS Independent
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy>=1.20.0
23
+ Requires-Dist: pandas>=1.3.0
24
+ Requires-Dist: pyarrow>=10.0.0
25
+ Requires-Dist: plotly>=5.0.0
26
+ Provides-Extra: docs
27
+ Requires-Dist: sphinx>=7.0.0; extra == "docs"
28
+ Requires-Dist: sphinx-rtd-theme>=2.0.0; extra == "docs"
29
+ Requires-Dist: myst-parser>=2.0.0; extra == "docs"
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7.0.0; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # Universal Discrete-Event Tick Backtester Framework
35
+
36
+ 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).
37
+
38
+ ---
39
+
40
+ ## Table of Contents
41
+ - [1. Core Architectural Pillars](#1-core-architectural-pillars)
42
+ - [2. Key Features](#2-key-features)
43
+ - [3. Architecture & Microstructure Pipeline](#3-architecture--microstructure-pipeline)
44
+ - [4. Performance & Microsecond Benchmark](#4-performance--microsecond-benchmark)
45
+ - [5. Installation & Prerequisites](#5-installation--prerequisites)
46
+ - [6. Quickstart: Building a Strategy](#6-quickstart-building-a-strategy)
47
+ - [7. Command-Line Interface (CLI) Usage](#7-command-line-interface-cli-usage)
48
+ - [8. Institutional Ledgers & Audit DataFrames](#8-institutional-ledgers--audit-dataframes)
49
+ - [9. Interactive HTML Visualizer Report](#9-interactive-html-visualizer-report)
50
+ - [10. Sub-Tick & High-Frequency Scheduling (1ms / 1μs)](#10-sub-tick--high-frequency-scheduling-1ms--1μs)
51
+ - [11. Current Limitations & Architectural Boundary Conditions](#11-current-limitations--architectural-boundary-conditions)
52
+ - [12. File Directory Map](#12-file-directory-map)
53
+ - [13. Test Suite Verification](#13-test-suite-verification)
54
+ - [14. Full Sphinx & ReadTheDocs Documentation](#14-full-sphinx--readthedocs-documentation)
55
+
56
+ ---
57
+
58
+ ## 1. Core Architectural Pillars
59
+
60
+ 1. **Zero MT5 Dependency**:
61
+ - Completely disconnected from MetaTrader 5 Strategy Tester, MetaEditor, and MT5 MCP wrappers.
62
+ - Eliminates MT5 closed-source interpolation artifacts, single-threaded bottlenecks, and optimistic wick fills.
63
+ 2. **Zero Lookahead Bias & Strict Next-Quote Causality**:
64
+ - 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**.
65
+ - All orders queue into an in-flight latency pipeline and execute strictly on incoming subsequent quotes at:
66
+ $$t_{\text{execution}} \ge t_{\text{next\_quote}} + l$$
67
+ where $l$ is the simulated network latency delay.
68
+ 3. **Execution Reality & Microstructure Friction**:
69
+ - **Spread-Aware Fills**: Market BUYs and Short exits execute on **Ask** ($P_a$); Market SELLs and Long exits execute on **Bid** ($P_b$).
70
+ - **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.
71
+ - **Broker Commissions**: Hardcoded institutional commission models (e.g. FTMO $\$11.00$/lot on Gold, $\$3.00$/lot on FX & Indices).
72
+ 4. **Sub-Tick Universal Timeline Synchronization**:
73
+ - 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.
74
+
75
+ ---
76
+
77
+ ## 2. Key Features
78
+
79
+ - **Extreme Throughput (>420,000 Ticks/Second)**:
80
+ Memory-safe Parquet streaming with zero-copy PyArrow table slicing and column statistics metadata skipping. Processes 100+ million ticks without RAM exhaustion.
81
+ - **Dual Drawdown Accounting**:
82
+ Maintains strict separation between **Closed Cash Balance Drawdown** and **Continuous Tick-by-Tick Mark-to-Market (MTM) Floating Equity Drawdown**.
83
+ - **Complete Audit Trail**:
84
+ Every simulation produces 4 immutable transaction ledgers:
85
+ 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`).
86
+ 2. [`DealRecord`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L150-L188): Discrete exchange execution fills (IN/OUT).
87
+ 3. [`OrderEventRecord`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L191-L231): Order lifecycle events (`SUBMIT`, `ACCEPT`, `FILL`, `MODIFY`, `CANCEL`, `REJECT`).
88
+ 4. [`AccountSnapshot`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/models.py#L298-L322): Periodic and milestone balance/equity snapshots.
89
+ - **Microstructure Strategy Callbacks**:
90
+ Strategies receive real-time notifications via `on_position_closed(trade)` and `on_order_event(event)`.
91
+ - **IEEE 754 Floating-Point Protection**:
92
+ Sizing formulas include epsilon guards (`+ 1e-9`) preventing floating-point division truncation (e.g. `0.29 / 0.01` dropping an entire lot step).
93
+ - **Frank Sortino Lower Partial Moment (LPM) Accuracy**:
94
+ 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.
95
+ - **Asset-Agnostic Presets**:
96
+ 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.
97
+
98
+ ---
99
+
100
+ ## 3. Architecture & Microstructure Pipeline
101
+
102
+ ```
103
+ [ Parquet Tick Stream ]
104
+
105
+
106
+ ┌───────────────────────────────────────┐
107
+ │ TickStreamRunner │
108
+ │ - Zero-cost row-group skipping │
109
+ │ - Column auto-detection │
110
+ │ - Vectorized pre-processing hook │
111
+ └───────────────────┬───────────────────┘
112
+
113
+ ┌─────────────────────┴─────────────────────┐
114
+ │ │
115
+ ▼ ▼
116
+ ┌─────────────────────────┐ ┌─────────────────────────┐
117
+ │ UniversalTickEngine │ │ BaseStrategy │
118
+ │ - Clock State (t) │ │ - User Trading Alpha │
119
+ │ - Pending Queue │ │ - Indicators │
120
+ │ - Resting Order Book │◄────────────────│ - Signals │
121
+ │ - MTM & SL/TP Triggers│ Submit Orders │ - Time Hooks │
122
+ │ - Deal/Trade Ledgers │ └─────────────────────────┘
123
+ └────────────┬────────────┘
124
+
125
+
126
+ ┌─────────────────────────────────────────────────────────┐
127
+ │ PerformanceAuditor │
128
+ │ - Dual Drawdown (Balance vs MTM Equity) │
129
+ │ - Continuous 252-Day Annualized Sharpe & Sortino (LPM)│
130
+ │ - Profit Factor, Expected Value, Win Rate │
131
+ │ - MAE / MFE Edge Ratio & Slippage Points │
132
+ └────────────────────────────┬────────────────────────────┘
133
+
134
+
135
+ ┌─────────────────────────────────────────────────────────┐
136
+ │ BacktestHTMLReporter │
137
+ │ - Responsive Dark-Themed Quantitative Visualizer │
138
+ │ - Dual-Pane Plotly Equity & Drawdown Curves │
139
+ │ - Tabbed Searchable Logs (Trades, Deals, Events) │
140
+ └─────────────────────────────────────────────────────────┘
141
+ ```
142
+
143
+ ---
144
+
145
+ ## 4. Performance & Microsecond Benchmark
146
+
147
+ Simulated over real Dukascopy millisecond tick datasets on standard desktop hardware:
148
+
149
+ | Benchmark Test | Symbol | Ticks Processed | Elapsed Time | Simulation Speed |
150
+ |---|---|---|---|---|
151
+ | **Spot Gold (XAUUSD)** | `xauusd` | 500,000 ticks | 1.18 sec | **424,451 ticks/sec** |
152
+ | **Nasdaq 100 CFD (NQ)** | `usatechidxusd`| 500,000 ticks | 1.18 sec | **422,271 ticks/sec** |
153
+
154
+ ---
155
+
156
+ ## 5. Installation & Prerequisites
157
+
158
+ The framework requires Python 3.10+ and standard numerical libraries:
159
+
160
+ ```powershell
161
+ pip install numpy pandas pyarrow
162
+ ```
163
+
164
+ *(No MetaTrader 5, proprietary DLLs, or C++ compilers required.)*
165
+
166
+ ---
167
+
168
+ ## 6. Quickstart: Building a Strategy
169
+
170
+ Inherit from [`BaseStrategy`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/strategy_base.py#L13-L188) and implement `on_tick`:
171
+
172
+ ```python
173
+ from research.backtester.models import Tick, TradeRecord, OrderEventRecord
174
+ from research.backtester.strategy_base import BaseStrategy
175
+ from research.backtester.engine import UniversalTickEngine
176
+ from research.backtester.instrument import Instrument
177
+ from research.backtester.commission import PerLotCommission
178
+ from research.backtester.slippage import NaturalGapSlippage
179
+ from research.backtester.latency import FixedLatency
180
+ from research.backtester.runner import TickStreamRunner
181
+
182
+ class SimpleBreakoutStrategy(BaseStrategy):
183
+ def __init__(self, engine: UniversalTickEngine, lookback: int = 50):
184
+ super().__init__(engine)
185
+ self.lookback = lookback
186
+ self.prices = []
187
+
188
+ def on_tick(self, tick: Tick) -> None:
189
+ self.prices.append(tick.mid)
190
+ if len(self.prices) > self.lookback:
191
+ self.prices.pop(0)
192
+ else:
193
+ return
194
+
195
+ # Single-position check
196
+ if self.position is not None:
197
+ return
198
+
199
+ high = max(self.prices[:-1])
200
+ low = min(self.prices[:-1])
201
+
202
+ # Risk-based lot sizing (0.5% risk, 200 ticks SL)
203
+ sl_dist = 200 * self.instrument.tick_size
204
+ tp_dist = 400 * self.instrument.tick_size # 1:2.0 RR
205
+ lots = self.instrument.calc_lots_from_risk(self.balance, 0.005, sl_dist)
206
+
207
+ if tick.mid > high:
208
+ self.buy(quantity=lots, sl=tick.ask - sl_dist, tp=tick.ask + tp_dist, tag="BREAKOUT_LONG")
209
+ elif tick.mid < low:
210
+ self.sell(quantity=lots, sl=tick.bid + sl_dist, tp=tick.bid - tp_dist, tag="BREAKOUT_SHORT")
211
+
212
+ def on_position_closed(self, trade: TradeRecord) -> None:
213
+ print(f"Trade #{trade.trade_id} closed: Net PnL = ${trade.net_pnl:.2f} via {trade.exit_reason}")
214
+
215
+ def on_order_event(self, event: OrderEventRecord) -> None:
216
+ # Real-time lifecycle logging
217
+ if event.event_type.name == "REJECT":
218
+ print(f"Order #{event.order_id} REJECTED: {event.details}")
219
+
220
+
221
+ if __name__ == "__main__":
222
+ # 1. Setup Instrument & Execution Physics
223
+ gold = Instrument.gold()
224
+ engine = UniversalTickEngine(
225
+ instrument=gold,
226
+ initial_balance=100_000.0,
227
+ commission_model=PerLotCommission(11.00), # FTMO Gold $11/lot
228
+ slippage_model=NaturalGapSlippage(),
229
+ latency_model=FixedLatency(50) # 50ms execution delay
230
+ )
231
+
232
+ # 2. Instantiate Strategy
233
+ strat = SimpleBreakoutStrategy(engine, lookback=100)
234
+
235
+ # 3. Stream Parquet Ticks
236
+ runner = TickStreamRunner(
237
+ strategy=strat,
238
+ data_source="D:/Developing_quant_system_for_FTMO/data/dukascopy_ticks",
239
+ symbol="xauusd",
240
+ max_ticks=200_000
241
+ )
242
+ results = runner.run()
243
+
244
+ # 4. Generate Interactive HTML Report
245
+ engine.generate_html_report("gold_breakout_report.html")
246
+ ```
247
+
248
+ ---
249
+
250
+ ## 7. Command-Line Interface (CLI) Usage
251
+
252
+ The framework includes a standalone CLI runner: [`run_backtest.py`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/run_backtest.py).
253
+
254
+ ### Basic Backtest
255
+ ```powershell
256
+ python research/backtester/run_backtest.py --symbol xauusd --max-ticks 500000
257
+ ```
258
+
259
+ ### Full Institutional Backtest with Visualizer & CSV Exports
260
+ ```powershell
261
+ python research/backtester/run_backtest.py `
262
+ --symbol usatechidxusd `
263
+ --balance 100000 `
264
+ --risk 0.005 `
265
+ --sl-ticks 300 `
266
+ --rr 2.0 `
267
+ --latency 50 `
268
+ --slippage natural `
269
+ --html nq_audit_report.html `
270
+ --show-trades `
271
+ --show-deals `
272
+ --show-events
273
+ ```
274
+
275
+ ### Key CLI Parameters
276
+ | Flag | Default | Description |
277
+ |---|---|---|
278
+ | `--symbol` | `xauusd` | Traded instrument symbol (`xauusd`, `usatechidxusd`, `eurusd`, `btcusd`). |
279
+ | `--balance` | `100000.0` | Starting cash balance in USD. |
280
+ | `--risk` | `0.005` | Risk per trade fraction (e.g. `0.005` = $0.5\%$). |
281
+ | `--sl-ticks` | `200.0` | Stop loss distance in discrete price ticks. |
282
+ | `--rr` | `2.0` | Reward-to-risk ratio. |
283
+ | `--latency` | `50` | In-flight network routing delay in milliseconds. |
284
+ | `--commission` | Auto | Round-trip commission override in USD per lot. |
285
+ | `--slippage` | `natural` | Slippage physics: `natural` (gap), `fixed` (penalty), or `zero`. |
286
+ | `--html` | `None` | Filepath to output interactive HTML report. |
287
+ | `--pulse` | `None` | Sub-tick time progression mode (`1ms` or `1us`). |
288
+ | `--export-csv` | `None` | Prefix to export 4 complete CSV ledgers (trades, deals, events, equity). |
289
+
290
+ ---
291
+
292
+ ## 8. Institutional Ledgers & Audit DataFrames
293
+
294
+ At any point during or after simulation, audit ledgers can be extracted as standard pandas DataFrames:
295
+
296
+ ```python
297
+ # Completed Round-Turn Trades (TradeRecord)
298
+ trades_df = engine.get_trades_df()
299
+
300
+ # Individual Execution Deals (DealRecord - Entries and Exits)
301
+ deals_df = engine.get_deals_df()
302
+
303
+ # Order Event Lifecycle Audit (OrderEventRecord - Submit, Accept, Fill, Cancel, Reject)
304
+ events_df = engine.get_order_events_df()
305
+
306
+ # Periodic Floating Equity & Drawdown Snapshots
307
+ equity_df = engine.get_equity_df()
308
+ ```
309
+
310
+ ### Printable ASCII Tables
311
+ - `engine.print_trade_log(limit=20)`: Formatted executed trades table.
312
+ - `engine.print_deals_log(limit=20)`: Formatted fills/deals ledger.
313
+ - `engine.print_order_events_log(limit=20)`: Formatted order lifecycle transitions.
314
+ - `PerformanceAuditor.print_performance_card(audit_results)`: Institutional KPI card.
315
+
316
+ ---
317
+
318
+ ## 9. Interactive HTML Visualizer Report
319
+
320
+ 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)):
321
+
322
+ - **Dual Plotly Timeseries**:
323
+ - Top: Continuous Mark-to-Market Floating Equity vs. Closed Balance vs. High-Water Mark.
324
+ - Bottom: Underwater Drawdown Curve (% Peak-to-Trough) with shaded risk zones.
325
+ - **Institutional Statistical Matrix**:
326
+ - Annualized Sharpe Ratio (continuous 252-day basis, zero day-omission bias).
327
+ - Annualized Sortino Ratio (exact Lower Partial Moment semi-deviation).
328
+ - Calmar Ratio, Profit Factor, Realized RR, Expectancy ($).
329
+ - Dual Drawdown figures (Max Balance DD vs Max MTM Equity DD).
330
+ - Microstructure Execution Analytics (MAE, MFE, Edge Ratio, Entry/Exit Slippage Points).
331
+ - **Searchable Tabbed Ledgers**:
332
+ - Tab 1: Completed Trades (with duration, PnL, return %, SL/TP, slippage, MAE/MFE).
333
+ - Tab 2: Execution Deals (individual IN/OUT fills with commissions and realized PnL).
334
+ - Tab 3: Order Events Lifecycle (audit trail with timestamps, prices, and rejection reasons).
335
+
336
+ ---
337
+
338
+ ## 10. Sub-Tick & High-Frequency Scheduling (1ms / 1μs)
339
+
340
+ 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:
341
+
342
+ ```python
343
+ runner = TickStreamRunner(
344
+ strategy=strat,
345
+ data_source="data/ticks",
346
+ pulse_interval="1ms" # or "1us"
347
+ )
348
+ ```
349
+
350
+ During pulses, the following lifecycle hooks trigger synchronously:
351
+ - `on_every_1ms(timestamp)`: 1-millisecond clock interval.
352
+ - `on_every_1us(timestamp)`: 1-microsecond clock interval.
353
+ - `on_time(timestamp)`: Generic time advancement hook.
354
+
355
+ ---
356
+
357
+ ## 11. Current Limitations & Architectural Boundary Conditions
358
+
359
+ To maintain absolute quantitative honesty and transparency, the following design boundaries are intentionally enforced:
360
+
361
+ 1. **Single-Position Netting Architecture (No Hedging)**:
362
+ - The engine operates under an institutional netting model. Only one active position per symbol can exist at a time.
363
+ - 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.
364
+ 2. **Top-of-Book (L1 / BBO) Liquidity Model**:
365
+ - Market orders fill against the Best Bid / Best Ask quote.
366
+ - 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.
367
+ 3. **Single-Instrument Execution Engine**:
368
+ - Each `UniversalTickEngine` instance simulates a single symbol's matching mechanics.
369
+ - 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.
370
+ 4. **Weekend & Holiday Gap Handling**:
371
+ - 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.
372
+
373
+ ---
374
+
375
+ ## 12. File Directory Map
376
+
377
+ ```
378
+ research/backtester/
379
+ ├── __init__.py # Module exports
380
+ ├── config.py # Global symbol registry, FTMO specifications, and presets
381
+ ├── commission.py # PerLot, Percentage, PerContract, and Zero commission models
382
+ ├── engine.py # UniversalTickEngine: discrete-event matching and MTM ledger
383
+ ├── instrument.py # Instrument class: contract size, tick value, sizing math
384
+ ├── latency.py # FixedLatency, JitterLatency, ZeroLatency models
385
+ ├── metrics.py # PerformanceAuditor: Sharpe, Sortino (LPM), Dual DD, MAE/MFE
386
+ ├── models.py # Tick, Order, Position, DealRecord, OrderEventRecord, TradeRecord
387
+ ├── report.py # BacktestHTMLReporter: interactive Plotly HTML visualizer
388
+ ├── run_backtest.py # CLI execution entry point
389
+ ├── runner.py # TickStreamRunner: high-speed streaming Parquet runner
390
+ ├── slippage.py # NaturalGapSlippage, FixedSlippage, ZeroSlippage models
391
+ ├── strategy_base.py # BaseStrategy: abstract strategy interface and trading API
392
+ └── docs/ # Sphinx & ReadTheDocs technical documentation
393
+ ├── conf.py # Sphinx build configuration
394
+ ├── requirements.txt # Documentation dependencies
395
+ ├── index.rst # Master documentation index
396
+ ├── architecture.rst # Discrete-event architecture
397
+ ├── microstructure.rst # Causality & execution physics
398
+ ├── sub_tick_engine.rst # Sub-tick & high-frequency scheduling
399
+ ├── quickstart.rst # Strategy authoring guide
400
+ ├── cli.rst # CLI execution manual
401
+ ├── api_reference.rst# Python API reference (autodoc)
402
+ └── limitations.rst # Architectural boundaries
403
+ ```
404
+
405
+ ---
406
+
407
+ ## 13. Test Suite Verification
408
+
409
+ All engine components are verified by a 36-test automated regression suite:
410
+
411
+ ```powershell
412
+ python -m unittest discover -s research/tests -p "test_*.py" -v
413
+ ```
414
+ ```
415
+ Ran 36 tests in 2.441s
416
+ OK
417
+ ```
418
+ 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.
419
+
420
+ ---
421
+
422
+ ## 14. Full Sphinx & ReadTheDocs Documentation
423
+
424
+ 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)):
425
+
426
+ - **Root Config**: [`.readthedocs.yaml`](file:///D:/Developing_quant_system_for_FTMO/.readthedocs.yaml)
427
+ - **Sphinx Documentation Root**: [`research/backtester/docs/`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/)
428
+ - [`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)
429
+ - [`research/backtester/docs/requirements.txt`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/requirements.txt): Build dependencies
430
+ - [`research/backtester/docs/index.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/index.rst): Master documentation index
431
+ - [`research/backtester/docs/architecture.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/architecture.rst): Discrete-event matching engine architecture & streaming pipeline
432
+ - [`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
433
+ - [`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
434
+ - [`research/backtester/docs/quickstart.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/quickstart.rst): Quickstart tutorial for strategy authors
435
+ - [`research/backtester/docs/cli.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/cli.rst): Command-Line Interface (CLI) manual & options
436
+ - [`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
437
+ - [`research/backtester/docs/limitations.rst`](file:///D:/Developing_quant_system_for_FTMO/research/backtester/docs/limitations.rst): Architectural boundary conditions & netting specifications
438
+
439
+ To build the HTML documentation locally:
440
+ ```powershell
441
+ python -m sphinx -b html research/backtester/docs research/backtester/docs/_build/html
442
+ ```
443
+ 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).
444
+