mdrap 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 (120) hide show
  1. mdrap-1.0.0/LICENSE +21 -0
  2. mdrap-1.0.0/PKG-INFO +493 -0
  3. mdrap-1.0.0/README.md +452 -0
  4. mdrap-1.0.0/pyproject.toml +92 -0
  5. mdrap-1.0.0/setup.cfg +4 -0
  6. mdrap-1.0.0/setup.py +21 -0
  7. mdrap-1.0.0/src/analytics.py +200 -0
  8. mdrap-1.0.0/src/archive.py +154 -0
  9. mdrap-1.0.0/src/async_storage.py +261 -0
  10. mdrap-1.0.0/src/bbo.py +268 -0
  11. mdrap-1.0.0/src/benchmark.py +169 -0
  12. mdrap-1.0.0/src/broker.py +178 -0
  13. mdrap-1.0.0/src/chaos.py +260 -0
  14. mdrap-1.0.0/src/cli.py +4412 -0
  15. mdrap-1.0.0/src/client.py +682 -0
  16. mdrap-1.0.0/src/columnar.py +651 -0
  17. mdrap-1.0.0/src/config.py +264 -0
  18. mdrap-1.0.0/src/dashboard.py +125 -0
  19. mdrap-1.0.0/src/databento_feed.py +558 -0
  20. mdrap-1.0.0/src/depth.py +621 -0
  21. mdrap-1.0.0/src/excel_bridge.py +795 -0
  22. mdrap-1.0.0/src/exporter.py +995 -0
  23. mdrap-1.0.0/src/fastpath.py +797 -0
  24. mdrap-1.0.0/src/feed_handler.py +216 -0
  25. mdrap-1.0.0/src/feed_workers.py +262 -0
  26. mdrap-1.0.0/src/flow_tracker.py +474 -0
  27. mdrap-1.0.0/src/gateway.py +102 -0
  28. mdrap-1.0.0/src/gateway_tcp.py +117 -0
  29. mdrap-1.0.0/src/live.py +564 -0
  30. mdrap-1.0.0/src/mbo.py +413 -0
  31. mdrap-1.0.0/src/mdrap.egg-info/PKG-INFO +493 -0
  32. mdrap-1.0.0/src/mdrap.egg-info/SOURCES.txt +118 -0
  33. mdrap-1.0.0/src/mdrap.egg-info/dependency_links.txt +1 -0
  34. mdrap-1.0.0/src/mdrap.egg-info/entry_points.txt +2 -0
  35. mdrap-1.0.0/src/mdrap.egg-info/requires.txt +24 -0
  36. mdrap-1.0.0/src/mdrap.egg-info/top_level.txt +53 -0
  37. mdrap-1.0.0/src/metrics.py +167 -0
  38. mdrap-1.0.0/src/models.py +84 -0
  39. mdrap-1.0.0/src/multicast_arbitrator.py +313 -0
  40. mdrap-1.0.0/src/pipeline.py +323 -0
  41. mdrap-1.0.0/src/pipeline_v2.py +370 -0
  42. mdrap-1.0.0/src/polygon_feed.py +503 -0
  43. mdrap-1.0.0/src/prometheus.py +275 -0
  44. mdrap-1.0.0/src/protocol.py +256 -0
  45. mdrap-1.0.0/src/quality.py +195 -0
  46. mdrap-1.0.0/src/reconciliation.py +186 -0
  47. mdrap-1.0.0/src/sbe.py +364 -0
  48. mdrap-1.0.0/src/sdk/__init__.py +3 -0
  49. mdrap-1.0.0/src/sdk/client.py +141 -0
  50. mdrap-1.0.0/src/sdk/execution.py +95 -0
  51. mdrap-1.0.0/src/sdk/strategy_vwap.py +69 -0
  52. mdrap-1.0.0/src/sdk_dashboard.py +183 -0
  53. mdrap-1.0.0/src/security.py +452 -0
  54. mdrap-1.0.0/src/service.py +1171 -0
  55. mdrap-1.0.0/src/sharded_pipeline.py +292 -0
  56. mdrap-1.0.0/src/shm.py +511 -0
  57. mdrap-1.0.0/src/simulator.py +171 -0
  58. mdrap-1.0.0/src/spsc_ring.py +167 -0
  59. mdrap-1.0.0/src/storage.py +704 -0
  60. mdrap-1.0.0/src/strategy_sdk.py +527 -0
  61. mdrap-1.0.0/src/stresstest.py +718 -0
  62. mdrap-1.0.0/src/tca.py +396 -0
  63. mdrap-1.0.0/src/term.py +199 -0
  64. mdrap-1.0.0/src/terminal_display.py +779 -0
  65. mdrap-1.0.0/src/watchdog.py +158 -0
  66. mdrap-1.0.0/src/web_cockpit.py +998 -0
  67. mdrap-1.0.0/src/workload_simulator.py +707 -0
  68. mdrap-1.0.0/src/ws_feed.py +523 -0
  69. mdrap-1.0.0/tests/test_analytics.py +207 -0
  70. mdrap-1.0.0/tests/test_archive.py +127 -0
  71. mdrap-1.0.0/tests/test_async_storage.py +120 -0
  72. mdrap-1.0.0/tests/test_audit_hardening.py +441 -0
  73. mdrap-1.0.0/tests/test_bbo.py +239 -0
  74. mdrap-1.0.0/tests/test_chaos.py +73 -0
  75. mdrap-1.0.0/tests/test_cli.py +370 -0
  76. mdrap-1.0.0/tests/test_client.py +227 -0
  77. mdrap-1.0.0/tests/test_columnar.py +251 -0
  78. mdrap-1.0.0/tests/test_concurrent_users.py +141 -0
  79. mdrap-1.0.0/tests/test_config.py +114 -0
  80. mdrap-1.0.0/tests/test_databento_feed.py +189 -0
  81. mdrap-1.0.0/tests/test_depth.py +299 -0
  82. mdrap-1.0.0/tests/test_entitlements.py +218 -0
  83. mdrap-1.0.0/tests/test_excel_bridge.py +119 -0
  84. mdrap-1.0.0/tests/test_export.py +172 -0
  85. mdrap-1.0.0/tests/test_fastpath.py +220 -0
  86. mdrap-1.0.0/tests/test_fastpath_throughput.py +167 -0
  87. mdrap-1.0.0/tests/test_feed_handler.py +158 -0
  88. mdrap-1.0.0/tests/test_feed_workers.py +104 -0
  89. mdrap-1.0.0/tests/test_flow_tracker.py +96 -0
  90. mdrap-1.0.0/tests/test_hardening.py +350 -0
  91. mdrap-1.0.0/tests/test_keyboard_shortcuts.py +86 -0
  92. mdrap-1.0.0/tests/test_live.py +380 -0
  93. mdrap-1.0.0/tests/test_mbo.py +212 -0
  94. mdrap-1.0.0/tests/test_multicast_arbitrator.py +155 -0
  95. mdrap-1.0.0/tests/test_pipeline_integration.py +74 -0
  96. mdrap-1.0.0/tests/test_polygon_feed.py +171 -0
  97. mdrap-1.0.0/tests/test_prometheus.py +105 -0
  98. mdrap-1.0.0/tests/test_prometheus_caching.py +83 -0
  99. mdrap-1.0.0/tests/test_protocol.py +203 -0
  100. mdrap-1.0.0/tests/test_quality.py +95 -0
  101. mdrap-1.0.0/tests/test_sbe.py +173 -0
  102. mdrap-1.0.0/tests/test_sdk.py +90 -0
  103. mdrap-1.0.0/tests/test_security.py +221 -0
  104. mdrap-1.0.0/tests/test_service.py +146 -0
  105. mdrap-1.0.0/tests/test_service_resilience.py +131 -0
  106. mdrap-1.0.0/tests/test_sharded_pipeline.py +45 -0
  107. mdrap-1.0.0/tests/test_shm.py +244 -0
  108. mdrap-1.0.0/tests/test_shm_decoupled.py +417 -0
  109. mdrap-1.0.0/tests/test_spsc_ring.py +129 -0
  110. mdrap-1.0.0/tests/test_strategy_sdk.py +143 -0
  111. mdrap-1.0.0/tests/test_stresstest.py +95 -0
  112. mdrap-1.0.0/tests/test_system_limitations.py +335 -0
  113. mdrap-1.0.0/tests/test_system_stress_and_adversarial.py +486 -0
  114. mdrap-1.0.0/tests/test_tca.py +117 -0
  115. mdrap-1.0.0/tests/test_terminal_display.py +171 -0
  116. mdrap-1.0.0/tests/test_v2_streaming.py +85 -0
  117. mdrap-1.0.0/tests/test_vwap.py +279 -0
  118. mdrap-1.0.0/tests/test_watchdog.py +148 -0
  119. mdrap-1.0.0/tests/test_web_cockpit.py +77 -0
  120. mdrap-1.0.0/tests/test_ws_feed.py +196 -0
mdrap-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MDRAP Platform Contributors
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.
mdrap-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,493 @@
1
+ Metadata-Version: 2.4
2
+ Name: mdrap
3
+ Version: 1.0.0
4
+ Summary: Market Data Reliability & Acceleration Platform - Financial market infrastructure for converting noisy market feeds into validated canonical streams
5
+ Author: MDRAP Team
6
+ License: MIT
7
+ Keywords: market-data,hft,trading,bbo,nbbo,cryptocurrency,finance,latency,data-quality,infrastructure
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Financial and Insurance Industry
10
+ Classifier: Topic :: Office/Business :: Financial :: Investment
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: C
17
+ Classifier: Operating System :: OS Independent
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: rich>=13.0.0
22
+ Provides-Extra: export
23
+ Requires-Dist: openpyxl>=3.1.0; extra == "export"
24
+ Provides-Extra: stream
25
+ Requires-Dist: websockets>=12.0; extra == "stream"
26
+ Provides-Extra: config
27
+ Requires-Dist: pyyaml>=6.0; extra == "config"
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
30
+ Requires-Dist: pytest-timeout>=2.3.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
32
+ Provides-Extra: all
33
+ Requires-Dist: rich>=13.0.0; extra == "all"
34
+ Requires-Dist: openpyxl>=3.1.0; extra == "all"
35
+ Requires-Dist: websockets>=12.0; extra == "all"
36
+ Requires-Dist: pyyaml>=6.0; extra == "all"
37
+ Requires-Dist: pytest>=8.0.0; extra == "all"
38
+ Requires-Dist: pytest-timeout>=2.3.0; extra == "all"
39
+ Requires-Dist: pytest-cov>=5.0.0; extra == "all"
40
+ Dynamic: license-file
41
+
42
+ # Market Data Reliability & Acceleration Platform (MDRAP)
43
+
44
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg)](https://www.python.org/)
45
+ [![Tests](https://img.shields.io/badge/tests-238%2F238%20passing-brightgreen.svg)](tests/)
46
+ [![Hot Path Latency](https://img.shields.io/badge/hot--path-50.0%20ns%20%7C%2018.6M%20eps-orange.svg)](src/fastpath.c)
47
+ [![Architecture](https://img.shields.io/badge/architecture-V1%20%7C%20V2%20%7C%20V3%20%7C%20V4%20C--Fastpath-purple.svg)](docs/architecture.md)
48
+ [![User Guide](https://img.shields.io/badge/manual-Operator%20%26%20User%20Guide-teal.svg)](docs/USER_GUIDE.md)
49
+ [![Dependencies](https://img.shields.io/badge/dependencies-zero%20mandatory-success.svg)](requirements.txt)
50
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
51
+
52
+ A high-performance financial market infrastructure platform designed to ingest, validate, accelerate, and reconcile noisy, delayed, duplicated, and inconsistent market data from disparate exchanges and internal feeds into a unified, ultra-low-latency canonical stream with mathematical reliability scoring, cryptographic lineage auditing, and institutional execution analytics.
53
+
54
+ 📖 **Complete Documentation**: See the [**Comprehensive Operator & User Manual**](docs/USER_GUIDE.md) for full syntax, flags, hotkeys, and role-based workflows.
55
+
56
+ ---
57
+
58
+ ## High-Level Architecture
59
+
60
+ ```mermaid
61
+ flowchart TD
62
+ subgraph INGESTION ["1. Market Ingestion & Direct Streaming Feeds"]
63
+ POLY[Polygon.io WebSocket<br/>US Equities & Crypto Q/T/AM]
64
+ DBN[Databento Binary DBN<br/>CME/Nasdaq MBP-1/10 & Trades]
65
+ B[Binance / Coinbase / Kraken<br/>Crypto WebSockets & REST]
66
+ SIM[Deterministic Feed Simulator<br/>Seeded Faults & Injections]
67
+ FSUP[Streaming Feed Supervisor<br/>Thread-Safe Low-Contention Queue]
68
+ end
69
+
70
+ subgraph SECURITY ["2. Security & Gatekeeper (Spec §19)"]
71
+ RL[Token Bucket Rate Limiter<br/>20,000 eps per IP/Key]
72
+ SAN[Regex & Range Payload Sanitizer]
73
+ HMAC[HMAC-SHA256 Signature Verification<br/>Constant-Time Digest]
74
+ RBAC[RBAC Entitlement Guard<br/>VIEWER / OPERATOR / ADMIN]
75
+ end
76
+
77
+ subgraph PIPELINE ["3. Validation, Acceleration & Consensus Pipeline"]
78
+ GW[Gateway & Normalization<br/>RawEvent -> CanonicalEvent]
79
+ QE[7-Rule Quality Engine<br/>Schema, Dedup, Gap, Order, Stale, Crossed, 3-Sigma]
80
+ FP[Native C Hot Path Accelerator<br/>8,192 Symbols | 18.6M eps | 50.0 ns]
81
+ WD[Source Watchdog & Failover Circuit Breaker<br/>Silence & Degradation Monitoring]
82
+ BBO[Synthetic Consolidated BBO<br/>5-Venue Multi-Exchange NBBO]
83
+ DEPTH[Consolidated L2 Order Book<br/>Multi-Venue Depth Aggregation & VWAP Curves]
84
+ end
85
+
86
+ subgraph STORAGE ["4. Columnar & Batched Storage, Archive & Audit (Spec §14, §19, §26)"]
87
+ CAN[(canonical_events<br/>WAL SQLite Batch)]
88
+ QUAR[(quarantine<br/>Never Silently Drop)]
89
+ LIN[(lineage<br/>Transformation Lineage Proof)]
90
+ AUD[(audit_log<br/>Merkle Hash Chained)]
91
+ ARC[[Immutable Raw JSONL Archive<br/>Write-Ahead Partitioned Log]]
92
+ COL[(DuckDB Columnar Store<br/>SIMD Resampling & Parquet Export)]
93
+ end
94
+
95
+ subgraph PRESENTATION ["5. Presentation, IPC & Institutional Export"]
96
+ DAEMON[Headless Streaming Daemon<br/>Non-blocking Socket IPC]
97
+ SHM[Binary Shared Memory Transport<br/>Zero-Copy Ring Buffer]
98
+ LIVE[In-Place Live Terminal Ticker<br/>Cursor-Repositioned Rich HUD]
99
+ CHART[Visual Candlestick Terminal Chart<br/>Unicode Wicks & Outlier Percentile Scaling]
100
+ EXCEL[Institutional 5-Tab Excel Exporter<br/>XLSX Financial Model & CSV Packages]
101
+ end
102
+
103
+ POLY & DBN & B & SIM --> FSUP --> RL
104
+ RL --> SAN --> HMAC --> RBAC --> GW
105
+ GW --> ARC
106
+ GW --> QE
107
+ QE <--> FP
108
+ QE --> BBO & DEPTH
109
+ QE --> WD
110
+ BBO & DEPTH --> DAEMON & SHM
111
+ QE --> CAN & QUAR & LIN & AUD
112
+ CAN --> COL
113
+ BBO & DEPTH & COL --> LIVE & CHART & EXCEL
114
+ ```
115
+
116
+ ---
117
+
118
+ ## Key Platform Capabilities
119
+
120
+ ### 1. 7-Rule Data Quality Engine (Spec §7)
121
+ - **Structural Schema Validation**: Rejects malformed JSON and missing sequence/timestamp attributes.
122
+ - **Sliding-Window Deduplication**: Identifies exact and sliding-window duplicate packet bursts without memory bloat.
123
+ - **Monotonic Sequence Gap Detection**: Detects missing exchange packets and penalizes feed reputation.
124
+ - **Out-of-Order Sequencing**: Catches retrograde arrival events across jittery network paths.
125
+ - **Timestamp Staleness Evaluation**: Flags lagging feeds exceeding max latency thresholds.
126
+ - **Crossed Quote Detection**: Flags invalid book states where $\text{Bid} > \text{Ask}$.
127
+ - **Statistical Price Sanity Checks**: Evaluates sudden price jumps ($>3\sigma$) using Welford's online variance algorithm.
128
+ - **Strict Quality Priority**: Non-downgradable status progression: `INVALID` > `SUSPICIOUS` > `VALID`. Quarantines bad data; **never silently drops events**.
129
+
130
+ ### 2. Native C Hot-Path Accelerator (`fastpath.c`)
131
+ - Pure C implementation compiled with GCC `-O3` into a native shared library (`fastpath.dll`).
132
+ - **Capacity Expanded to 8,192 Symbols ($2^{13}$)** and 32 feed sources with dynamically allocated, SIMD-aligned contiguous memory arrays.
133
+ - **Zero-Division Bitshift Slot Indexing**: Computes slot offsets in 1 CPU cycle: `(source_id << 13) | instrument_id`.
134
+ - **Ultra-High Throughput**: Evaluates **18,669,082 events/sec (50.0 nanoseconds/event)** in batch mode.
135
+ - Seamless, transparent boundary fallback to pure Python if instrument universe exceeds 8,192 symbols.
136
+
137
+ ### 3. Direct High-Throughput Streaming Feed Handlers (`src/polygon_feed.py`, `src/databento_feed.py`, `src/feed_handler.py`)
138
+ - **Polygon.io WebSocket Connector**: Streams high-frequency US Equities and Crypto quotes (`Q`), trades (`T`), and aggregate bars (`AM`) with API key authentication, multiplexed subscription channels, exponential backoff reconnection, and built-in offline wire-format mock generators.
139
+ - **Databento Binary Encoding (DBN) Ingestion**: Sub-microsecond binary record decoding using `struct.Struct` with C-struct layouts for Databento DBN formats (`MBP-1`, `MBP-10`, `TradeMsg`), nanosecond UTC epoch timestamps, fixed-point price scaling ($10^9$), dynamic symbol resolution, and live TCP / `.dbn` file / synthetic binary packet streaming.
140
+ - **Unified Streaming Feed Supervisor**: Coordinates multiple streaming providers into a bounded, low-contention queue with ring eviction to guarantee real-time latency and zero stale queue backlog. Ingestion telemetry tracks throughput (eps), dropped frames, and provider health.
141
+
142
+ ### 4. DuckDB Columnar Time-Series Storage & SIMD Analytics (`src/columnar.py`, Spec §14, §26)
143
+ - **High-Throughput Embedded Columnar Store**: Embedded in-process DuckDB analytical engine with SIMD-vectorized execution for ultra-fast billion-tick historical queries.
144
+ - **Zero-Copy SQLite Sync**: Directly attaches operational SQLite databases via DuckDB's native SQLite scanner (`ATTACH '...' AS sqldb (TYPE SQLITE)`) and bulk copies 300,000+ ticks in ~2.8s into columnar storage.
145
+ - **Vectorized Resampling & Aggregation**:
146
+ - Resamples trade ticks into OHLCV candles via `arg_min(price, exchange_timestamp)` and `arg_max(price, exchange_timestamp)` in a single pass without window functions or self-joins (**37.2x faster than SQLite**).
147
+ - Computes exact institutional VWAP (`sum(P*Q) / sum(Q)`) and total notional across tens of thousands of trades in <10ms (**63.3x faster than SQLite**).
148
+ - Vectorized bid-ask spread analytics and crossed-market anomaly tracking.
149
+ - Sub-microsecond latency quantile extraction (`p50`, `p90`, `p95`, `p99`, `p99.9`) across millions of records via `quantile_cont()`.
150
+ - Discrete price-rung volume profile distribution.
151
+ - **Apache Parquet Compressed Export**: Direct export of tick universes to compressed `.parquet` files with Zstandard (`zstd`), Snappy, or GZIP compression (299k ticks compressed to 1.52 MB).
152
+
153
+ ### 5. Consolidated Level-2 Market Depth & Real-Time VWAP Slicing (`src/depth.py`)
154
+ - Real-time aggregation of multi-venue order books into a consolidated L2 depth ladder.
155
+ - Dynamic **VWAP Slippage Curve calculation**: computes estimated executed price, basis point slippage, and market impact across any requested order size.
156
+ - Real-time bid/ask liquidity imbalances and multi-venue depth visualization via `cli.py depth` and `cli.py vwap`.
157
+
158
+ ### 6. Institutional Financial Model & 5-Tab Excel Exporter (`src/exporter.py`)
159
+ - Translates live ticks, order book depth, and quality metrics into institutional-grade Microsoft Excel (`.xlsx`) workbooks:
160
+ - **Tab 1: Executive Summary & Microstructure KPIs**: Total volume, VWAP, spreads, crossed quote count, tick count.
161
+ - **Tab 2: Consolidated Market Depth**: Multi-venue aggregated bid/ask ladders with depth visualization.
162
+ - **Tab 3: VWAP Slippage Curve**: Execution slippage schedule across order tranches.
163
+ - **Tab 4: Quality & Quarantine Audit**: Detailed record of rejected/quarantined events with exact failure reasons.
164
+ - **Tab 5: OHLCV Candlesticks**: 5-second candle aggregates (Open, High, Low, Close, Volume, Trades).
165
+ - Automatic fallback to structured CSV report directories if `openpyxl` is not installed.
166
+ - One-command generation and instant launch: `mdrap export AAPL --open`.
167
+
168
+ ### 7. In-Place Live Terminal Ticker & Candlestick Charts (`src/terminal_display.py`)
169
+ - **Zero-Scroll In-Place Display**: Updates live market quotes and candlestick charts in-place using ANSI cursor repositioning without cluttering terminal history.
170
+ - **High-Resolution Candlestick Visualization**: Renders 3-character columns (` █ `, ` │ `, ` ┼ `) with distinct body margins and box-drawing wicks.
171
+ - **Outlier-Resilient Percentile Scaling**: Visual bounds clamped to the 10th–90th price percentiles so extreme anomalies never crush normal candles into a flat line.
172
+ - **Aligned Volume Histogram**: Synchronized volume bars underneath each candle column.
173
+ - Dedicated modes: full live ticker dashboard (`mdrap live`), ticker-only mode (`mdrap live AAPL --ticker-only`), and standalone historical chart viewer (`mdrap chart AAPL`).
174
+
175
+ ### 8. Synthetic Consolidated NBBO & Multi-Market Connectors (`src/live.py`, `src/bbo.py`)
176
+ - Ingests real-time prices across major global crypto exchanges (**Binance, Coinbase, Kraken, OKX, Bybit**) and global equities (**AAPL, MSFT, NVDA, TSLA, SPY, QQQ, GOLD**).
177
+ - Computes global tightest bid/ask spread, mid-price, and real-time venue attribution with crossed-market flags.
178
+
179
+ ### 9. Live Watchdog & Automated Source Failover (`src/watchdog.py`)
180
+ - Real-time source reliability tracking with silence detection and degradation alerts.
181
+ - Automated failover circuit breaker: dynamically evicts silent or corrupt feeds from the consolidated book with hysteresis recovery.
182
+
183
+ ### 10. Immutable Raw Event Archive & Deterministic Replay (`src/archive.py`)
184
+ - Date- and source-partitioned write-ahead JSONL log capturing every raw event before processing.
185
+ - Deterministic event replay engine allows historical backtesting and auditing through the complete pipeline.
186
+
187
+ ### 11. Enterprise Security & Cryptographic Merkle Audit (`src/security.py`)
188
+ - **HMAC-SHA256 Feed Authentication**: Anti-spoofing signature verification with pre-shared feed secrets.
189
+ - **Role-Based Access Control (RBAC)**: Privilege boundaries across `VIEWER`, `OPERATOR`, and `ADMIN`.
190
+ - **Token Bucket Rate Limiting**: Shields pipeline against denial-of-service and quote flooding ($20,000\text{ eps}$).
191
+ - **Tamper-Evident Merkle Audit Log**: Cryptographically chained SHA-256 hash trail in SQLite with standalone verification via `mdrap audit --verify`.
192
+
193
+ ### 12. Binary Shared Memory IPC Transport (`src/shm.py`, `src/protocol.py`)
194
+ - Zero-copy lock-free ring buffer for ultra-low latency IPC between the ingestion daemon and trading algorithms.
195
+
196
+ ---
197
+
198
+ ## Architectural Progression & Benchmarks
199
+
200
+ Measured on identical 10,000-event workloads (`seed=42`) with fixed ground-truth errors:
201
+
202
+ | Architecture | Throughput (eps) | Proc Latency p50 | Proc Latency Max | Design Highlight |
203
+ |---|:---:|:---:|:---:|---|
204
+ | **V1 Synchronous Baseline** | **29,402 eps** | **14.6 µs** (14,600 ns) | 255.8 µs | Pure Python, synchronous loop, SQLite batched writes |
205
+ | **V2 Decoupled Streaming** | **22,351 eps** | **15.3 µs** (15,300 ns) | 19.9 ms | Multi-threaded in-memory queue bus with backpressure |
206
+ | **V4 Native C Hot Path** | **27,274 eps** | **15.7 µs** (15,700 ns) | 265.2 µs | GCC `-O3` ctypes binding with fallback safety |
207
+ | **Native C Direct Batch** | **18,669,082 eps** | **50.0 ns** (0.050 µs) | 110.0 ns | Zero-copy SIMD contiguous arrays in CPU L1 cache |
208
+
209
+ ### Latency Hierarchy & Physical Bounds
210
+
211
+ - **Native C Batch (50.0 ns) vs Pipeline (15.7 µs)**: The **50.0 ns** figure measures the C accelerator alone operating on pre-batched contiguous arrays in CPU L1 cache. The **15.7 µs** figure is the same accelerator measured end-to-end inside the full pipeline (gateway → quality engine → reconciliation → storage).
212
+ - **Physics of the "~5 Nanosecond" Myth**: At 4.0 GHz, one CPU cycle is 0.25 nanoseconds; **5 nanoseconds is exactly 20 CPU cycles**. Software running on general-purpose operating systems cannot receive network packets, parse payloads, and evaluate state in 5 nanoseconds (PCIe bus transfer from NIC to RAM alone takes 100–250 ns). Sub-20ns latencies are only physically possible in dedicated **hardware FPGA gate logic** (e.g. AMD Xilinx UltraScale+).
213
+
214
+ #### The 3 Measurable Platform Latency Tiers
215
+ | Tier | Scope / Boundary | Latency (p50) | Throughput | Use Case |
216
+ |---|---|:---:|:---:|---|
217
+ | **Tier 1: Core C L1 Algorithm** | Isolated Native C rolling math (`fastpath.c`) | **50.0 ns** | 18,669,082 eps | Micro-benchmark core arithmetic |
218
+ | **Tier 2: In-Memory Pipeline** | End-to-end stream: gateway + 7 quality rules + BBO | **15.7 µs** | ~63,000 eps | Real-time IPC streaming to bots |
219
+ | **Tier 3: Durable Ingest-to-Disk** | Full pipeline with SQLite WAL batched disk persistence | **783.6 µs** | 18,000–22,000 eps | Regulatory audit & persistent storage |
220
+
221
+ ---
222
+
223
+ ## Quick Start
224
+
225
+ ### Installation
226
+
227
+ Clone the repository and install optional dependencies:
228
+ ```bash
229
+ git clone https://github.com/Aryan-20-04/mdrap.git
230
+ cd mdrap
231
+
232
+ # MDRAP has ZERO mandatory dependencies (runs 100% on standard library).
233
+ # Install optional visualization, financial exporter, and test packages:
234
+ pip install -r requirements.txt
235
+ ```
236
+
237
+ Compile the Native C accelerator (optional — transparent pure-Python fallback is included):
238
+ ```bash
239
+ python build_fastpath.py
240
+ ```
241
+
242
+ ---
243
+
244
+ ### 1. Interactive Wall Street & Quant Terminal
245
+ Run `mdrap` (or `.\mdrap.bat`) with zero arguments to enter the pre-warmed shell:
246
+ ```bash
247
+ .\mdrap.bat
248
+ ```
249
+ ```text
250
+ mdrap> LIVE AAPL # Live market stream with in-place updating table & candlestick chart
251
+ mdrap> CHART BTC/USD # Standalone visual candlestick chart with volume histogram
252
+ mdrap> DEPTH AAPL # Consolidated Level-2 market depth ladder
253
+ mdrap> VWAP AAPL 1000 # Calculate VWAP slippage curve for 1,000 shares
254
+ mdrap> EXPORT AAPL --open# Export 5-tab financial model workbook to Excel and open it
255
+ mdrap> BTC BBO # 5-Venue Consolidated NBBO across Binance, Coinbase, Kraken, OKX, Bybit
256
+ mdrap> TOP # Launch real-time full-screen service cockpit
257
+ mdrap> STRESS # Run multi-directional stress tests and 1M-1B scale analysis
258
+ mdrap> AUDIT # Cryptographically verify tamper-evident Merkle hash chain
259
+ mdrap> ? # Open clean 4-quadrant command palette
260
+ ```
261
+
262
+ You can also run all commands directly from PowerShell / CMD / Bash:
263
+ ```bash
264
+ .\mdrap.bat live AAPL # In-place terminal ticker & candlestick chart
265
+ .\mdrap.bat live AAPL --ticker-only # Clean single-table ticker view
266
+ .\mdrap.bat chart AAPL # Unicode candlestick chart
267
+ .\mdrap.bat depth AAPL # L2 market depth ladder
268
+ .\mdrap.bat vwap AAPL --size 500 # Execution slippage schedule
269
+ .\mdrap.bat export AAPL --open # Generate Excel model (.xlsx) & open immediately
270
+ .\mdrap.bat bbo BTC/USD # 5-Venue crypto NBBO quote
271
+ .\mdrap.bat top # Terminal service cockpit
272
+ .\mdrap.bat stress --module quality # Benchmark C hotpath (18.6M eps)
273
+ ```
274
+
275
+ ---
276
+
277
+ ### 2. Headless Daemon & Live IPC Streaming
278
+ In **Terminal 1**, start the background ingestion daemon:
279
+ ```bash
280
+ # High-speed simulated multi-venue feed
281
+ .\mdrap.bat daemon --speed 2000
282
+
283
+ # Or live multi-venue market feeds (Binance, Coinbase, Kraken, OKX, Bybit)
284
+ .\mdrap.bat daemon --live
285
+ ```
286
+
287
+ In **Terminal 2**, stream clean canonical ticks directly to stdout or pipe into trading algorithms:
288
+ ```bash
289
+ # Formatted ANSI color stream
290
+ .\mdrap.bat sub BTC/USD
291
+
292
+ # Raw JSON stream for automated algorithmic bots or jq
293
+ .\mdrap.bat sub BTC/USD --json | jq '{bid: .bbo.bid, ask: .bbo.ask}'
294
+ ```
295
+
296
+ In **Terminal 3**, launch the real-time terminal monitor:
297
+ ```bash
298
+ .\mdrap.bat top
299
+ ```
300
+
301
+ ---
302
+
303
+ ## Keyboard-First Speed Ergonomics
304
+
305
+ MDRAP provides sub-second keyboard ergonomics inspired by Bloomberg terminals (`<TICKER> <FUNCTION> <GO>`), eliminating long CLI commands for high-speed trading desks and quant operations:
306
+
307
+ ### 1. Wall Street 2-Token Mnemonic Shell
308
+ Inside the interactive shell (`.\mdrap.bat` or `./mdrap`), type:
309
+ - `AAPL C` -> Candlestick Chart HUD
310
+ - `BTC D` -> Consolidated Level-2 Depth Book Ladder
311
+ - `AAPL V` -> Institutional Real-Time VWAP Slippage Curve
312
+ - `AAPL P` -> Polygon.io Streaming WebSocket Feed
313
+ - `ES B` -> Databento Binary DBN Fast Streaming Feed
314
+ - `AAPL X` -> 5-Tab Financial Model Excel Export (Auto-Opens)
315
+ - `AAPL` (ticker only) -> Instant Consolidated NBBO Quote
316
+ - `1` to `9` -> Instant 1-Key Launches (`1` = Live BTC, `2` = NBBO, `3` = Cockpit, `4` = Chart, etc.)
317
+
318
+ ### 2. Live In-Stream Hotkeys (Non-Blocking Keystrokes)
319
+ During any live stream (`mdrap live`, `mdrap top`, `mdrap depth`), hands never leave the keyboard:
320
+ - `[Space]` -> **Freeze / Unfreeze Frame**: Pauses the live rendering so you can inspect fast-moving prints and L2 depth levels without them scrolling away. Pressing `[Space]` again resumes real-time updates.
321
+ - `[q]` or `[Esc]` -> **Instant Clean Exit**: Cleanly restores terminal cursor without Python stack traces.
322
+ - `[c]` -> **Toggle Candlestick HUD**: Show or hide the inline technical chart.
323
+ - `[d]` -> **Toggle Level-2 Depth Ladder**: Show or hide the consolidated depth rungs.
324
+ - `[Tab]` / `[1-9]` -> **Switch Active Symbol Focus**: Cycle or jump between active universe tickers on the fly.
325
+
326
+ ### 3. Single-Letter OS CLI Shortcuts
327
+ From your terminal (PowerShell, CMD, or bash):
328
+ ```bash
329
+ mdrap c AAPL # Candlestick Chart
330
+ mdrap d BTC # Level-2 Depth Ladder
331
+ mdrap v AAPL # Real-Time VWAP Curve
332
+ mdrap p AAPL # Polygon.io Streaming Feed
333
+ mdrap b ES # Databento DBN Streaming Feed
334
+ mdrap x AAPL # 5-Tab Excel Export
335
+ mdrap AAPL # Instant Best Bid & Offer Quote
336
+ ```
337
+
338
+ ---
339
+
340
+ ## CLI Command Reference
341
+
342
+ | Command | Aliases | Description |
343
+ |---|---|---|
344
+ | `status` | `s`, `stat` | Show comprehensive platform status overview, database statistics, and engine readiness |
345
+ | `shell` | `sh` | Launch low-latency interactive slash-command terminal shell |
346
+ | `live` | `stream`, `watch`, `ticker` | Stream live market ticks with in-place updating table & candlestick chart (`--feed polygon/databento`) |
347
+ | `feed` | `stream-feed`, `feeds` | Inspect, benchmark, and test direct streaming feeds (Polygon, Databento, Crypto WS) |
348
+ | `chart` | `candle`, `graph` | Display visual in-terminal ASCII/Unicode candlestick chart with volume histogram |
349
+ | `depth` | `l2`, `book`, `ladder` | Display Consolidated Level-2 Multi-Venue Market Depth Ladder |
350
+ | `vwap` | `curve`, `slip` | Compute multi-venue real-time VWAP execution & slippage curves |
351
+ | `export` | `exp`, `excel`, `xlsx` | Export market microstructure data to 5-tab Excel (.xlsx) or CSV package |
352
+ | `bbo` | `nbbo` | Query Synthetic Consolidated Best Bid & Offer (NBBO) across 5 exchanges |
353
+ | `run` | `r` | Run the validation pipeline against the simulator (with live HUD) |
354
+ | `benchmark` | `bench`, `b` | Run controlled benchmark and score quality detection against ground truth |
355
+ | `compare` | `comp`, `c` | Run V1, V2, and V4 Native C on identical workloads and print comparative report |
356
+ | `loadtest` | `load`, `l` | Sweep increasing event volumes (10k to 250k) and report performance trend |
357
+ | `stress` | `str` | Run multi-directional stress testing suite and 1M–1B transaction scale analysis |
358
+ | `chaos` | `ch` | Execute automated chaos & resilience drills (source kill, network jitter, storage outage) |
359
+ | `watchdog` | `w`, `wd` | Show source health status, silence alerts, and automated failover events |
360
+ | `security` | `sec` | Display platform security posture, HMAC verification, RBAC, and rate limiting status |
361
+ | `keys` | — | Manage client API keys and entitlement tiers (`FREE`, `PRO`, `INSTITUTIONAL`) |
362
+ | `audit` | — | View and cryptographically verify tamper-evident Merkle hash audit logs |
363
+ | `query` | `q` | Inspect stored SQLite tables: health, latest ticks, lineage trail, and quarantine |
364
+ | `replay` | `rep` | Replay archived raw events deterministically through the pipeline |
365
+ | `archive` | `arc` | Show immutable raw event JSONL archive statistics |
366
+ | `analytics` | `a`, `an` | Query 5s OHLCV candles, bid-ask spreads, and realized volatility |
367
+ | `columnar` | `col`, `duck`, `duckdb` | Query DuckDB columnar storage, vectorized SIMD OHLCV/VWAP, zero-copy SQLite sync, and Parquet export |
368
+ | `daemon` | `d` | Run headless streaming socket daemon service (Spec §18) |
369
+ | `sub` | `subscribe`, `listen` | Subscribe to daemon stream and output formatted ticks or depth to stdout |
370
+ | `top` | `mon`, `monitor` | Launch dynamic full-screen terminal service cockpit |
371
+ | `test-all` | `test`, `t` | Run all platform CLI commands, benchmarks, queries, and verifications in one pass |
372
+
373
+ ---
374
+
375
+ ## Verification & Testing
376
+
377
+ MDRAP includes a rigorous test suite of **238 automated unit, integration, security, and chaos tests** covering 100% of pipeline stages:
378
+
379
+ ```bash
380
+ # Run the complete automated test suite
381
+ pytest tests/ -v
382
+ ```
383
+
384
+ ```bash
385
+ # Run the comprehensive platform verification scorecard
386
+ .\mdrap.bat test-all
387
+ ```
388
+
389
+ All tests execute with deterministic seeds and verify ground-truth fault detection, boundary conditions, C fallback mechanisms, and zero memory leaks.
390
+
391
+ ---
392
+
393
+ ## Repository Structure
394
+
395
+ ```text
396
+ mdrap/
397
+ ├── cli.py # Unified CLI, interactive quant shell, and command dispatcher
398
+ ├── mdrap.bat # Windows zero-config launcher script
399
+ ├── build_fastpath.py # Native C accelerator build script (GCC / Clang / MSVC)
400
+ ├── config.yaml # Externalized quality thresholds, anomaly windows & security policies
401
+ ├── pyproject.toml # PEP 518/621 project configuration, scripts & package packaging
402
+ ├── requirements.txt # Optional runtime & dev dependencies (pure stdlib default)
403
+ ├── LICENSE # MIT License
404
+ ├── .gitignore # Production-grade gitignore for Python, C artifacts, data, and reports
405
+
406
+ ├── src/ # Core MDRAP Platform Engine
407
+ │ ├── analytics.py # 5s OHLCV candles, bid-ask spread tracking, Welford realized volatility
408
+ │ ├── archive.py # Immutable write-ahead JSONL archive & deterministic replay
409
+ │ ├── bbo.py # Synthetic Consolidated BBO (NBBO) multi-venue engine
410
+ │ ├── benchmark.py # Micro-benchmark harness & ground-truth scoring
411
+ │ ├── broker.py # Thread-safe in-memory streaming bus with backpressure
412
+ │ ├── chaos.py # Automated failure injection & chaos drill suite (Spec §15)
413
+ │ ├── client.py # Low-latency streaming client SDK with reconnect logic
414
+ │ ├── columnar.py # DuckDB columnar engine, zero-copy SQLite scanner & Parquet exporter
415
+ │ ├── config.py # Central configuration manager & asset-class override resolver
416
+ │ ├── dashboard.py # Real-time terminal pipeline telemetry HUD
417
+ │ ├── databento_feed.py# Databento DBN binary decoding (MBP-1, MBP-10, Trades) & streaming
418
+ │ ├── depth.py # Consolidated L2 depth aggregation & VWAP slippage curve engine
419
+ │ ├── exporter.py # Institutional 5-tab Excel (.xlsx) & CSV financial model exporter
420
+ │ ├── fastpath.c # Native C hot path accelerator (8,192 symbols, GCC -O3)
421
+ │ ├── fastpath.dll # Pre-compiled high-performance native C shared library
422
+ │ ├── fastpath.py # C ctypes wrapper with transparent pure-Python boundary fallback
423
+ │ ├── feed_handler.py # Unified streaming supervisor (Polygon, Databento, Crypto WebSockets)
424
+ │ ├── gateway.py # Ingestion gateway, timestamp recorder, and schema normalizer
425
+ │ ├── live.py # Multi-exchange connectors (Binance, Coinbase, Kraken, OKX, Bybit, Equities)
426
+ │ ├── metrics.py # High-resolution hardware nanosecond latency & percentile telemetry
427
+ │ ├── models.py # CanonicalEvent, RawEvent, QualityStatus, Reason dataclasses
428
+ │ ├── pipeline.py # V1 synchronous baseline pipeline (ground-truth reference)
429
+ │ ├── pipeline_v2.py # V2 decoupled streaming pipeline with bounded queue broker
430
+ │ ├── polygon_feed.py # Polygon.io streaming WebSocket connector (Quotes, Trades, Bars)
431
+ │ ├── protocol.py # Binary serialization & framing protocol for IPC
432
+ │ ├── quality.py # 7-rule data quality evaluation engine (Spec §7)
433
+ │ ├── reconciliation.py# Multi-feed cross-reconciliation & dynamic reliability scoring
434
+ │ ├── security.py # HMAC-SHA256 signing, RBAC, Token Bucket rate limiter, Merkle audit log
435
+ │ ├── service.py # Headless streaming daemon, authenticated socket, and service cockpit
436
+ │ ├── shm.py # Lock-free binary shared memory ring buffer IPC
437
+ │ ├── simulator.py # Deterministic feed simulator with seeded anomaly injections
438
+ │ ├── storage.py # Batched SQLite store (canonical, quarantine, lineage, audit, health)
439
+ │ ├── stresstest.py # Multi-directional stress benchmarks & 1B-scale profiling
440
+ │ ├── term.py # Auto-responsive terminal styling with stdlib fallback
441
+ │ ├── terminal_display.py # In-place live terminal ticker & ANSI candlestick chart renderer
442
+ │ ├── watchdog.py # Live source watchdog, silence detection & automated failover
443
+ │ └── ws_feed.py # Async WebSocket live market feed connector
444
+
445
+ ├── tests/ # 238 Automated Unit & Integration Tests (100% Passing)
446
+ │ ├── test_analytics.py
447
+ │ ├── test_archive.py
448
+ │ ├── test_bbo.py
449
+ │ ├── test_chaos.py
450
+ │ ├── test_cli.py
451
+ │ ├── test_client.py
452
+ │ ├── test_columnar.py
453
+ │ ├── test_config.py
454
+ │ ├── test_databento_feed.py
455
+ │ ├── test_depth.py
456
+ │ ├── test_entitlements.py
457
+ │ ├── test_export.py
458
+ │ ├── test_fastpath.py
459
+ │ ├── test_feed_handler.py
460
+ │ ├── test_hardening.py
461
+ │ ├── test_keyboard_shortcuts.py
462
+ │ ├── test_live.py
463
+ │ ├── test_pipeline_integration.py
464
+ │ ├── test_polygon_feed.py
465
+ │ ├── test_protocol.py
466
+ │ ├── test_quality.py
467
+ │ ├── test_security.py
468
+ │ ├── test_service.py
469
+ │ ├── test_shm.py
470
+ │ ├── test_stresstest.py
471
+ │ ├── test_system_limitations.py
472
+ │ ├── test_terminal_display.py
473
+ │ ├── test_v2_streaming.py
474
+ │ ├── test_vwap.py
475
+ │ ├── test_watchdog.py
476
+ │ └── test_ws_feed.py
477
+
478
+ ├── docs/ # Architecture & Platform Specifications
479
+ │ ├── USER_GUIDE.md # Comprehensive Operator & User Manual (all commands, flags, workflows)
480
+ │ ├── architecture.md # Full platform architecture specification (V1–V4)
481
+ │ ├── audit-log-format.md # Merkle tree hash chain format & audit specification (§19)
482
+ │ ├── benchmark-methodology.md # Scientific measurement standards & latency hierarchy
483
+ │ ├── data-model.md # Canonical event schema & lineage data model
484
+ │ └── quality-rules.md # 7-rule data quality evaluation definitions & fault scoring
485
+
486
+ └── benchmarks/ # Immutable benchmark runs, JSON reports, and cProfile traces
487
+ ```
488
+
489
+ ---
490
+
491
+ ## License
492
+
493
+ This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.