ShawnChamberlain commited on
Commit
ebcde1f
·
verified ·
1 Parent(s): 1afb023

Publish Microstructure code and documentation package

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Microstructure/.gitignore +36 -0
  2. Microstructure/.python-version +1 -0
  3. Microstructure/AGENTS.md +66 -0
  4. Microstructure/LICENSE +21 -0
  5. Microstructure/Makefile +202 -0
  6. Microstructure/README.md +509 -0
  7. Microstructure/STATUS.md +163 -0
  8. Microstructure/configs/exploratory_aggtrades_2026-08-05_08.toml +58 -0
  9. Microstructure/configs/m8_l2_analysis.toml +100 -0
  10. Microstructure/configs/m8_l2_capture_study.toml +81 -0
  11. Microstructure/configs/m8_multidate_trade_study.toml +58 -0
  12. Microstructure/configs/public_sample.toml +63 -0
  13. Microstructure/configs/smoke.toml +57 -0
  14. Microstructure/dashboard/app.py +189 -0
  15. Microstructure/data/_ingestion_manifests/.gitkeep +1 -0
  16. Microstructure/data/derived/.gitkeep +1 -0
  17. Microstructure/data/models/.gitkeep +1 -0
  18. Microstructure/data/normalized/.gitkeep +1 -0
  19. Microstructure/data/quality/.gitkeep +1 -0
  20. Microstructure/docs/DATA_CONTRACT.md +269 -0
  21. Microstructure/docs/DATA_POLICY.md +45 -0
  22. Microstructure/docs/DECISION_LOG.md +487 -0
  23. Microstructure/docs/EXPLORATORY_AGGTRADES_2026_08_05_08.md +59 -0
  24. Microstructure/docs/M8_L2_ANALYSIS_CONTRACT.md +183 -0
  25. Microstructure/docs/M8_L2_PROTOCOL.md +103 -0
  26. Microstructure/docs/M8_MULTIDATE_TRADE_PROTOCOL.md +269 -0
  27. Microstructure/docs/PROJECT_PLAN.md +135 -0
  28. Microstructure/docs/PUBLICATION.md +29 -0
  29. Microstructure/docs/PUBLIC_TRADE_PROTOCOL.md +99 -0
  30. Microstructure/docs/RESEARCH_PROTOCOL.md +129 -0
  31. Microstructure/portfolio/interview_story.md +125 -0
  32. Microstructure/portfolio/resume_bullets.md +26 -0
  33. Microstructure/portfolio/ten_minute_presentation_outline.md +89 -0
  34. Microstructure/project.yaml +45 -0
  35. Microstructure/pyproject.toml +62 -0
  36. Microstructure/reports/executive_memo.md +95 -0
  37. Microstructure/reports/methodology_limitations.md +189 -0
  38. Microstructure/reports/model_comparison.md +12 -0
  39. Microstructure/reports/technical_report.md +80 -0
  40. Microstructure/src/microstructure/__init__.py +10 -0
  41. Microstructure/src/microstructure/cli.py +2003 -0
  42. Microstructure/src/microstructure/config.py +341 -0
  43. Microstructure/src/microstructure/data/__init__.py +33 -0
  44. Microstructure/src/microstructure/data/binance.py +1330 -0
  45. Microstructure/src/microstructure/data/binance_archive.py +1459 -0
  46. Microstructure/src/microstructure/data/book.py +483 -0
  47. Microstructure/src/microstructure/data/evidence_budget.py +208 -0
  48. Microstructure/src/microstructure/data/quality.py +1103 -0
  49. Microstructure/src/microstructure/data/schemas.py +223 -0
  50. Microstructure/src/microstructure/data/storage.py +605 -0
Microstructure/.gitignore ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ .idea/
3
+ .vscode/
4
+ .venv/
5
+ __pycache__/
6
+ *.py[cod]
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
11
+ .coverage
12
+ htmlcov/
13
+
14
+ # External and generated research data must stay local.
15
+ data/raw/**
16
+ data/normalized/**
17
+ data/derived/**
18
+ data/models/**
19
+ data/quality/**
20
+ data/_ingestion_manifests/**
21
+ data/m8/**
22
+ data/m8_l2/**
23
+ data/exploratory_aggtrades_2026-08-05_08/**
24
+ !data/raw/.gitkeep
25
+ !data/normalized/.gitkeep
26
+ !data/derived/.gitkeep
27
+ !data/models/.gitkeep
28
+ !data/quality/.gitkeep
29
+ !data/_ingestion_manifests/.gitkeep
30
+
31
+ # Generated run artifacts are reproducible and may contain large files.
32
+ artifacts/runs/**
33
+ !artifacts/runs/.gitkeep
34
+
35
+ # Generated dashboard/runtime files.
36
+ .streamlit/secrets.toml
Microstructure/.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
Microstructure/AGENTS.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repository instructions
2
+
3
+ These instructions apply to the entire repository.
4
+
5
+ ## Mission and safety boundary
6
+
7
+ Build a reproducible research and simulation system for short-horizon market
8
+ microstructure. The repository must never place live orders, authenticate to a
9
+ trading account, or imply that a simulated result is executable profit.
10
+
11
+ ## Research integrity
12
+
13
+ - Never invent observations, performance, statistical significance, or a data
14
+ source. Label synthetic, fixture, smoke-test, partial, and full-data results.
15
+ - Keep predictive quality, execution assumptions, and strategy results separate.
16
+ - Every generated result must include the configuration hash, input manifest
17
+ hashes, UTC data interval, code version or explicit `UNBORN`, and dirty state.
18
+ - Preserve raw observations. Put transformations in normalized or derived data
19
+ and log exclusions; do not silently repair suspect events.
20
+ - Treat a timestamp at decision time `t` as unavailable unless its event and
21
+ receipt ordering prove it was observable at `t`. Features use information at
22
+ or before `t`; labels begin strictly after `t`.
23
+ - Do not tune against the final test period. Use time-ordered splits, purge
24
+ overlapping label horizons, and embargo adjacent folds when configured.
25
+
26
+ ## Engineering conventions
27
+
28
+ - Target Python 3.12 and a local Apple Silicon machine with 16 GB RAM.
29
+ - Keep core logic in `src/microstructure`; notebooks may call but not duplicate it.
30
+ - Prefer Polars lazy/streaming scans and partitioned Parquet. DuckDB may query
31
+ partitions without loading the full data set.
32
+ - New data sources implement the adapter interfaces; exchange-specific fields do
33
+ not leak into normalized research modules.
34
+ - Store timestamps as UTC epoch nanoseconds and prices/quantities as decimal-safe
35
+ integer ticks/lots where the adapter supplies metadata; floating research
36
+ columns must document their units.
37
+ - Randomized procedures require an explicit seed.
38
+ - External raw data belongs under ignored `data/raw`; only small, documented test
39
+ fixtures belong in Git.
40
+
41
+ ## Verification
42
+
43
+ Run focused tests after each meaningful phase and `make check` before handoff.
44
+ Tests must cover sequence gaps and book invariants, temporal leakage, purged
45
+ splits, deterministic simulations, partial fills, fees, and latency. A test may
46
+ not call the public internet; mock adapters at the HTTP boundary.
47
+
48
+ Primary commands:
49
+
50
+ ```text
51
+ make setup
52
+ make download-sample
53
+ make validate-data
54
+ make smoke
55
+ make test
56
+ make reproduce-sample
57
+ make report
58
+ make dashboard
59
+ ```
60
+
61
+ ## Documentation discipline
62
+
63
+ Record material assumptions and reversals in `docs/DECISION_LOG.md`. Keep
64
+ `STATUS.md` honest and current. Update `docs/PROJECT_PLAN.md` acceptance evidence
65
+ when a milestone moves state. Do not manually paste model metrics into prose;
66
+ reports must read machine-generated run artifacts.
Microstructure/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Microstructure Research Project
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.
Microstructure/Makefile ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PYTHON_BIN ?= python3.12
2
+ PYTHON ?= .venv/bin/python
3
+ RUN_DIR ?= artifacts/runs/sample-smoke
4
+ PUBLIC_RUN_DIR ?= artifacts/runs/binance-public-sample
5
+ SMOKE_CONFIG ?= configs/smoke.toml
6
+ PUBLIC_CONFIG ?= configs/public_sample.toml
7
+ PUBLIC_INGESTION_MANIFEST ?=
8
+ PUBLIC_INGESTION_MANIFEST_SHA256 ?=
9
+ M8_CONFIG ?= configs/m8_multidate_trade_study.toml
10
+ M8_DATA_ROOT ?= data/m8
11
+ M8_RUN_DIR ?= artifacts/runs/binance-m8-multidate
12
+ M8_RAW_MANIFEST ?=
13
+ M8_RAW_MANIFEST_SHA256 ?=
14
+ M8_L2_CONFIG ?= configs/m8_l2_capture_study.toml
15
+ M8_L2_ANALYSIS_CONFIG ?= configs/m8_l2_analysis.toml
16
+ M8_L2_DATA_ROOT ?= data/m8_l2
17
+ M8_L2_SESSION_DATE ?=
18
+ M8_L2_BUNDLE_DIR ?=
19
+ M8_L2_TRAIN_BUNDLE_DIR ?=
20
+ M8_L2_TRAIN_MANIFEST_SHA256 ?=
21
+ M8_L2_TRAIN_CHECKSUMS_SHA256 ?=
22
+ M8_L2_VALIDATION_BUNDLE_DIR ?=
23
+ M8_L2_VALIDATION_MANIFEST_SHA256 ?=
24
+ M8_L2_VALIDATION_CHECKSUMS_SHA256 ?=
25
+ M8_L2_DEVELOPMENT_LOCK_DIR ?=
26
+ M8_L2_DEVELOPMENT_LOCK_SHA256 ?=
27
+ M8_L2_PRIMARY_BUNDLE_DIR ?=
28
+ M8_L2_PRIMARY_MANIFEST_SHA256 ?=
29
+ M8_L2_PRIMARY_CHECKSUMS_SHA256 ?=
30
+ M8_L2_REPLICATION_BUNDLE_DIR ?=
31
+ M8_L2_REPLICATION_MANIFEST_SHA256 ?=
32
+ M8_L2_REPLICATION_CHECKSUMS_SHA256 ?=
33
+ M8_L2_RUN_DIR ?= artifacts/runs/binance-m8-live-l2
34
+ M8_L2_RUN_MANIFEST_SHA256 ?=
35
+ M8_L2_RUN_CHECKSUMS_SHA256 ?=
36
+ M8_L2_REPORT_DIR ?= artifacts/runs/binance-m8-live-l2-reports
37
+
38
+ .PHONY: setup download-sample download-m8 capture-m8-l2-session verify-m8-l2-session lock-m8-l2-development verify-m8-l2-development-lock reproduce-m8-l2 verify-m8-l2-run report-m8-l2 validate-data validate-public-data smoke check-smoke test reproduce-sample reproduce-public-sample reproduce-m8 verify-run verify-public-run verify-m8-run report report-public report-m8 dashboard dashboard-public lint typecheck check
39
+
40
+ setup:
41
+ @if command -v uv >/dev/null 2>&1; then \
42
+ uv sync --locked --extra dev; \
43
+ else \
44
+ "$(PYTHON_BIN)" -m venv .venv; \
45
+ .venv/bin/python -m pip install --upgrade pip; \
46
+ .venv/bin/pip install -e ".[dev]"; \
47
+ fi
48
+
49
+ download-sample:
50
+ $(PYTHON) -m microstructure.cli ingest --config $(PUBLIC_CONFIG)
51
+
52
+ download-m8:
53
+ $(PYTHON) -m microstructure.cli acquire-m8 --config "$(M8_CONFIG)" --output-root "$(M8_DATA_ROOT)"
54
+
55
+ capture-m8-l2-session:
56
+ @test -n "$(M8_L2_SESSION_DATE)" || { echo "M8_L2_SESSION_DATE is required"; exit 2; }
57
+ @status=0; $(PYTHON) -m microstructure.cli capture-m8-l2-session --config "$(M8_L2_CONFIG)" --date "$(M8_L2_SESSION_DATE)" --output-root "$(M8_L2_DATA_ROOT)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status"
58
+
59
+ verify-m8-l2-session:
60
+ @test -n "$(M8_L2_BUNDLE_DIR)" || { echo "M8_L2_BUNDLE_DIR is required"; exit 2; }
61
+ $(PYTHON) -m microstructure.cli verify-m8-l2-session --config "$(M8_L2_CONFIG)" --bundle-dir "$(M8_L2_BUNDLE_DIR)"
62
+
63
+ lock-m8-l2-development:
64
+ @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; }
65
+ @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; }
66
+ @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; }
67
+ @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; }
68
+ @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; }
69
+ @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; }
70
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; }
71
+ @status=0; $(PYTHON) -m microstructure.cli lock-m8-l2-development --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status"
72
+
73
+ verify-m8-l2-development-lock:
74
+ @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; }
75
+ @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; }
76
+ @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; }
77
+ @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; }
78
+ @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; }
79
+ @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; }
80
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; }
81
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; }
82
+ @status=0; $(PYTHON) -m microstructure.cli verify-m8-l2-development-lock --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status"
83
+
84
+ reproduce-m8-l2:
85
+ @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; }
86
+ @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; }
87
+ @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; }
88
+ @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; }
89
+ @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; }
90
+ @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; }
91
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; }
92
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; }
93
+ @test -n "$(M8_L2_PRIMARY_BUNDLE_DIR)" || { echo "M8_L2_PRIMARY_BUNDLE_DIR is required"; exit 2; }
94
+ @test -n "$(M8_L2_PRIMARY_MANIFEST_SHA256)" || { echo "M8_L2_PRIMARY_MANIFEST_SHA256 is required"; exit 2; }
95
+ @test -n "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" || { echo "M8_L2_PRIMARY_CHECKSUMS_SHA256 is required"; exit 2; }
96
+ @test -n "$(M8_L2_REPLICATION_BUNDLE_DIR)" || { echo "M8_L2_REPLICATION_BUNDLE_DIR is required"; exit 2; }
97
+ @test -n "$(M8_L2_REPLICATION_MANIFEST_SHA256)" || { echo "M8_L2_REPLICATION_MANIFEST_SHA256 is required"; exit 2; }
98
+ @test -n "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" || { echo "M8_L2_REPLICATION_CHECKSUMS_SHA256 is required"; exit 2; }
99
+ @status=0; $(PYTHON) -m microstructure.cli reproduce-m8-l2 --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --development-lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" --primary-bundle-dir "$(M8_L2_PRIMARY_BUNDLE_DIR)" --primary-manifest-sha256 "$(M8_L2_PRIMARY_MANIFEST_SHA256)" --primary-checksums-sha256 "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" --replication-bundle-dir "$(M8_L2_REPLICATION_BUNDLE_DIR)" --replication-manifest-sha256 "$(M8_L2_REPLICATION_MANIFEST_SHA256)" --replication-checksums-sha256 "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" --run-dir "$(M8_L2_RUN_DIR)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status"
100
+
101
+ verify-m8-l2-run:
102
+ @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; }
103
+ @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; }
104
+ @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; }
105
+ @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; }
106
+ @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; }
107
+ @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; }
108
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; }
109
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; }
110
+ @test -n "$(M8_L2_PRIMARY_BUNDLE_DIR)" || { echo "M8_L2_PRIMARY_BUNDLE_DIR is required"; exit 2; }
111
+ @test -n "$(M8_L2_PRIMARY_MANIFEST_SHA256)" || { echo "M8_L2_PRIMARY_MANIFEST_SHA256 is required"; exit 2; }
112
+ @test -n "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" || { echo "M8_L2_PRIMARY_CHECKSUMS_SHA256 is required"; exit 2; }
113
+ @test -n "$(M8_L2_REPLICATION_BUNDLE_DIR)" || { echo "M8_L2_REPLICATION_BUNDLE_DIR is required"; exit 2; }
114
+ @test -n "$(M8_L2_REPLICATION_MANIFEST_SHA256)" || { echo "M8_L2_REPLICATION_MANIFEST_SHA256 is required"; exit 2; }
115
+ @test -n "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" || { echo "M8_L2_REPLICATION_CHECKSUMS_SHA256 is required"; exit 2; }
116
+ @test -n "$(M8_L2_RUN_MANIFEST_SHA256)" || { echo "M8_L2_RUN_MANIFEST_SHA256 is required"; exit 2; }
117
+ @test -n "$(M8_L2_RUN_CHECKSUMS_SHA256)" || { echo "M8_L2_RUN_CHECKSUMS_SHA256 is required"; exit 2; }
118
+ @status=0; $(PYTHON) -m microstructure.cli verify-m8-l2-run --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --development-lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" --primary-bundle-dir "$(M8_L2_PRIMARY_BUNDLE_DIR)" --primary-manifest-sha256 "$(M8_L2_PRIMARY_MANIFEST_SHA256)" --primary-checksums-sha256 "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" --replication-bundle-dir "$(M8_L2_REPLICATION_BUNDLE_DIR)" --replication-manifest-sha256 "$(M8_L2_REPLICATION_MANIFEST_SHA256)" --replication-checksums-sha256 "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" --run-dir "$(M8_L2_RUN_DIR)" --run-manifest-sha256 "$(M8_L2_RUN_MANIFEST_SHA256)" --run-checksums-sha256 "$(M8_L2_RUN_CHECKSUMS_SHA256)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status"
119
+
120
+ report-m8-l2:
121
+ @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; }
122
+ @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; }
123
+ @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; }
124
+ @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; }
125
+ @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; }
126
+ @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; }
127
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; }
128
+ @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; }
129
+ @test -n "$(M8_L2_PRIMARY_BUNDLE_DIR)" || { echo "M8_L2_PRIMARY_BUNDLE_DIR is required"; exit 2; }
130
+ @test -n "$(M8_L2_PRIMARY_MANIFEST_SHA256)" || { echo "M8_L2_PRIMARY_MANIFEST_SHA256 is required"; exit 2; }
131
+ @test -n "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" || { echo "M8_L2_PRIMARY_CHECKSUMS_SHA256 is required"; exit 2; }
132
+ @test -n "$(M8_L2_REPLICATION_BUNDLE_DIR)" || { echo "M8_L2_REPLICATION_BUNDLE_DIR is required"; exit 2; }
133
+ @test -n "$(M8_L2_REPLICATION_MANIFEST_SHA256)" || { echo "M8_L2_REPLICATION_MANIFEST_SHA256 is required"; exit 2; }
134
+ @test -n "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" || { echo "M8_L2_REPLICATION_CHECKSUMS_SHA256 is required"; exit 2; }
135
+ @test -n "$(M8_L2_RUN_MANIFEST_SHA256)" || { echo "M8_L2_RUN_MANIFEST_SHA256 is required"; exit 2; }
136
+ @test -n "$(M8_L2_RUN_CHECKSUMS_SHA256)" || { echo "M8_L2_RUN_CHECKSUMS_SHA256 is required"; exit 2; }
137
+ @status=0; $(PYTHON) -m microstructure.cli report-m8-l2 --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --development-lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" --primary-bundle-dir "$(M8_L2_PRIMARY_BUNDLE_DIR)" --primary-manifest-sha256 "$(M8_L2_PRIMARY_MANIFEST_SHA256)" --primary-checksums-sha256 "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" --replication-bundle-dir "$(M8_L2_REPLICATION_BUNDLE_DIR)" --replication-manifest-sha256 "$(M8_L2_REPLICATION_MANIFEST_SHA256)" --replication-checksums-sha256 "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" --run-dir "$(M8_L2_RUN_DIR)" --run-manifest-sha256 "$(M8_L2_RUN_MANIFEST_SHA256)" --run-checksums-sha256 "$(M8_L2_RUN_CHECKSUMS_SHA256)" --output-dir "$(M8_L2_REPORT_DIR)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status"
138
+
139
+ validate-data:
140
+ $(PYTHON) -m microstructure.cli validate --config $(SMOKE_CONFIG)
141
+
142
+ validate-public-data:
143
+ $(PYTHON) -m microstructure.cli validate --config $(PUBLIC_CONFIG)
144
+
145
+ smoke:
146
+ $(PYTHON) -m microstructure.cli reproduce --config $(SMOKE_CONFIG) --run-dir $(RUN_DIR)
147
+
148
+ check-smoke:
149
+ @check_root="$$(mktemp -d)"; \
150
+ trap 'rm -rf "$$check_root"' EXIT; \
151
+ $(PYTHON) -m microstructure.cli reproduce --config $(SMOKE_CONFIG) --run-dir "$$check_root/run"
152
+
153
+ test:
154
+ $(PYTHON) -m pytest
155
+
156
+ reproduce-sample: smoke
157
+
158
+ reproduce-public-sample:
159
+ @test -n "$(PUBLIC_INGESTION_MANIFEST)" || { echo "PUBLIC_INGESTION_MANIFEST is required"; exit 2; }
160
+ @test -n "$(PUBLIC_INGESTION_MANIFEST_SHA256)" || { echo "PUBLIC_INGESTION_MANIFEST_SHA256 is required"; exit 2; }
161
+ $(PYTHON) -m microstructure.cli reproduce --config $(PUBLIC_CONFIG) --run-dir $(PUBLIC_RUN_DIR) --ingestion-manifest $(PUBLIC_INGESTION_MANIFEST) --ingestion-manifest-sha256 $(PUBLIC_INGESTION_MANIFEST_SHA256)
162
+
163
+ reproduce-m8:
164
+ @test -n "$(M8_RAW_MANIFEST)" || { echo "M8_RAW_MANIFEST is required"; exit 2; }
165
+ @test -n "$(M8_RAW_MANIFEST_SHA256)" || { echo "M8_RAW_MANIFEST_SHA256 is required"; exit 2; }
166
+ $(PYTHON) -m microstructure.cli reproduce-m8 --config "$(M8_CONFIG)" --run-dir "$(M8_RUN_DIR)" --raw-manifest "$(M8_RAW_MANIFEST)" --raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)"
167
+
168
+ verify-run:
169
+ $(PYTHON) -m microstructure.cli verify --run-dir $(RUN_DIR)
170
+
171
+ verify-public-run:
172
+ $(PYTHON) -m microstructure.cli verify --run-dir $(PUBLIC_RUN_DIR)
173
+
174
+ verify-m8-run:
175
+ @test -n "$(M8_RAW_MANIFEST)" || { echo "M8_RAW_MANIFEST is required"; exit 2; }
176
+ @test -n "$(M8_RAW_MANIFEST_SHA256)" || { echo "M8_RAW_MANIFEST_SHA256 is required"; exit 2; }
177
+ $(PYTHON) -m microstructure.cli verify-m8 --config "$(M8_CONFIG)" --run-dir "$(M8_RUN_DIR)" --raw-manifest "$(M8_RAW_MANIFEST)" --raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)"
178
+
179
+ report:
180
+ $(PYTHON) -m microstructure.cli report --run-dir $(RUN_DIR)
181
+
182
+ report-public:
183
+ $(PYTHON) -m microstructure.cli report --run-dir $(PUBLIC_RUN_DIR)
184
+
185
+ report-m8:
186
+ @test -n "$(M8_RAW_MANIFEST)" || { echo "M8_RAW_MANIFEST is required"; exit 2; }
187
+ @test -n "$(M8_RAW_MANIFEST_SHA256)" || { echo "M8_RAW_MANIFEST_SHA256 is required"; exit 2; }
188
+ $(PYTHON) -m microstructure.cli report-m8 --config "$(M8_CONFIG)" --run-dir "$(M8_RUN_DIR)" --raw-manifest "$(M8_RAW_MANIFEST)" --raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)"
189
+
190
+ dashboard:
191
+ $(PYTHON) -m streamlit run dashboard/app.py -- --run-dir $(RUN_DIR)
192
+
193
+ dashboard-public:
194
+ $(PYTHON) -m streamlit run dashboard/app.py -- --run-dir $(PUBLIC_RUN_DIR)
195
+
196
+ lint:
197
+ $(PYTHON) -m ruff check .
198
+
199
+ typecheck:
200
+ $(PYTHON) -m mypy src/microstructure
201
+
202
+ check: lint typecheck test check-smoke
Microstructure/README.md ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Order Flow to Price Impact
2
+
3
+ A research-only, event-driven market-microstructure platform for asking:
4
+
5
+ > When do order-flow imbalance, liquidity, and limit-order-book conditions
6
+ > predict short-horizon price movement, and how much apparent value survives
7
+ > fees, latency, uncertain fills, adverse selection, and inventory risk?
8
+
9
+ The project is deliberately reproducibility-first. It keeps market-data evidence,
10
+ predictive diagnostics, execution assumptions, and simulated outcomes separate.
11
+ It has no authenticated exchange client, account connection, or order-entry path.
12
+
13
+ > **Evidence boundary:** `SYNTHETIC_SMOKE` output verifies software behavior only.
14
+ > It is not market, alpha, profitability, or investment evidence.
15
+
16
+ ## Architecture
17
+
18
+ ```mermaid
19
+ flowchart LR
20
+ A["Public REST trades or deterministic synthetic events"] --> B["Raw bytes + immutable manifests"]
21
+ C["Optional public live diff-depth + REST snapshot"] --> B
22
+ B --> D["Versioned UTC-normalized Arrow schemas"]
23
+ D --> E["Partitioned, content-addressed Parquet"]
24
+ E --> F["Non-mutating quality findings"]
25
+ F --> G["Causal features + strictly future labels"]
26
+ G --> H["Purged expanding walk-forward models"]
27
+ H --> I["OOS-only execution simulation"]
28
+ I --> J["Frozen checksummed run bundle"]
29
+ J --> K["Generated reports + read-only dashboard"]
30
+ ```
31
+
32
+ The normalized event contract retains exchange time, local receipt time when
33
+ captured, the conservative availability clock used by research, exact integer
34
+ ticks/lots, sequence identifiers, and a continuity epoch. Features, labels,
35
+ folds, open orders, and markouts cannot cross a known book gap.
36
+
37
+ ## Quick start
38
+
39
+ Python 3.12 is required. The default acceptance path is deterministic and does
40
+ not need internet access:
41
+
42
+ ```bash
43
+ make setup
44
+ make check
45
+ make reproduce-sample
46
+ make report
47
+ ```
48
+
49
+ The frozen sample is written to `artifacts/runs/sample-smoke`; independently
50
+ rendered reports go to `artifacts/runs/sample-smoke-reports`. Both directories
51
+ are reproducible and intentionally ignored by Git.
52
+
53
+ To inspect the completed run:
54
+
55
+ ```bash
56
+ make verify-run
57
+ make dashboard
58
+ ```
59
+
60
+ The dashboard loads only checksum-verified artifacts. It does not download data,
61
+ fit models, rerun simulations, or place orders.
62
+
63
+ ## Credential-free public sample
64
+
65
+ The bounded public path downloads BTCUSDT and ETHUSDT aggregate trades from a
66
+ fixed UTC interval, fetches `exchangeInfo` for exact tick and lot scales, keeps
67
+ the response bytes, and writes raw and normalized manifests:
68
+
69
+ ```bash
70
+ make download-sample
71
+ .venv/bin/python -m microstructure.cli validate \
72
+ --config configs/public_sample.toml
73
+ ```
74
+
75
+ It uses Binance's public market-data-only REST base URL and requires no API key.
76
+ The adapter honors retryable status codes, `Retry-After`, and interrupted body
77
+ streams; paginates by trade ID to avoid losing tied timestamps; enforces a
78
+ response-byte ceiling; and imposes a small per-symbol row cap. Pages flow once
79
+ through disk-backed incremental validation into bounded Parquet batches. See
80
+ the official [Spot REST documentation](https://developers.binance.com/en/docs/products/spot/rest-api)
81
+ and [Spot WebSocket stream guide](https://developers.binance.com/en/docs/catalog/core-trading-spot-trading/api/ws-streams/~).
82
+
83
+ Historical public trade ingestion and live order-book collection are separate on
84
+ purpose. Public historical Spot depth is not assumed to exist. A book-based
85
+ empirical study begins only after a continuous local snapshot/delta epoch has
86
+ been captured and passed sequence checks.
87
+
88
+ Producing a public research bundle never scans for a "latest" input. Select the
89
+ immutable ingestion manifest explicitly by both path and digest:
90
+
91
+ ```bash
92
+ make reproduce-public-sample \
93
+ PUBLIC_INGESTION_MANIFEST=data/_ingestion_manifests/<manifest>.json \
94
+ PUBLIC_INGESTION_MANIFEST_SHA256=<64-character-sha256>
95
+ make verify-public-run
96
+ make report-public
97
+ ```
98
+
99
+ ## Frozen multi-date trade study
100
+
101
+ The prospective M8 trade-only study uses the complete BTCUSDT and ETHUSDT
102
+ Binance Spot daily aggregate-trade archives for 2024-01-03 through 2024-01-06.
103
+ Acquisition is deliberately separate from research production:
104
+
105
+ ```bash
106
+ # Networked, raw-only: authenticates ZIP/CHECKSUM/metadata evidence but never
107
+ # opens a CSV member or reads an economic field.
108
+ make download-m8
109
+
110
+ # Copy the manifest path and lowercase SHA-256 printed by download-m8.
111
+ # Production requires the exact clean committed source tree.
112
+ make reproduce-m8 \
113
+ M8_RAW_MANIFEST=data/m8/_manifests/<manifest>.json \
114
+ M8_RAW_MANIFEST_SHA256=<64-character-sha256>
115
+ make verify-m8-run \
116
+ M8_RAW_MANIFEST=data/m8/_manifests/<manifest>.json \
117
+ M8_RAW_MANIFEST_SHA256=<64-character-sha256>
118
+ make report-m8 \
119
+ M8_RAW_MANIFEST=data/m8/_manifests/<manifest>.json \
120
+ M8_RAW_MANIFEST_SHA256=<64-character-sha256>
121
+ ```
122
+
123
+ The producer opens and validates only the train and validation members first.
124
+ It fits and calibrates the selected model and an independent historical prior
125
+ exactly once on development data, persists their canonical numeric preprocessing
126
+ and estimator states in each per-symbol lock, closes one aggregate lock, and
127
+ revalidates the exact protocol, config, Git/source identity, raw authority,
128
+ development manifest, fitted-state hashes, and child locks immediately before
129
+ every held-out member is opened. Held-out evaluation restores those states with
130
+ no fit, refit, recalibration, or update.
131
+ A declared-data failure becomes an immutable `INSUFFICIENT_DATA` bundle with no
132
+ replacement date or endpoint predictions. A successful bundle remains
133
+ trade-only: execution, P&L, capacity, significance, and cross-instrument pooling
134
+ are unauthorized by the protocol.
135
+
136
+ That failure branch is the observed outcome of the declared study. The canonical
137
+ bundle at `artifacts/runs/binance-m8-multidate` stopped on the ETHUSDT training
138
+ archive after complete normalization found 53 `temporal.long_silence` warnings.
139
+ BTCUSDT training normalization had already completed with 2,071,461 rows and no
140
+ findings; ETHUSDT contributed 987,297 rows, zero errors, and 53 warnings. The
141
+ producer did not start selection, create a development lock, open either held-out
142
+ date, publish a prediction, or run execution. This is a valid, checksummed
143
+ `INSUFFICIENT_DATA` result, not an incomplete attempt and not evidence against or
144
+ for the economic hypothesis.
145
+ `report-m8` revalidates the terminal and its external raw authority, then renders
146
+ the failure report into a separate report directory. It does not repair, append
147
+ to, or otherwise mutate the canonical failure bundle.
148
+
149
+ ## Frozen live-L2 sessions — replacement campaign v2
150
+
151
+ Each declared date is captured by one command that waits for the exact common
152
+ UTC barrier and starts both public market-data feeds under one authority. It
153
+ never authenticates or exposes an order-entry path:
154
+
155
+ ```bash
156
+ make capture-m8-l2-session M8_L2_SESSION_DATE=2026-08-10
157
+ ```
158
+
159
+ The superseded v1 campaign is retained as historical control evidence: Aug 8
160
+ was a verified `MISSED_WINDOW`, Aug 9 completed, and its development authority
161
+ is permanently `NOT_CREATED`. It is not rewritten or used by v2. Before any v2
162
+ session was observed, the user explicitly reset the empirical campaign to Aug
163
+ 10 train, Aug 11 validation, Aug 12 primary test, and Aug 13 replication test,
164
+ each at 14:00--15:00 UTC. A missed, disconnected, gapped, warning-bearing, or
165
+ otherwise insufficient v2 date is frozen as such and is never replaced. Only
166
+ checksum-verified `COMPLETE` bundles may expose economic frames.
167
+ A verified held-out `INSUFFICIENT_DATA` bundle may be consumed only as control
168
+ evidence for an aggregate insufficiency terminal; its economic frames are never
169
+ opened.
170
+
171
+ The analysis specification is separately frozen in
172
+ [`docs/M8_L2_ANALYSIS_CONTRACT.md`](docs/M8_L2_ANALYSIS_CONTRACT.md). Its strict
173
+ loader, session input verifier, observed-interval feature/label construction,
174
+ Aug 10/11 development-authority producer, no-refit Aug 12/13 evaluation, market-only
175
+ execution evaluator, descriptive diagnostics, and artifact-driven report
176
+ renderers are integrated behind tested CLI/Make producers and recursive
177
+ verifiers. The software path is complete; no v2 session data existed when the
178
+ 10--13 calendar and authority bytes were fixed, so v2 may reach either a valid
179
+ complete result or an honest insufficiency terminal. No L2 metric or execution
180
+ result is claimed before those terminals exist. During the campaign, live
181
+ status belongs only to the immutable campaign/session authorities; this tracked
182
+ README must not be revised between sessions.
183
+ Use the ignored run targets
184
+ `artifacts/runs/binance-m8-l2-development-lock` for the durable development
185
+ authority and `artifacts/runs/binance-m8-live-l2` for the final campaign bundle;
186
+ do not place mutable study state in a source-controlled path.
187
+
188
+ ### Frozen L2 operating sequence
189
+
190
+ Every later command requires explicit authorities; none scans for a "latest"
191
+ bundle. The Make targets default to the frozen
192
+ `M8_L2_CONFIG=configs/m8_l2_capture_study.toml` and
193
+ `M8_L2_ANALYSIS_CONFIG=configs/m8_l2_analysis.toml`; do not substitute either
194
+ during the campaign. After each capture, retain the emitted JSON. Its
195
+ `output_root`, `session_manifest_sha256`, and `checksums` fields identify the
196
+ bundle, manifest digest, and checksum file. Independently hash that exact
197
+ checksum file:
198
+
199
+ ```bash
200
+ shasum -a 256 /absolute/session/bundle/checksums.sha256
201
+ ```
202
+
203
+ Map those values without abbreviation to the role-specific Make variables:
204
+
205
+ - `M8_L2_<ROLE>_BUNDLE_DIR`
206
+ - `M8_L2_<ROLE>_MANIFEST_SHA256`
207
+ - `M8_L2_<ROLE>_CHECKSUMS_SHA256`
208
+
209
+ where `<ROLE>` is `TRAIN`, `VALIDATION`, `PRIMARY`, or `REPLICATION`. Make accepts
210
+ these as command-line assignments or exported environment variables. First
211
+ verify every session. After the Aug 11 validation terminal, create and verify the
212
+ development authority before any held-out analysis. If both development
213
+ sessions are `COMPLETE`, the authority is `LOCKED` and contains the eight fitted
214
+ child states. If either is a valid `INSUFFICIENT_DATA` terminal, the authority is
215
+ `NOT_CREATED`; it contains typed control evidence and deliberately opens no
216
+ economic frame. In either case it is immutable, and the Aug 12/13 captures must
217
+ still proceed on their declared dates:
218
+
219
+ ```bash
220
+ make verify-m8-l2-session M8_L2_BUNDLE_DIR=/absolute/session/bundle
221
+
222
+ make lock-m8-l2-development \
223
+ M8_L2_DEVELOPMENT_LOCK_DIR=artifacts/runs/binance-m8-l2-development-lock \
224
+ M8_L2_TRAIN_BUNDLE_DIR=... M8_L2_TRAIN_MANIFEST_SHA256=... \
225
+ M8_L2_TRAIN_CHECKSUMS_SHA256=... \
226
+ M8_L2_VALIDATION_BUNDLE_DIR=... M8_L2_VALIDATION_MANIFEST_SHA256=... \
227
+ M8_L2_VALIDATION_CHECKSUMS_SHA256=...
228
+
229
+ make verify-m8-l2-development-lock \
230
+ M8_L2_DEVELOPMENT_LOCK_DIR=artifacts/runs/binance-m8-l2-development-lock \
231
+ M8_L2_DEVELOPMENT_LOCK_SHA256=... \
232
+ M8_L2_TRAIN_BUNDLE_DIR=... M8_L2_TRAIN_MANIFEST_SHA256=... \
233
+ M8_L2_TRAIN_CHECKSUMS_SHA256=... \
234
+ M8_L2_VALIDATION_BUNDLE_DIR=... M8_L2_VALIDATION_MANIFEST_SHA256=... \
235
+ M8_L2_VALIDATION_CHECKSUMS_SHA256=...
236
+ ```
237
+
238
+ Use the `development_lock_sha256` printed by the command for either `LOCKED` or
239
+ `NOT_CREATED`. The direct CLI returns 1 for a valid `NOT_CREATED` command or
240
+ verification; the Make wrapper normalizes that research-terminal code to 0.
241
+ In both cases inspect the JSON status and preserve its `development_lock.json`,
242
+ exact `_NOT_CREATED` marker (`not-created\n`), and printed authority SHA instead
243
+ of retrying or changing dates. After Aug 13, pass
244
+ the same development coordinates plus both held-out authorities to the final
245
+ producer. A `NOT_CREATED` authority forces an aggregate `INSUFFICIENT_DATA`
246
+ result, opens no economic frames from any of the four sessions, and reports the
247
+ union of development and held-out control reasons. The command below explicitly
248
+ lists all four role triplets; none may be omitted or discovered by wildcard:
249
+
250
+ ```bash
251
+ make reproduce-m8-l2 \
252
+ M8_L2_DEVELOPMENT_LOCK_DIR=artifacts/runs/binance-m8-l2-development-lock \
253
+ M8_L2_DEVELOPMENT_LOCK_SHA256=... \
254
+ M8_L2_TRAIN_BUNDLE_DIR=... M8_L2_TRAIN_MANIFEST_SHA256=... \
255
+ M8_L2_TRAIN_CHECKSUMS_SHA256=... \
256
+ M8_L2_VALIDATION_BUNDLE_DIR=... M8_L2_VALIDATION_MANIFEST_SHA256=... \
257
+ M8_L2_VALIDATION_CHECKSUMS_SHA256=... \
258
+ M8_L2_PRIMARY_BUNDLE_DIR=... M8_L2_PRIMARY_MANIFEST_SHA256=... \
259
+ M8_L2_PRIMARY_CHECKSUMS_SHA256=... \
260
+ M8_L2_REPLICATION_BUNDLE_DIR=... M8_L2_REPLICATION_MANIFEST_SHA256=... \
261
+ M8_L2_REPLICATION_CHECKSUMS_SHA256=...
262
+ ```
263
+
264
+ The producer prints `run_manifest_sha256` and `checksums_sha256`. Reuse the full
265
+ four-session/development authority set and add those two values for
266
+ `verify-m8-l2-run` and `report-m8-l2`. If that full set has been exported under
267
+ the exact Make variable names above, the terminal commands are:
268
+
269
+ ```bash
270
+ make verify-m8-l2-run M8_L2_RUN_MANIFEST_SHA256=... \
271
+ M8_L2_RUN_CHECKSUMS_SHA256=...
272
+ make report-m8-l2 M8_L2_RUN_MANIFEST_SHA256=... \
273
+ M8_L2_RUN_CHECKSUMS_SHA256=...
274
+ ```
275
+
276
+ `report-m8-l2` recursively verifies the final run and all external authorities,
277
+ then writes to `artifacts/runs/binance-m8-live-l2-reports`. It never modifies the
278
+ immutable run bundle. At the direct CLI boundary, capture, development, final
279
+ producer, verifier, and report commands use exit 1 for a valid insufficiency
280
+ terminal; Make maps that one code to success because GNU Make otherwise collapses
281
+ it into a generic error. Automation must inspect the emitted JSON status and
282
+ exact marker rather than infer research status from Make's process code or retry
283
+ with changed dates or rules.
284
+
285
+ ## Commands
286
+
287
+ | Command | Purpose |
288
+ | --- | --- |
289
+ | `make setup` | Create/synchronize the locked Python 3.12 environment |
290
+ | `make download-sample` | Download the bounded credential-free public trade sample |
291
+ | `make download-m8` | Acquire the frozen M8 raw authority without opening archive members |
292
+ | `make capture-m8-l2-session M8_L2_SESSION_DATE=YYYY-MM-DD` | Capture the frozen concurrent BTCUSDT/ETHUSDT L2 session for one declared date |
293
+ | `make verify-m8-l2-session M8_L2_BUNDLE_DIR=<path>` | Verify a complete or `INSUFFICIENT_DATA` frozen L2 session bundle |
294
+ | `make lock-m8-l2-development` | Atomically publish the Aug 10/11 development authority: fitted `LOCKED` state when both sessions pass, or control-only `NOT_CREATED` evidence when either is insufficient |
295
+ | `make verify-m8-l2-development-lock` | Recursively verify either development-authority status against its path, SHA, configs, sessions, campaign, and clean source identity |
296
+ | `make reproduce-m8-l2` | Produce a new immutable four-session L2 terminal bundle; use the explicit-digest verifier for an existing target |
297
+ | `make verify-m8-l2-run` | Verify a complete or `INSUFFICIENT_DATA` L2 run plus all external authorities |
298
+ | `make report-m8-l2` | Re-render verified L2 reports into a separate directory without mutating the run |
299
+ | `make validate-data` | Run offline, non-mutating validation on the synthetic fixture |
300
+ | `make validate-public-data` | Validate configured public normalized partitions incrementally |
301
+ | `make smoke` | Produce or verify the immutable synthetic vertical slice |
302
+ | `make test` | Run all unit and integration tests without network access |
303
+ | `make reproduce-sample` | Alias for the canonical smoke producer |
304
+ | `make reproduce-public-sample` | Produce a trade-only run from an explicit manifest path + SHA |
305
+ | `make reproduce-m8` | Produce M8 from an explicit raw manifest + SHA under a clean commit |
306
+ | `make verify-run` | Verify run structure and every protected checksum |
307
+ | `make verify-public-run` | Verify the explicit public run bundle |
308
+ | `make verify-m8-run` | Verify a complete or `INSUFFICIENT_DATA` M8 terminal bundle |
309
+ | `make report` | Render a fresh report set from the frozen bundle |
310
+ | `make report-m8` | Render a complete M8 bundle or expose its frozen failure report |
311
+ | `make dashboard` | Open the local read-only Streamlit research dashboard |
312
+ | `make check` | Run Ruff, strict mypy, pytest, and the smoke producer |
313
+
314
+ The equivalent CLI is available as `microstructure` after setup. Run
315
+ `microstructure --help` for the `ingest`, `acquire-m8`, `validate`, `reproduce`,
316
+ `reproduce-m8`, `verify-m8`, `report-m8`, generic `verify`/`report`, the frozen
317
+ `capture-m8-l2-session`, `verify-m8-l2-session`, `lock-m8-l2-development`,
318
+ `verify-m8-l2-development-lock`, `reproduce-m8-l2`, `verify-m8-l2-run`, and
319
+ `report-m8-l2` commands, plus exploratory research-only `collect-l2`.
320
+
321
+ ## What is implemented
322
+
323
+ - Credential-free aggregate-trade ingestion with bounded retries, raw response
324
+ preservation, symbol metadata, exact scaling, immutable manifests, and
325
+ streaming partitioned Parquet writes. A verified public reader performs
326
+ physical-order incremental DQ and a single upstream Parquet pass into a
327
+ spill-capable DuckDB canonical sort; eager compatibility reads have a separate
328
+ hard row limit.
329
+ - Optional public live diff-depth capture plus REST snapshot anchoring and pure
330
+ `U/u` reconstruction with stale, overlap, gap, crossed-book, and invariant
331
+ checks. Reconnection starts a new continuity epoch. The frozen L2 runner uses
332
+ one absolute UTC barrier for both instruments, a byte-bounded receiver queue,
333
+ OBSERVED-only continuity intervals, cross-symbol overlap gates, exhaustive
334
+ artifact inventory, and atomic `COMPLETE`/`INSUFFICIENT_DATA` evidence.
335
+ - Typed quality findings for duplicates, ordering and clocks, invalid values,
336
+ scale mismatches, abnormal spread, silence, gaps, and crossed books. Validation
337
+ never repairs observations.
338
+ - Leakage-safe spread, L1/L5/L10 depth state, queue imbalance, microprice, OFI,
339
+ signed flow, intensity, volatility, observable zero-quantity cancellation,
340
+ causal lagged impact/recovery, regime, and stability features, with event-time
341
+ and clock-time labels and explicit censoring.
342
+ - A common-fold model ladder: historical prior, unpenalized logistic regression,
343
+ L2-regularized logistic grid, and shallow tree. Selection uses validation data;
344
+ the final test is frozen. Calibration and protocol-specific paired bootstrap
345
+ diagnostics are serialized with their block count, status, and seed: the
346
+ trade-only study uses fixed dependency blocks, while the prospective L2 study
347
+ uses interval-local overlapping moving blocks. Neither is presented as a
348
+ complete model of cross-instrument or overlapping-label dependence.
349
+ - OOS-only market/limit simulation with decision and order latency, maker/taker
350
+ fees, adverse price rounding, top-depth caps, partial fills, a declared queue
351
+ proxy, adverse selection, inventory limits, liquidation, turnover, and size
352
+ sensitivity.
353
+ - Atomic run production. `_SUCCESS` is written last; every other file is covered
354
+ by `checksums.sha256`. A completed target is read-only and reusable only when
355
+ the caller supplies its previously retained manifest and checksum digests to
356
+ the recursive verifier.
357
+ - Raw-only M8 acquisition with exact official CHECKSUM evidence, bounded ZIP
358
+ central-directory inspection, a hard retained-evidence byte ledger, an exact
359
+ content-addressed inventory, and an atomic self-contained bundle copy. The M8
360
+ producer enforces development-only normalization and final selected/prior
361
+ fitting before a durable analysis lock, restores transparent numeric states
362
+ for prediction, and fails closed at every held-out member-open boundary.
363
+ - Frozen L2 campaign identity and strict session readers that reject changed
364
+ clean-source identities, tampered or symlinked artifacts, invalid Parquet
365
+ footers/schemas, row mismatches, and continuity violations before exposing a
366
+ frame. One outcome-blind nonce binds all dates to the canonical output-root
367
+ path/filesystem identity, loaded source/import origin, and a hashed fingerprint
368
+ of Python, platform, and eight production dependency versions. Development-only
369
+ regime/model locks, no-refit held-out evaluation, paired dependency-block
370
+ diagnostics, market-only scenarios, descriptive analyses, and generated L2
371
+ reports feed one atomic final producer. Fail-closed memory admissions reserve
372
+ at most 8 GiB for development materialization and 12 GiB for final production
373
+ (raw, causal, evaluation, descriptive, and execution workspaces), leaving at
374
+ least 4 GiB of the 16 GiB host envelope for the interpreter and libraries;
375
+ every major allocation is checked before and immediately after materialization.
376
+ Its verifier streams tabular checks,
377
+ recursively revalidates the four external sessions and development authority,
378
+ binds a self-contained authority snapshot, rejects tampering, and enforces
379
+ `COMPLETE` versus `INSUFFICIENT_DATA` semantics.
380
+ - Generated technical report, two-page IC memo, held-out comparison table, and
381
+ six-tab Streamlit dashboard, all downstream of frozen serialized artifacts.
382
+
383
+ ## Run contents
384
+
385
+ Each completed run includes:
386
+
387
+ ```text
388
+ run_manifest.json # data interval, symbols, artifact map, assumptions
389
+ provenance.json # config/input hashes, seed, runtime, Git commit/state
390
+ resolved_config.json
391
+ data/normalized/ # partitioned Parquet + immutable manifests
392
+ quality/summary.json
393
+ research/ # full/evaluation frames and exact fold indices
394
+ models/ # all predictions and selected held-out predictions
395
+ metrics/ # predictive, execution, and sensitivity diagnostics
396
+ execution/ # orders, fills, positions, replay state
397
+ reports/ # code-generated report, memo, comparison table
398
+ dashboard/market_state.parquet
399
+ checksums.sha256
400
+ _SUCCESS
401
+ ```
402
+
403
+ The final L2 bundle uses the same immutable terminal convention but has its own
404
+ study inventory: self-contained `authority/` snapshots, per-date/symbol/endpoint
405
+ `causal_frames/`, locked `evaluation/`, seven descriptive analyses, partitioned
406
+ market-scenario orders/fills/positions plus assumptions and metrics, a
407
+ checksummed `report_inputs.json`, and three generated reports. An
408
+ `INSUFFICIENT_DATA` terminal retains the exact authorities, any allowable causal
409
+ evidence, report snapshot, and failure reports while omitting promoted
410
+ evaluation, descriptive, and execution artifacts. The recursive verifier checks
411
+ physical inventory, Parquet semantic claims, rendered-report equality, and all
412
+ external authorities. Exactly one final marker closes the bundle: `_SUCCESS`
413
+ contains `complete\n` for `COMPLETE`, while `INSUFFICIENT_DATA` contains
414
+ `terminal\n` for the typed data-availability terminal.
415
+
416
+ The semantic run key is derived from the configuration, immutable input identity,
417
+ Git commit, the exact tracked/non-ignored source-tree digest, and seed—not
418
+ generation timestamps. Reuse additionally requires the current source identity
419
+ and caller-retained output manifest/checksum digests to match; an older or
420
+ coordinatedly rewritten bundle cannot masquerade as evidence for changed code.
421
+
422
+ ## Main findings and current evidence
423
+
424
+ Replacement-campaign source-freeze snapshot as of 2026-08-09:
425
+
426
+ - The latest settled integration gates passed Ruff, formatting, strict mypy, and
427
+ the full pytest suite across the data, reconstruction, timing, modeling,
428
+ execution, reporting, dashboard, and pipeline boundaries. Exact test/module
429
+ counts belong to the dated verification ledger in `STATUS.md`, not to an
430
+ empirical claim.
431
+ - A fixed public sample for 2024-01-02 downloaded and normalized 10,000 real
432
+ aggregate trades: 5,000 each for BTCUSDT and ETHUSDT. The configured cap was
433
+ reached for both instruments, so both ranges are explicitly marked incomplete.
434
+ The current validators reported zero errors and zero warnings on those rows.
435
+ - The generated trade-only report serializes per-symbol paired held-out
436
+ model-minus-prior diagnostics without pooling instruments. Exact metrics live
437
+ only in the checksum-verified run bundle; they are not manually copied into
438
+ this file.
439
+ - The single-date, cap-truncated, validation-selected diagnostics do
440
+ not authorize a statistical-significance, persistent-alpha, profitability,
441
+ or capacity claim. The public bundle records execution and P&L as `NOT_RUN`;
442
+ synthetic model/P&L values are never interpreted economically.
443
+ - The prospective M8 acquisition, lock-before-open producer, failure bundle,
444
+ verifier, and report interfaces are implemented and tested offline. The eight
445
+ official archives and their CHECKSUM/metadata evidence are now present in the
446
+ verified raw-only authority
447
+ `data/m8/_manifests/m8-acquisition.manifest-04d5c01f3810b6a300ec.json`
448
+ (SHA-256 `04d5c01f3810b6a300ec0f9317052f254b2bec5d89bc0dfefd18cd71ad6582e6`).
449
+ The raw-acquisition phase opened no CSV member. The corrected clean-source
450
+ producer then published and verified the canonical
451
+ `artifacts/runs/binance-m8-multidate` terminal at commit
452
+ `88060613abe211cd8e80a3499678fca830f8ba2d`. It stopped at the declared ETHUSDT
453
+ training DQ gate with 53 warnings, before selection, locks, or held-out access;
454
+ execution is `NOT_RUN`. The bundle, rather than this summary, is the authority
455
+ for its exact status and evidence inventory.
456
+ - The live-L2 capture protocol and analysis contract are frozen, and strict
457
+ capture, session-verification, input, development-lock, locked-evaluation,
458
+ market-scenario, descriptive-analysis, and report components are covered by
459
+ offline tests. The superseded v1 evidence is preserved separately; no v2
460
+ Aug 10--13 L2 session existed at this source freeze, so these tracked bytes
461
+ contain no v2 book-based empirical result.
462
+
463
+ This distinction is the main research conclusion so far: a functioning simulator
464
+ is not evidence that a market effect exists.
465
+
466
+ ## Limitations and next milestone
467
+
468
+ Exchange timestamps are not colocated receipt times. Public trades cannot reveal
469
+ true queue priority, hidden liquidity, cancellations, or endogenous impact. The
470
+ limit-fill mechanism is therefore a scenario proxy, and reported sensitivity is
471
+ not deployable capacity. A short crypto interval cannot generalize across dates,
472
+ venues, or asset classes; overlapping horizons also reduce effective sample size
473
+ and make multiplicity control necessary.
474
+
475
+ The trade-only study is closed at its predeclared `INSUFFICIENT_DATA` gate and
476
+ must not be rerun with replacement dates or a relaxed warning policy. The next
477
+ empirical milestone is the already-frozen prospective, simultaneous
478
+ BTCUSDT/ETHUSDT local-L2 study. It requires four declared session terminals, a
479
+ single clean campaign source identity, continuous valid observed intervals, an
480
+ Aug 10/11 development authority durably published before either held-out session,
481
+ and unchanged Aug 12/13 evaluation when that authority is `LOCKED`. A
482
+ `NOT_CREATED` authority records why fitting was forbidden, while the declared
483
+ held-out captures still proceed and the final producer opens no economic frame.
484
+ A failed session remains evidence of insufficiency; no trade-only result can
485
+ substitute for book evidence.
486
+
487
+ See [the research protocol](docs/RESEARCH_PROTOCOL.md), [data contract](docs/DATA_CONTRACT.md),
488
+ [project plan](docs/PROJECT_PLAN.md), [decision log](docs/DECISION_LOG.md),
489
+ [L2 analysis contract](docs/M8_L2_ANALYSIS_CONTRACT.md), and
490
+ [methodology limitations](reports/methodology_limitations.md) for the exact
491
+ contracts and promotion rules.
492
+
493
+ ## Portfolio material
494
+
495
+ The source-controlled report files contain no manually pasted performance
496
+ numbers. Run-specific documents are generated from verified bundles. Supporting
497
+ communication artifacts are in `portfolio/`: an interview narrative, three
498
+ resume-bullet variants, and a ten-minute presentation outline.
499
+
500
+ ## Public release
501
+
502
+ - Project page: <https://yangxiaoshawn.github.io/projects/microstructure/>
503
+ - GitHub source: <https://github.com/YangXiaoShawn/open-economic-quant-microstructure>
504
+ - Versioned code and documentation mirror: <https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/Microstructure>
505
+ - Interactive evidence explorer: <https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory>
506
+ - Publication and data boundaries: [docs/PUBLICATION.md](docs/PUBLICATION.md) and [docs/DATA_POLICY.md](docs/DATA_POLICY.md)
507
+
508
+ Licensed under the MIT License. This repository is for research and simulation,
509
+ not investment advice or live trading.
Microstructure/STATUS.md ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Status
2
+
3
+ Last updated: 2026-08-09 UTC
4
+
5
+ > **Replacement-campaign source-freeze snapshot.** This tracked file records the
6
+ > state before the v2 four-date L2 campaign. It must not be edited between the
7
+ > first Aug 10 capture and the Aug 13 terminal. During that interval, current
8
+ > status is authoritative only in `data/m8_l2/campaign_authority.json` and the
9
+ > immutable per-session bundles; after the campaign, generated final-run
10
+ > provenance is the authority for results.
11
+
12
+ ## Current evidence
13
+
14
+ The portfolio-quality software vertical slice is complete. Its model and
15
+ execution output is labeled `SYNTHETIC_SMOKE` and supports only a software
16
+ reproducibility claim.
17
+
18
+ A credential-free `PUBLIC_SAMPLE_PARTIAL` ingestion and a frozen trade-only
19
+ research protocol were also completed for the
20
+ fixed 2024-01-02 UTC configuration: 5,000 aggregate trades each for BTCUSDT and
21
+ ETHUSDT. Both symbol ranges reached the configured cap and are explicitly
22
+ incomplete. The normalized 10,000 rows produced zero current validation errors
23
+ and warnings. This supports a bounded data-pipeline observation only—not a market
24
+ signal, statistical-significance, profitability, or capacity claim. The public
25
+ producer uses per-symbol purged folds and paired model-minus-prior uncertainty;
26
+ execution and P&L are explicitly `NOT_RUN` because no contemporaneous book is
27
+ present.
28
+
29
+ The frozen trade-only M8 study has reached its canonical terminal state. The
30
+ raw-only authority binds two exchange-metadata responses, eight official
31
+ ZIP/CHECKSUM pairs, and 36 retained artifacts totaling 117,897,562 bytes; every
32
+ acquisition entry records `csv_member_opened=false` and
33
+ `economic_fields_inspected=false`. The corrected clean-source producer at commit
34
+ `88060613abe211cd8e80a3499678fca830f8ba2d` published the checksummed
35
+ `artifacts/runs/binance-m8-multidate` bundle with status
36
+ `INSUFFICIENT_DATA`. BTCUSDT training normalization completed with 2,071,461
37
+ rows, zero errors, and zero warnings. ETHUSDT training normalization completed
38
+ with 987,297 rows, zero errors, and 53 warnings, triggering the predeclared
39
+ quality gate. Selection never started; no development lock or prediction was
40
+ published; no validation or held-out archive member was opened; execution and
41
+ P&L are `NOT_RUN`. No date or policy was replaced. Its report command revalidates
42
+ the terminal/raw authority and writes a fresh external report without modifying
43
+ the canonical bundle.
44
+
45
+ The live-L2 campaign remains the active evidence milestone. The superseded v1
46
+ campaign is preserved, not repaired: Aug 8 is `MISSED_WINDOW`, Aug 9 is a
47
+ verified complete session, and its development authority is `NOT_CREATED`.
48
+ Before observing any v2 session, the user reset the active prospective calendar
49
+ to Aug 10 train, Aug 11 validation, Aug 12 primary test, and Aug 13 replication
50
+ test. V1 evidence is not an input to v2. The v2 capture config, protocol, and
51
+ analysis authority are separately hash-bound. The campaign-authority mechanism
52
+ requires all four dates to share one outcome-blind nonce, canonical output-root
53
+ filesystem identity, clean commit/source/import origin, and hashed
54
+ Python/platform/production-dependency fingerprint. Strict capture and session
55
+ verification, verified lazy inputs, observed-interval endpoint frames,
56
+ Aug 10/11 `LOCKED | NOT_CREATED` development authority, no-refit Aug 12/13 evaluation, dependency-aware
57
+ diagnostics, market-only scenarios, descriptive analyses, and artifact-driven
58
+ L2 reporting are integrated in a tested end-to-end producer and CLI/Make path.
59
+ Development and final production have explicit 8 GiB and 12 GiB fail-closed
60
+ live-memory envelopes respectively; crossing any admission or post-allocation
61
+ bound is a system failure and cannot publish a research terminal.
62
+ The atomic final bundle is either `COMPLETE` or `INSUFFICIENT_DATA`; it embeds
63
+ exact config/protocol, campaign, session-control, and development authority
64
+ snapshots, while its verifier also revalidates every external authority. Reports
65
+ are regenerated only into an external directory, leaving the immutable run
66
+ untouched. The software path was complete at this remaining-campaign source
67
+ freeze; the real v2 session-control evidence was not. No v2 session bundle or
68
+ L2 empirical metric existed when these tracked bytes were frozen.
69
+
70
+ ## Milestones
71
+
72
+ | Milestone | Status | Evidence |
73
+ | --- | --- | --- |
74
+ | M0 Repository contract | Complete | Required files, Python packaging, locked environment, typed configuration and provenance |
75
+ | M1 Event data foundation | Complete | Public/synthetic adapters, exact schemas, partitioned Parquet, immutable raw/normalized manifests |
76
+ | M2 Book and quality controls | Complete | Gap-safe snapshot/delta replay and non-mutating quality rules covered by tests |
77
+ | M3 Leakage-safe dataset | Complete | Causal features, future labels, censoring, continuity isolation, lineage audit |
78
+ | M4 Model evaluation | Complete | Purged walk-forward prior/unpenalized/L2/tree ladder with calibration and block bootstrap |
79
+ | M5 Execution research | Complete | OOS-only costs, two-stage latency, market/limit partial fills, queue proxy, inventory, liquidation and sensitivity |
80
+ | M6 Reproducible vertical slice | Complete | Atomic CLI producer, immutable checksum bundle, deterministic run key, idempotent verification |
81
+ | M7 Research communication | Complete | Code-generated report/memo/table, read-only six-tab dashboard, limitations and portfolio material |
82
+ | M8 Broader empirical study | In progress | Trade-only branch closed with a canonical `INSUFFICIENT_DATA` terminal; complete frozen L2 software path verified offline; four prospective local-L2 session terminals and the resulting empirical terminal remain required |
83
+
84
+ ## Verification ledger
85
+
86
+ - 2026-08-08: the final L2 session, input, development-lock, total-producer,
87
+ recursive-verifier, CLI/Make, and external-report paths passed their focused
88
+ offline suites. A consolidated repository gate is run separately before source
89
+ freeze; its volatile test count is not hardcoded in this market-evidence file.
90
+ - 2026-08-08: every path listed by the canonical trade M8
91
+ `checksums.sha256` reverified. Its manifest/failure/provenance agree on
92
+ `INSUFFICIENT_DATA`, the clean source identity above, zero selection, zero
93
+ held-out access, and `NOT_RUN` execution.
94
+ - 2026-08-07: `make lint` passed across source, tests, and dashboard.
95
+ - 2026-08-08: the pre-L2 baseline `make check` passed Ruff, strict mypy across 40 package
96
+ modules, all 574 offline tests on Python 3.12.13, and a fresh current-source
97
+ synthetic bundle. `ruff format --check` also passed across all 92 Python files.
98
+ - 2026-08-07: `make check` passed Ruff, strict mypy, all tests, and a fresh
99
+ current-source synthetic bundle produced in an isolated temporary target.
100
+ - 2026-08-07: adversarial M8 tests proved that raw acquisition opens no CSV
101
+ member, unsafe ZIP metadata is rejected before the standard ZIP parser, both
102
+ symbol locks precede the first held-out open, tampered/missing authorities
103
+ expose zero held-out rows, and deterministic data failures publish no endpoint.
104
+ - 2026-08-08: raw-only M8 acquisition published and independently reverified
105
+ `data/m8/_manifests/m8-acquisition.manifest-04d5c01f3810b6a300ec.json`
106
+ (SHA-256 `04d5c01f3810b6a300ec0f9317052f254b2bec5d89bc0dfefd18cd71ad6582e6`).
107
+ Verification opened no CSV member and found no extra, missing, symlinked, or
108
+ unmanifested raw artifact.
109
+ - 2026-08-08: the frozen dual-symbol L2 session core and Binance adapter passed
110
+ 82 joint tests. A real adapter-produced mock bundle exposed 19 artifacts that
111
+ passed strict raw-journal, snapshot, Parquet footer/schema, quality, manifest,
112
+ absolute-time, overlap, and 29-gate reconciliation.
113
+ - 2026-08-07: pipeline tests independently reproduced two semantically identical
114
+ run bundles, verified their checksums, rejected corruption, and preserved an
115
+ incomplete target without repair.
116
+ - 2026-08-07: `make download-sample` succeeded after network permission was
117
+ granted; raw public responses and metadata were manifested and kept outside
118
+ Git. `validate-public-data` passed 10,000 normalized rows with zero findings.
119
+ - 2026-08-07: clean-commit canonical synthetic and public bundles were produced,
120
+ checksum-verified, and independently re-rendered into technical report, IC
121
+ memo, and model table. Generated artifacts remain ignored rather than
122
+ committed.
123
+
124
+ ## Empirical claim register
125
+
126
+ - Supported: the fixed, capped public REST sample can be acquired, normalized
127
+ with exchange-provided scales, content-hashed, partitioned, and validated.
128
+ - Exploratory diagnostic: the public producer persists each symbol's selected
129
+ model, paired held-out model-minus-prior loss, fixed-block interval and status
130
+ in a checksum-protected artifact. Exact metrics are read by generated reports
131
+ and are not manually duplicated in this status file; instruments are not
132
+ pooled.
133
+ - Not supported: confirmatory order-flow predictability, statistical
134
+ significance, effect half-life, cross-date/instrument stability, economic
135
+ profitability, live fill probability, or deployable capacity. Execution is
136
+ `NOT_RUN` for the public trade-only input.
137
+ - Inconclusive by design: the full-archive trade M8 hypothesis was not evaluated
138
+ because ETHUSDT training data failed the frozen warning gate. The terminal is
139
+ evidence of data insufficiency, not evidence that the hypothesis failed.
140
+ - Failed/unsupported hypothesis disclosure is generated per symbol for runs
141
+ that reach evaluation. The single capped date cannot test persistence or
142
+ book/liquidity hypotheses, and synthetic output cannot evaluate a market
143
+ hypothesis.
144
+
145
+ ## Next evidence sequence
146
+
147
+ Retain the canonical trade-only `INSUFFICIENT_DATA` bundle and its source-tagged
148
+ predecessor unchanged; do not relax the warning gate, replace a date, or rerun
149
+ until a favorable outcome appears. Use the completed L2 producer and explicit
150
+ authority interfaces with ignored targets
151
+ `artifacts/runs/binance-m8-l2-development-lock` and
152
+ `artifacts/runs/binance-m8-live-l2` for the development authority and final run,
153
+ respectively. Then capture the exact simultaneous Aug 10--13 BTCUSDT/ETHUSDT
154
+ sessions under one new clean v2 campaign authority. After Aug 11, durably publish
155
+ either the fitted `LOCKED` authority or the control-only `NOT_CREATED` authority
156
+ before Aug 12. A valid `NOT_CREATED` result exits 1 but does not cancel the Aug
157
+ 12/13 captures; the final producer uses all four control authorities without
158
+ opening economic frames. After Aug 13, produce and recursively verify the immutable
159
+ final bundle, render reports externally, measure peak RSS, and complete the
160
+ clean-room/resource audit. A failed/missed date terminalizes the declared
161
+ campaign rather than selecting a substitute. The
162
+ frozen facts are in `docs/M8_L2_ANALYSIS_CONTRACT.md`; generated bundles remain
163
+ the only authority for any eventual metrics.
Microstructure/configs/exploratory_aggtrades_2026-08-05_08.toml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [study]
2
+ name = "binance-aggtrades-2026-08-05-08-exploratory"
3
+ protocol_version = "1.0.0"
4
+ evidence_tier = "PUBLIC_ARCHIVE_EXPLORATORY"
5
+ seed = 20260809
6
+ source = "binance_spot_daily_aggtrades_archive"
7
+ symbols = ["BTCUSDT", "ETHUSDT"]
8
+ selection_metric = "log_loss"
9
+ target = "future_trade_up"
10
+ label_horizon_events = 20
11
+ calibration_fraction = 0.20
12
+ bootstrap_samples = 2000
13
+ bootstrap_block_events = 40
14
+ feature_stability_bins = 10
15
+ max_archive_compressed_bytes = 268435456
16
+ max_archive_uncompressed_bytes = 2147483648
17
+ max_total_download_bytes = 8589934592
18
+
19
+ [[periods]]
20
+ date = "2026-08-05"
21
+ role = "train"
22
+
23
+ [[periods]]
24
+ date = "2026-08-06"
25
+ role = "validation"
26
+
27
+ [[periods]]
28
+ date = "2026-08-07"
29
+ role = "primary_test"
30
+
31
+ [[periods]]
32
+ date = "2026-08-08"
33
+ role = "replication_test"
34
+
35
+ [features]
36
+ trade_windows = [5, 20, 100]
37
+ volatility_window = 100
38
+ intensity_window = 50
39
+ large_trade_quantile = 0.95
40
+
41
+ [models]
42
+ logistic_c_values = [0.1, 1.0, 10.0]
43
+ tree_max_depth_values = [2, 4, 6]
44
+ tree_min_samples_leaf = 40
45
+
46
+ [quality]
47
+ fail_on_error = true
48
+ require_complete_daily_archive = true
49
+ require_contiguous_trade_ids_within_symbol_date = true
50
+ require_nondecreasing_event_time = true
51
+ allow_quality_warnings = true
52
+
53
+ [claims]
54
+ allow_p_values = false
55
+ allow_significance_claim = false
56
+ allow_cross_instrument_pooling = false
57
+ allow_execution_claim = false
58
+ allow_profitability_claim = false
Microstructure/configs/m8_l2_analysis.toml ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [study]
2
+ name = "binance-m8-live-l2-analysis-v2"
3
+ protocol_version = "2.0.0"
4
+ seed = 20260807
5
+ source = "verified_m8_l2_session_bundles"
6
+ capture_config_source_sha256 = "b1bf3b4e2820e24e4555bfeb9cb0957f9a0bcdef62039f7d92360e0a97d0dd39"
7
+ capture_protocol_sha256 = "4c77a2099a4cabd049d10e0f8264d3b4c66704d8e87cbaf0c817fd085f4bbd83"
8
+ symbols = ["BTCUSDT", "ETHUSDT"]
9
+ training_role = "train"
10
+ selection_role = "validation"
11
+ primary_endpoint_role = "primary_test"
12
+ replication_endpoint_role = "replication_test"
13
+
14
+ [features]
15
+ decision_scope = "per_symbol_verified_observed_intervals"
16
+ flat_direction_policy = "flat_is_non_up"
17
+ rolling_windows = [20, 100]
18
+ volatility_window = 100
19
+ model_feature_columns = ["spread_bps", "depth_total_l1", "depth_total_l5", "depth_total_l10", "queue_imbalance_l1", "queue_imbalance_l5", "queue_imbalance_l10", "microprice_deviation_bps", "ofi_l1", "ofi_w20", "ofi_w100", "cancellation_intensity_w20", "cancellation_intensity_w100", "realized_volatility_w20", "realized_volatility_w100", "volatility_regime_low", "volatility_regime_high", "liquidity_regime_liquid", "liquidity_regime_stressed"]
20
+ clock_max_state_age_ms = 500
21
+ clock_target_policy = "exact_target_locf_same_valid_observed_interval"
22
+ clock_label_information_end = "exact_target"
23
+ clock_record_target_sequence = true
24
+ clock_censor_if_no_eligible_state = true
25
+
26
+ [[endpoints]]
27
+ name = "event_20"
28
+ domain = "event"
29
+ horizon_value = 20
30
+ unit = "events"
31
+ paired_block_width = 40
32
+ paired_block_unit = "events"
33
+ nominal_event_block_width = 40
34
+
35
+ [[endpoints]]
36
+ name = "event_100"
37
+ domain = "event"
38
+ horizon_value = 100
39
+ unit = "events"
40
+ paired_block_width = 200
41
+ paired_block_unit = "events"
42
+ nominal_event_block_width = 200
43
+
44
+ [[endpoints]]
45
+ name = "clock_1000ms"
46
+ domain = "clock"
47
+ horizon_value = 1000
48
+ unit = "milliseconds"
49
+ paired_block_width = 2000
50
+ paired_block_unit = "milliseconds"
51
+ nominal_event_block_width = 20
52
+
53
+ [[endpoints]]
54
+ name = "clock_5000ms"
55
+ domain = "clock"
56
+ horizon_value = 5000
57
+ unit = "milliseconds"
58
+ paired_block_width = 10000
59
+ paired_block_unit = "milliseconds"
60
+ nominal_event_block_width = 100
61
+
62
+ [regimes]
63
+ fit_role = "train"
64
+ feature = "realized_volatility_w100"
65
+ quantile_numerators = [1, 2]
66
+ quantile_denominator = 3
67
+
68
+ [calibration]
69
+ bins = 10
70
+
71
+ [bootstrap]
72
+ method = "paired_moving_block"
73
+ samples = 2000
74
+
75
+ [signed_impact]
76
+ metric = "ofi_signed_future_mid_markout"
77
+ side_rule = "sign_of_horizon_matched_ofi"
78
+ price_rule = "ofi_sign_times_future_log_mid_return_bps"
79
+
80
+ [execution]
81
+ market_orders_only = true
82
+ probability_threshold = 0.55
83
+ symmetric_probability_thresholds = true
84
+ order_notional_usd = 100.0
85
+ max_l1_participation = 0.10
86
+ inventory_order_multiples = 10
87
+ reference_price_fit_role = "train"
88
+ reference_depth_fit_role = "train"
89
+ reference_price_statistic = "train_median_mid_price"
90
+ reference_depth_statistic = "train_q05_min_bid_ask_l1_depth"
91
+ reference_quantity_policy = "min_100usd_and_10pct_train_q05_l1_depth_rounded_down_to_lot"
92
+ l1_fill_policy = "fill_up_to_recorded_l1_depth_cancel_remainder"
93
+ scenario_reset_policy = "per_symbol_session_endpoint_latency_pair"
94
+ extra_slippage_bps = 0.0
95
+ liquidate_at_end = true
96
+
97
+ [claims]
98
+ allow_capacity_claim = false
99
+ allow_realized_execution_claim = false
100
+ allow_profitability_claim = false
Microstructure/configs/m8_l2_capture_study.toml ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [study]
2
+ name = "binance-m8-live-l2-study-v2"
3
+ protocol_version = "2.0.0"
4
+ evidence_tier = "FULL_DATA"
5
+ seed = 20260807
6
+ source = "binance_spot_live_diff_depth_100ms"
7
+ symbols = ["BTCUSDT", "ETHUSDT"]
8
+ stream_interval_ms = 100
9
+
10
+ [[sessions]]
11
+ date = "2026-08-10"
12
+ start_utc = "14:00:00"
13
+ end_utc = "15:00:00"
14
+ role = "train"
15
+
16
+ [[sessions]]
17
+ date = "2026-08-11"
18
+ start_utc = "14:00:00"
19
+ end_utc = "15:00:00"
20
+ role = "validation"
21
+
22
+ [[sessions]]
23
+ date = "2026-08-12"
24
+ start_utc = "14:00:00"
25
+ end_utc = "15:00:00"
26
+ role = "primary_test"
27
+
28
+ [[sessions]]
29
+ date = "2026-08-13"
30
+ start_utc = "14:00:00"
31
+ end_utc = "15:00:00"
32
+ role = "replication_test"
33
+
34
+ [capture]
35
+ duration_seconds = 3600
36
+ max_messages_per_symbol = 60000
37
+ max_raw_frame_bytes = 1048576
38
+ max_arrow_batch_bytes = 16777216
39
+ min_overlapping_coverage_seconds = 3300
40
+ min_single_continuity_epoch_seconds = 1800
41
+ require_complete_status = true
42
+ require_live_reconstruction = true
43
+ max_sequence_gaps = 0
44
+ max_quality_errors = 0
45
+ max_quality_warnings = 0
46
+
47
+ [features]
48
+ depth_levels = [1, 5, 10]
49
+ event_horizons = [20, 100]
50
+ clock_horizons_ms = [1000, 5000]
51
+ include_spread = true
52
+ include_depth = true
53
+ include_ofi = true
54
+ include_queue_imbalance = true
55
+ include_microprice = true
56
+ include_cancellation_intensity = true
57
+ include_realized_volatility = true
58
+ include_reference_fit_regimes = true
59
+
60
+ [models]
61
+ selection_metric = "log_loss"
62
+ logistic_c_values = [0.1, 1.0, 10.0]
63
+ tree_max_depth_values = [2, 4, 6]
64
+ tree_min_samples_leaf = 40
65
+ calibration_fraction = 0.20
66
+ bootstrap_samples = 2000
67
+
68
+ [execution]
69
+ market_orders_only = true
70
+ taker_fee_bps = 4.0
71
+ decision_latency_events = [0, 1, 5]
72
+ order_latency_events = [0, 1, 5]
73
+ liquidate_at_end = true
74
+ allow_limit_fill_claim = false
75
+ allow_capacity_claim = false
76
+
77
+ [claims]
78
+ allow_p_values = false
79
+ allow_significance_claim = false
80
+ allow_realized_execution_claim = false
81
+ allow_profitability_claim = false
Microstructure/configs/m8_multidate_trade_study.toml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [study]
2
+ name = "binance-m8-multidate-trades"
3
+ protocol_version = "1.0.2"
4
+ evidence_tier = "FULL_DATA"
5
+ seed = 20260807
6
+ source = "binance_spot_daily_aggtrades_archive"
7
+ symbols = ["BTCUSDT", "ETHUSDT"]
8
+ selection_metric = "log_loss"
9
+ target = "future_trade_up"
10
+ label_horizon_events = 20
11
+ calibration_fraction = 0.20
12
+ bootstrap_samples = 2000
13
+ bootstrap_block_events = 40
14
+ feature_stability_bins = 10
15
+ max_archive_compressed_bytes = 268435456
16
+ max_archive_uncompressed_bytes = 2147483648
17
+ max_total_download_bytes = 8589934592
18
+
19
+ [[periods]]
20
+ date = "2024-01-03"
21
+ role = "train"
22
+
23
+ [[periods]]
24
+ date = "2024-01-04"
25
+ role = "validation"
26
+
27
+ [[periods]]
28
+ date = "2024-01-05"
29
+ role = "primary_test"
30
+
31
+ [[periods]]
32
+ date = "2024-01-06"
33
+ role = "replication_test"
34
+
35
+ [features]
36
+ trade_windows = [5, 20, 100]
37
+ volatility_window = 100
38
+ intensity_window = 50
39
+ large_trade_quantile = 0.95
40
+
41
+ [models]
42
+ logistic_c_values = [0.1, 1.0, 10.0]
43
+ tree_max_depth_values = [2, 4, 6]
44
+ tree_min_samples_leaf = 40
45
+
46
+ [quality]
47
+ fail_on_error = true
48
+ require_complete_daily_archive = true
49
+ require_contiguous_trade_ids_within_symbol_date = true
50
+ require_nondecreasing_event_time = true
51
+ allow_quality_warnings = false
52
+
53
+ [claims]
54
+ allow_p_values = false
55
+ allow_significance_claim = false
56
+ allow_cross_instrument_pooling = false
57
+ allow_execution_claim = false
58
+ allow_profitability_claim = false
Microstructure/configs/public_sample.toml ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [run]
2
+ name = "binance-public-sample"
3
+ evidence_tier = "PUBLIC_SAMPLE_PARTIAL"
4
+ seed = 20260807
5
+
6
+ [data]
7
+ mode = "binance_rest"
8
+ source = "binance_spot_rest"
9
+ symbols = ["BTCUSDT", "ETHUSDT"]
10
+ start = "2024-01-02T00:00:00Z"
11
+ end = "2024-01-02T00:10:00Z"
12
+ max_events_per_symbol = 5000
13
+ raw_root = "data/raw"
14
+ partition_root = "data/normalized"
15
+ schema_version = "1.0.0"
16
+ base_url = "https://data-api.binance.vision"
17
+ request_limit = 1000
18
+ timeout_seconds = 30.0
19
+ max_retries = 5
20
+
21
+ [quality]
22
+ max_spread_bps = 100.0
23
+ max_silence_ms = 5000
24
+ fail_on_error = true
25
+
26
+ [features]
27
+ trade_windows = [5, 20, 100]
28
+ volatility_window = 100
29
+ intensity_window = 50
30
+ label_horizon_events = 20
31
+ large_trade_quantile = 0.95
32
+
33
+ [evaluation]
34
+ min_train_events = 1200
35
+ validation_events = 400
36
+ test_events = 400
37
+ step_events = 400
38
+ embargo_events = 20
39
+ bootstrap_samples = 500
40
+ calibration_bins = 10
41
+
42
+ [models]
43
+ selection_metric = "log_loss"
44
+ logistic_c_values = [0.1, 1.0, 10.0]
45
+ tree_max_depth_values = [2, 4, 6]
46
+ tree_min_samples_leaf = 40
47
+
48
+ [execution]
49
+ decision_latency_events = 1
50
+ order_latency_events = 1
51
+ maker_fee_bps = 1.0
52
+ taker_fee_bps = 4.0
53
+ half_spread_bps = 1.0
54
+ slippage_bps_per_unit = 0.20
55
+ signal_threshold = 0.56
56
+ max_position_units = 3.0
57
+ order_size_units = 1.0
58
+ limit_fill_base_probability = 0.55
59
+ queue_ahead_units = 2.0
60
+ limit_max_age_events = 20
61
+ cancel_latency_events = 1
62
+ liquidate_at_end = true
63
+ capacity_multipliers = [0.5, 1.0, 2.0, 4.0]
Microstructure/configs/smoke.toml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [run]
2
+ name = "sample-smoke"
3
+ evidence_tier = "SYNTHETIC_SMOKE"
4
+ seed = 20260807
5
+
6
+ [data]
7
+ mode = "synthetic"
8
+ source = "synthetic_v1"
9
+ symbols = ["BTCUSDT", "ETHUSDT"]
10
+ start = "2024-01-02T00:00:00Z"
11
+ events_per_symbol = 3600
12
+ partition_root = "data/normalized"
13
+ schema_version = "1.0.0"
14
+
15
+ [quality]
16
+ max_spread_bps = 100.0
17
+ max_silence_ms = 5000
18
+ fail_on_error = true
19
+
20
+ [features]
21
+ trade_windows = [5, 20, 100]
22
+ volatility_window = 100
23
+ intensity_window = 50
24
+ label_horizon_events = 20
25
+ large_trade_quantile = 0.95
26
+
27
+ [evaluation]
28
+ min_train_events = 1200
29
+ validation_events = 400
30
+ test_events = 400
31
+ step_events = 400
32
+ embargo_events = 20
33
+ bootstrap_samples = 200
34
+ calibration_bins = 10
35
+
36
+ [models]
37
+ selection_metric = "log_loss"
38
+ logistic_c_values = [0.1, 1.0, 10.0]
39
+ tree_max_depth_values = [2, 4, 6]
40
+ tree_min_samples_leaf = 40
41
+
42
+ [execution]
43
+ decision_latency_events = 1
44
+ order_latency_events = 1
45
+ maker_fee_bps = 1.0
46
+ taker_fee_bps = 4.0
47
+ half_spread_bps = 1.0
48
+ slippage_bps_per_unit = 0.20
49
+ signal_threshold = 0.56
50
+ max_position_units = 3.0
51
+ order_size_units = 1.0
52
+ limit_fill_base_probability = 0.55
53
+ queue_ahead_units = 2.0
54
+ limit_max_age_events = 20
55
+ cancel_latency_events = 1
56
+ liquidate_at_end = true
57
+ capacity_multipliers = [0.5, 1.0, 2.0, 4.0]
Microstructure/dashboard/app.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only Streamlit dashboard for a completed microstructure run bundle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from collections.abc import Mapping, Sequence
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import streamlit as st
14
+
15
+ from microstructure.provenance import sha256_file
16
+ from microstructure.reporting import RunBundle, RunBundleError, load_run_bundle
17
+
18
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
19
+ DEFAULT_RUN_DIR = PROJECT_ROOT / "artifacts" / "runs" / "sample-smoke"
20
+
21
+
22
+ def _argument_run_dir(arguments: Sequence[str]) -> Path:
23
+ parser = argparse.ArgumentParser(add_help=False)
24
+ parser.add_argument("--run-dir")
25
+ parsed, _ = parser.parse_known_args(arguments)
26
+ configured = parsed.run_dir or os.environ.get("MICROSTRUCTURE_RUN_DIR")
27
+ return Path(configured).expanduser() if configured else DEFAULT_RUN_DIR
28
+
29
+
30
+ def _integrity_key(run_dir: Path) -> str:
31
+ checksum_path = run_dir / "checksums.sha256"
32
+ return sha256_file(checksum_path) if checksum_path.is_file() else "missing"
33
+
34
+
35
+ @st.cache_resource(show_spinner=False)
36
+ def _cached_bundle(run_dir: str, integrity_key: str) -> RunBundle:
37
+ del integrity_key # It is part of Streamlit's cache key.
38
+ return load_run_bundle(run_dir)
39
+
40
+
41
+ def _rows(rows: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
42
+ return [dict(row) for row in rows]
43
+
44
+
45
+ def _show_rows(rows: Sequence[Mapping[str, Any]], empty_message: str) -> None:
46
+ if rows:
47
+ st.dataframe(_rows(rows), hide_index=True)
48
+ else:
49
+ st.info(empty_message)
50
+
51
+
52
+ def _show_overview(bundle: RunBundle) -> None:
53
+ st.subheader("Evidence and lineage")
54
+ columns = st.columns(4)
55
+ columns[0].metric("Run", bundle.run_id)
56
+ columns[1].metric("Evidence", bundle.evidence_tier)
57
+ columns[2].metric("Symbols", len(bundle.symbols))
58
+ columns[3].metric(
59
+ "Git state",
60
+ "dirty" if bool(cast_mapping(bundle.provenance.get("git")).get("dirty")) else "clean",
61
+ )
62
+ st.markdown(
63
+ f"**Observed UTC period:** `{bundle.observed_start_utc}` → `{bundle.observed_end_utc}`"
64
+ )
65
+ st.markdown(f"**Instruments:** {', '.join(bundle.symbols)}")
66
+ st.caption(
67
+ "The dashboard reads serialized artifacts only. It does not download data, "
68
+ "train models, or simulate orders."
69
+ )
70
+
71
+
72
+ def cast_mapping(value: Any) -> Mapping[str, Any]:
73
+ return value if isinstance(value, Mapping) else {}
74
+
75
+
76
+ def _show_quality(bundle: RunBundle) -> None:
77
+ st.subheader("Non-mutating validation findings")
78
+ if bundle.quality:
79
+ st.json(dict(bundle.quality), expanded=True)
80
+ else:
81
+ st.info("No quality summary was serialized in this completed run bundle.")
82
+ st.caption("Findings are displayed as recorded; this app does not repair observations.")
83
+
84
+
85
+ def _show_market_state(bundle: RunBundle) -> None:
86
+ st.subheader("Market-state aggregates")
87
+ _show_rows(
88
+ bundle.market_state,
89
+ "No dashboard-safe market-state aggregate was serialized for this run.",
90
+ )
91
+ st.caption(
92
+ "Only bounded aggregates are loaded here; the dashboard never scans external raw data."
93
+ )
94
+
95
+
96
+ def _show_predictions(bundle: RunBundle) -> None:
97
+ st.subheader("Serialized predictive diagnostics")
98
+ _show_rows(
99
+ bundle.predictive_metrics,
100
+ "No predictive metric rows were serialized for this run.",
101
+ )
102
+ st.caption(
103
+ "Predictive metrics do not establish fillability or performance after execution costs."
104
+ )
105
+
106
+
107
+ def _show_execution(bundle: RunBundle) -> None:
108
+ st.subheader("Serialized simulated performance")
109
+ _show_rows(
110
+ bundle.execution_metrics,
111
+ "No execution or simulated-performance rows were serialized for this run.",
112
+ )
113
+ st.markdown("#### Execution sensitivity grid")
114
+ _show_rows(
115
+ bundle.execution_sensitivity,
116
+ "No execution-sensitivity rows were serialized for this run.",
117
+ )
118
+ assumptions = bundle.manifest.get("execution_assumptions")
119
+ if isinstance(assumptions, Mapping) and assumptions:
120
+ st.markdown("#### Recorded execution assumptions")
121
+ st.json(dict(assumptions), expanded=False)
122
+ st.caption(
123
+ "Fees, latency, fills, adverse selection, inventory, and liquidation are model "
124
+ "assumptions—not realized trading outcomes."
125
+ )
126
+
127
+
128
+ def _show_reproducibility(bundle: RunBundle) -> None:
129
+ st.subheader("Frozen provenance")
130
+ st.markdown(f"**Run directory:** `{bundle.root}`")
131
+ st.markdown(f"**Configuration SHA-256:** `{bundle.provenance.get('config_sha256', 'N/A')}`")
132
+ st.markdown("#### Run manifest")
133
+ st.code(json.dumps(bundle.manifest, indent=2, sort_keys=True), language="json")
134
+ st.markdown("#### Provenance")
135
+ st.code(json.dumps(bundle.provenance, indent=2, sort_keys=True), language="json")
136
+ st.caption(
137
+ "The completion marker and checksum manifest were verified before these values loaded."
138
+ )
139
+
140
+
141
+ def render_dashboard(bundle: RunBundle) -> None:
142
+ """Render a verified bundle without changing it."""
143
+ st.title("Order Flow to Price Impact")
144
+ if bundle.evidence_tier in {"SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL"}:
145
+ st.warning(bundle.watermark)
146
+ else:
147
+ st.info(bundle.watermark)
148
+
149
+ labels = (
150
+ "Overview",
151
+ "Data Quality",
152
+ "Market State",
153
+ "Predictions",
154
+ "Simulated Performance",
155
+ "Reproducibility & Limitations",
156
+ )
157
+ tabs = st.tabs(labels)
158
+ with tabs[0]:
159
+ _show_overview(bundle)
160
+ with tabs[1]:
161
+ _show_quality(bundle)
162
+ with tabs[2]:
163
+ _show_market_state(bundle)
164
+ with tabs[3]:
165
+ _show_predictions(bundle)
166
+ with tabs[4]:
167
+ _show_execution(bundle)
168
+ with tabs[5]:
169
+ _show_reproducibility(bundle)
170
+
171
+
172
+ def main(arguments: Sequence[str] | None = None) -> None:
173
+ st.set_page_config(page_title="Microstructure Research", layout="wide")
174
+ run_dir = _argument_run_dir(sys.argv[1:] if arguments is None else arguments).resolve()
175
+ try:
176
+ bundle = _cached_bundle(str(run_dir), _integrity_key(run_dir))
177
+ except RunBundleError as error:
178
+ st.title("Order Flow to Price Impact")
179
+ st.error(f"Run bundle is incomplete or invalid: {error}")
180
+ st.caption(
181
+ "Select a directory containing run_manifest.json, provenance.json, "
182
+ "checksums.sha256, and the final _SUCCESS marker."
183
+ )
184
+ st.stop()
185
+ render_dashboard(bundle)
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
Microstructure/data/_ingestion_manifests/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
Microstructure/data/derived/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
Microstructure/data/models/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
Microstructure/data/normalized/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
Microstructure/data/quality/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+
Microstructure/docs/DATA_CONTRACT.md ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data contract and lineage
2
+
3
+ ## Scope
4
+
5
+ The normalized layer separates exchange-specific acquisition from research
6
+ logic. An adapter may add a new venue, but it must produce the same versioned
7
+ event contracts, preserve original bytes, and declare how observation time is
8
+ approximated. No normalized table is evidence that an event was available to a
9
+ real colocated strategy unless local receipt time was actually captured.
10
+
11
+ Current schema version: `1.0.0`.
12
+
13
+ ## Clocks and ordering
14
+
15
+ All timestamps are signed UTC epoch nanoseconds:
16
+
17
+ - `event_ts_ns`: timestamp supplied by the market-data source;
18
+ - `received_ts_ns`: local wall-clock receipt when captured live, otherwise null;
19
+ - `available_ts_ns`: earliest time the pipeline permits the row to enter an
20
+ information set;
21
+ - `availability_basis`: explicit reason, such as `local_receive_time`,
22
+ `exchange_event_time_proxy`, or `synthetic_receipt`;
23
+ - `capture_seq`: local arrival ordering when a collector supplies it;
24
+ - `continuity_id`: a feed epoch that cannot be crossed by rolling features,
25
+ labels, open orders, or markouts.
26
+
27
+ Within a continuous book epoch, sequence IDs—not exchange timestamps—are the
28
+ authoritative reconstruction order. Research ordering is stable on availability
29
+ time, sequence/capture order, and event identity. Separate trade and book streams
30
+ with equal timestamps have no assumed common ordering, so cross-stream joins are
31
+ strictly prior unless a future source proves a shared sequence.
32
+
33
+ ## Exact numerical representation
34
+
35
+ Adapters retain integer `price_ticks`/`quantity_lots` and the corresponding
36
+ `tick_size`/`lot_size`. Floating `price` and `quantity` columns are convenience
37
+ units and must agree with the exact representation. Binance symbol scales come
38
+ from public `exchangeInfo` filters for each download; fixed `1e-8` scale defaults
39
+ exist only as explicit low-level fallbacks and are not the configured sample
40
+ path.
41
+
42
+ Derived ratios, log returns, volatility, probabilities, and P&L use `Float64`
43
+ with their units named or documented. Execution quantities are rounded down to
44
+ the observable lot size; slippage-adjusted prices round adversely to the tick.
45
+
46
+ ## Normalized tables
47
+
48
+ ### Trades
49
+
50
+ Identity is `(venue, symbol, trade_id)`. Required economic fields include exact
51
+ and floating price/quantity, quote quantity, first/last constituent trade IDs,
52
+ buyer-maker flag, normalized aggressor side, timestamps, and source artifact ID.
53
+ A `buy` aggressor lifts the ask; a `sell` aggressor hits the bid.
54
+
55
+ ### Depth deltas
56
+
57
+ Each event contains `first_update_id`, `last_update_id`, optional previous update
58
+ ID, and bid/ask lists of exact `(price_ticks, quantity_lots)` changes. Quantity
59
+ zero is a delete instruction; a negative quantity is invalid.
60
+
61
+ ### Book snapshots
62
+
63
+ A snapshot carries its request/receipt/availability times, last update ID,
64
+ depth limit, exact levels, scale metadata, source artifact ID, and a new
65
+ continuity ID. Binance REST snapshots do not provide an exchange event timestamp;
66
+ the local receipt time is the anchor availability time.
67
+
68
+ ### Book observations
69
+
70
+ Reconstruction emits best bid/ask, L1 quantities, cumulative depth at 1/5/10
71
+ levels, spread, mid, microprice, queue imbalance, sequence range, validity flag,
72
+ and full lineage. A crossed/locked or emptied book terminates the epoch rather
73
+ than being silently repaired.
74
+
75
+ ### Sequence gaps
76
+
77
+ A gap row records expected and observed ranges, the missing inclusive range,
78
+ detection time, continuity ID, source artifact, and reason. After a forward gap,
79
+ the book is not live again until a new snapshot starts a new epoch.
80
+
81
+ ## Binance acquisition semantics
82
+
83
+ The configured historical adapter uses only credential-free public market-data
84
+ REST endpoints. It starts aggregate-trade pagination with a fixed UTC interval,
85
+ then advances by aggregate trade ID so trades sharing a timestamp are not lost.
86
+ HTTP 408/418/429/5xx, connection failures, and recoverable interruptions while
87
+ streaming an HTTP 200 body use bounded exponential backoff; `Retry-After` is
88
+ honored for rate-limit responses. Response bodies have a byte ceiling. Every
89
+ accepted exact body is content-addressed and manifested before normalization;
90
+ an interrupted or oversized response preserves a bounded rejected prefix and an
91
+ explicit rejection sidecar before retry/failure.
92
+
93
+ The optional live collector uses the market-data-only WebSocket endpoint and
94
+ diff-depth `U/u` updates. A correct local book buffers updates, fetches a public
95
+ snapshot, discards stale events, requires the first usable event to cover
96
+ `lastUpdateId + 1`, and then validates continuity for every event. Reconnection
97
+ starts a new continuity epoch. These rules follow Binance's official
98
+ [Spot WebSocket stream guide](https://developers.binance.com/en/docs/catalog/core-trading-spot-trading/api/ws-streams/~).
99
+ Public REST behavior and rate-limit headers are described in the official
100
+ [Spot REST documentation](https://developers.binance.com/en/docs/products/spot/rest-api).
101
+
102
+ Live capture persists each WebSocket frame before UTF-8/JSON parsing in a typed
103
+ base64 journal containing exact bytes, local receipt time, capture sequence and
104
+ continuity epoch. Each reconnect snapshot's raw body and sidecar are journaled as
105
+ an anchor. A frame above 1 MiB fails only after its evidence is preserved;
106
+ normalized Arrow spools flush before an estimated 16 MiB batch ceiling. A
107
+ capture-ID-scoped normalized root produces one streaming Parquet descriptor per
108
+ nonempty table, and a capture-ID completion summary is atomically published
109
+ last. The fixed summary name is only a latest-pointer, never the sole completion
110
+ record. Historical REST output retains the date-partition layout described
111
+ below.
112
+
113
+ Every historical download requires a finite per-symbol event cap, but that cap
114
+ is not treated as a RAM budget. The default path lazily yields at most one REST
115
+ page per Arrow batch, updates exact disk-backed quality state, and feeds the
116
+ Parquet writer once. Eager compatibility materialization has a separate hard
117
+ row guard. A `ConfiguredDataAdapter` protocol/registry is the normalized
118
+ extension boundary for later venues or institutional sources; its mode must
119
+ match the resolved configuration before dispatch.
120
+
121
+ ### Daily-archive acquisition boundary
122
+
123
+ A daily-archive acquisition object authenticates raw transport evidence; it is
124
+ not a normalized-data object. Acquisition may hash exact bodies, authenticate
125
+ the official `CHECKSUM`, and inspect bounded ZIP
126
+ end-of-central-directory/central-directory metadata for member name, count, and
127
+ declared compressed/expanded sizes. It must not open or extract the CSV member,
128
+ read decompressed member bytes, parse a header or row, expose economic fields,
129
+ or compute row/ID/timestamp coverage. The first decompressed member byte is the
130
+ economic-data-open boundary, and the archive API must expose a fail-closed guard
131
+ immediately before that byte can be read.
132
+
133
+ For the prospective M8 study, all declared ZIP, `CHECKSUM`, and exchange-metadata
134
+ responses are acquired and placed in an immutable raw acquisition manifest
135
+ before any member is opened. Only train and validation members are then
136
+ stream-normalized and quality-checked. Their immutable development normalized
137
+ manifest is an input to selection. One per-symbol analysis lock and an aggregate
138
+ lock committing both child-lock hashes are closed and `fsync`ed, along with
139
+ their digest files and containing directories. Each child lock binds the
140
+ selected specification, development-frame identity, feature order, imputer and
141
+ scaler parameters, selected-estimator state, independent historical-prior state,
142
+ calibration state, fit cutoffs, and the canonical numeric fitted-state SHA-256.
143
+ Those states are fit on development data and durably closed before held-out
144
+ member access. The aggregate lock binds the
145
+ protocol/config, raw acquisition manifest, development normalized manifest, and
146
+ clean real Git revision. Every primary/replication member-open guard must
147
+ re-read and re-hash that exact durable lock before allowing decompression. Test
148
+ normalization may construct held-out features, but prediction restores the
149
+ locked numeric state; evaluation cannot reselect, fit, refit, recalibrate, or
150
+ update it.
151
+
152
+ Declared-object 404/410 responses, invalid exchange-metadata semantics, official
153
+ `CHECKSUM` or ZIP structural violations, frozen per-response size violations,
154
+ and retained-evidence budget exhaustion are typed deterministic insufficiency
155
+ and publish an immutable raw-only `INSUFFICIENT_DATA` authority. Retry exhaustion,
156
+ connection interruption, permission/local-I/O errors, collisions, and program
157
+ faults remain nonterminal system failures so they cannot masquerade as a market
158
+ or data result.
159
+
160
+ The M8 byte limits have distinct meanings. The compressed ceiling applies to
161
+ each archive response while streaming. The expanded ceiling applies to both the
162
+ declared and actually streamed bytes of each CSV member. The total-download
163
+ ceiling is the hard sum of immutable raw-response evidence retained for the
164
+ study: ZIP bodies, official `CHECKSUM` bodies, every response sidecar,
165
+ `exchangeInfo` bodies and sidecars, and all retained rejected-response prefixes
166
+ and rejection sidecars. Retried attempts still consume the total. A physically
167
+ retained content-addressed file is counted once even if referenced more than
168
+ once; separate retained copies are counted separately. Normalized Parquet,
169
+ quality outputs, and derived aggregate indexes are outside this raw-evidence
170
+ sum. Type-specific bounded `CHECKSUM`, metadata, and rejection responses remain
171
+ subject to the same total. Accounting is enforced while bytes are retained, not
172
+ after all downloads finish, and the raw acquisition manifest records every
173
+ accepted/rejected artifact and the final exact total.
174
+
175
+ If held-out normalization, continuity/completeness validation, or quality fails
176
+ after lock durability, the run publishes an atomic, checksum-protected,
177
+ immutable `INSUFFICIENT_DATA` terminal artifact under the same run identity. It
178
+ binds the raw and development manifests, per-symbol and aggregate locks, clean
179
+ Git identity, typed failure, partial-evidence hashes, and unopened remainder;
180
+ it contains no endpoint result. That identity may subsequently verify/reuse the
181
+ failure but may not overwrite it, return to selection, substitute inputs, or
182
+ publish a partial successful bundle. A source change creates a new clean Git
183
+ identity rather than rewriting prior evidence.
184
+
185
+ ## Storage and manifests
186
+
187
+ Normalized Parquet is content-addressed and partitioned beneath:
188
+
189
+ ```text
190
+ <root>/<dataset>/schema-<version>/venue-<venue>/symbol-<symbol>/date-YYYY-MM-DD/
191
+ ```
192
+
193
+ Writers reject oversized input batches before row conversion and consume
194
+ bounded Arrow record batches; they do not require all event rows in memory.
195
+ Each part has an immutable sidecar with source URI, download/creation
196
+ time, requested and observed ranges, row/byte counts, schema version,
197
+ transformations, input checksum, write ordinal, and Parquet checksum. A dataset
198
+ manifest lists all parts, sidecars, hashes, row counts, observed bounds and write
199
+ order. Validation checks those bytes before scanning rows. Run bundles snapshot
200
+ these manifest hashes and protect every included file with `checksums.sha256`.
201
+
202
+ Each config-driven ingestion also writes a content-named immutable ingestion
203
+ manifest linking only the exact raw responses used by that invocation to the
204
+ normalized dataset manifests. It records the row cap and each symbol's
205
+ `complete_range` state, so capped coverage cannot survive merely as terminal
206
+ output or be mistaken for the entire requested interval. Quality reports and
207
+ full findings JSONL are atomically published under per-run names and their
208
+ SHA-256/byte counts are bound into the same ingestion manifest.
209
+
210
+ The public research reader verifies metadata, URI/symbol semantics, exact raw
211
+ record membership, inverse raw-to-normalized coverage, scales, parts and
212
+ sidecars before exposing rows. Its batch API performs physical-order incremental
213
+ quality checks while a single upstream Arrow stream is staged through a
214
+ memory-limited, spill-capable DuckDB canonical sort. The legacy eager reader has
215
+ an independent finite materialization guard checked before any Parquet row read.
216
+
217
+ For M8 specifically, the raw acquisition manifest and normalized manifests are
218
+ different immutable stages and must not be collapsed into one post hoc record.
219
+ A self-contained run preserves the acquisition authority as an exact raw-only
220
+ copy below `data/input`; normalization, Parquet, and DQ evidence live separately
221
+ below `data/normalized_input`. The final all-date manifest is rooted at `data`
222
+ so it may bind both trees without making derived artifacts members of the raw
223
+ authority. A failed run inventories every pre-terminal regular file, binds any
224
+ completed and failed normalization evidence, and applies the same verifier both
225
+ before and after atomic publication.
226
+ A successful final bundle binds the raw acquisition manifest, final normalized
227
+ manifest for all eight declared symbol/dates, official `CHECKSUM` and metadata
228
+ bodies plus their sidecars, per-symbol and aggregate lock hashes, and the clean
229
+ real Git revision. Verification rejects a dirty, unborn, synthetic, or changed
230
+ source identity and rechecks all bound artifact bytes before reuse.
231
+
232
+ External raw and normalized data are ignored by Git. Small deterministic test
233
+ fixtures may be committed only under tests and must state whether they are
234
+ synthetic or sampled public observations.
235
+
236
+ ### Frozen dual-symbol live-L2 session authority
237
+
238
+ Each prospective L2 date uses one absolute UTC start/end barrier and one
239
+ cross-symbol authority for BTCUSDT and ETHUSDT. The two single-symbol producers
240
+ run concurrently and preserve raw frames before parsing. Coverage is computed
241
+ only from intervals backed by consecutive `OBSERVED` reconstructed book states;
242
+ raw socket first/last span, stale updates, excluded messages, gaps, and silent
243
+ holes do not create coverage. The session gate uses the exact union/intersection
244
+ of those intervals, requires one sufficiently long valid continuity epoch,
245
+ reconciles raw/normalized/reconstructed/excluded rows and snapshot anchors, and
246
+ enforces the frozen gap, error, warning, frame-byte, and Arrow-batch limits.
247
+
248
+ All per-symbol raw journals, snapshots, normalized data, manifests, quality
249
+ reports, and capture summaries must form an exhaustive regular-file inventory.
250
+ A passing dual-symbol session is published atomically with checksums and exact
251
+ `_SUCCESS` bytes; a typed capture/gate failure publishes an immutable
252
+ `INSUFFICIENT_DATA` authority. Permission, local-I/O, source/config/protocol
253
+ drift, or program faults retain nonterminal raw evidence but may not publish a
254
+ research terminal. Neither terminal authorizes live trading.
255
+
256
+ ## Quality policy
257
+
258
+ Validators never sort, deduplicate, clip, interpolate, or rewrite observations.
259
+ They emit typed findings for duplicate trades, timestamp/order reversals,
260
+ availability/receipt contradictions, sequence gaps or stale updates, crossed
261
+ books, invalid price/quantity, scale mismatches, abnormal spread, nonmonotone
262
+ depth, long silence, and receipt-clock reversal. A downstream research view may
263
+ exclude a row, but it must preserve the normalized source and report the
264
+ exclusion count/reason.
265
+
266
+ Incremental validators retain only a bounded in-memory finding preview; exact
267
+ duplicate/clock/sequence state spills to SQLite and complete findings stream to
268
+ JSONL. A failed validation closes and removes only its temporary sink, leaving
269
+ any previously published evidence untouched.
Microstructure/docs/DATA_POLICY.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data policy
2
+
3
+ ## Public repository boundary
4
+
5
+ The public repository and its Hugging Face mirror contain only Git-tracked
6
+ source code, configuration, tests, documentation, and small placeholder files.
7
+ They do not contain exchange observations or generated research bundles.
8
+
9
+ The following local paths are excluded from every public package:
10
+
11
+ - `data/raw/`, `data/normalized/`, `data/derived/`, `data/models/`, and
12
+ `data/quality/`;
13
+ - `data/m8/`, `data/m8_l2/`, and `data/_ingestion_manifests/`;
14
+ - `artifacts/runs/`;
15
+ - local environments, caches, bytecode, credentials, and dashboard secrets.
16
+
17
+ Empty `.gitkeep` placeholders may exist in the standalone GitHub repository but
18
+ are omitted from the Hugging Face publication mirror where practical.
19
+
20
+ ## Provider terms
21
+
22
+ The research adapters use credential-free public Binance market-data endpoints
23
+ and official archive metadata. Public availability is not treated as a grant to
24
+ redistribute provider data. Users who reproduce a public-data study obtain the
25
+ inputs independently and remain responsible for the provider's current terms,
26
+ rate limits, and permitted uses.
27
+
28
+ ## Research outputs
29
+
30
+ Source-controlled prose may summarize bounded aggregate validation counts and
31
+ protocol terminals. Raw events, normalized rows, derived features, fitted model
32
+ states, account-like records, and generated run bundles are not redistributed.
33
+ Synthetic fixtures and smoke outputs are labeled `SYNTHETIC_SMOKE` and support
34
+ software verification only.
35
+
36
+ The public website and Space may encode low-dimensional aggregate values already
37
+ stated in tracked README or status prose—for example row counts, warning counts,
38
+ and a declared terminal state—when they link back to that source and preserve its
39
+ evidence label. They do not publish additional model or execution metrics.
40
+
41
+ ## Trading boundary
42
+
43
+ The repository has no authenticated exchange client, account connection, or
44
+ order-entry path. Nothing in the public package is investment advice or evidence
45
+ of executable profit.
Microstructure/docs/DECISION_LOG.md ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Decision log
2
+
3
+ ## 2026-08-09 — Supersede the incomplete Aug 8–11 campaign with a new prospective v2 calendar
4
+
5
+ - **Observed boundary:** The v1 Aug 8 session is an immutable `MISSED_WINDOW`,
6
+ the Aug 9 validation session is immutable and complete, and the v1 development
7
+ authority is `NOT_CREATED`. Those facts and files remain preserved.
8
+ - **User decision:** Abandon v1 as the active empirical study and, before any of
9
+ the new dates is observed, freeze Aug 10 train, Aug 11 validation, Aug 12
10
+ primary test, and Aug 13 replication test at 14:00–15:00 UTC.
11
+ - **Integrity rule:** This is a new campaign/version and storage/source
12
+ authority, not a replacement bundle inside v1. V1 observations are not used
13
+ for v2 training, selection, evaluation, or reporting. Once Aug 10 begins, no
14
+ v2 date, threshold, feature, model, or interpretation rule may be changed.
15
+ - **Consequence:** A complete v2 train and validation may create the eight-state
16
+ `LOCKED` development authority before Aug 12; otherwise v2 terminates through
17
+ its existing `NOT_CREATED`/`INSUFFICIENT_DATA` branches without substitution.
18
+
19
+ ## 2026-08-08 — Preserve the missed first L2 window as control evidence only
20
+
21
+ - **Observed fact:** The declared Aug 8 14:00--15:00 UTC train window ended
22
+ before a clean committed producer authority was available. No capture command
23
+ ran, `data/m8_l2` remained absent, and no raw or economic field was opened.
24
+ - **Decision:** Never backfill, replace, or infer that session. Once the release
25
+ candidate has a clean source authority, invoke the already-tested late-start
26
+ path solely to publish `INSUFFICIENT_DATA / MISSED_WINDOW`; it must not call a
27
+ symbol capture adapter or network endpoint. Verify and retain that terminal,
28
+ then continue Aug 9--11 on their declared windows under the same campaign
29
+ authority.
30
+ - **Consequence:** The four-date study cannot promote a fitted development lock,
31
+ predictive metric, descriptive result, or execution scenario. Its honest final
32
+ outcome is necessarily aggregate `INSUFFICIENT_DATA`, backed by one missed
33
+ control terminal plus the remaining declared session authorities.
34
+
35
+ ## 2026-08-08 — Make development insufficiency a positive authority
36
+
37
+ - **Problem:** A valid `INSUFFICIENT_DATA` terminal on Aug 8 or Aug 9 forbids
38
+ fitting, but a missing development lock cannot authorize the final four-date
39
+ terminal and is indistinguishable from an interrupted workflow.
40
+ - **Decision:** The Aug 9 command always atomically publishes exactly one
41
+ development authority. `LOCKED` contains the eight fitted child states and
42
+ uses `_LOCKED` bytes `locked\n`. `NOT_CREATED` contains only typed,
43
+ recursively verified session-control reasons, uses `_NOT_CREATED` bytes
44
+ `not-created\n`, and must not load any economic frame. Both statuses expose the
45
+ same canonical authority path and SHA fields; a valid `NOT_CREATED` command
46
+ or verification exits 1 rather than masquerading as a system error.
47
+ - **Consequence:** Aug 10/11 are still captured on schedule. After Aug 11 the
48
+ one final producer verifies all four session controls and the development
49
+ authority. A `NOT_CREATED` branch publishes aggregate `INSUFFICIENT_DATA`,
50
+ reports the union of development and held-out reasons, and contains no
51
+ Parquet, model, prediction, descriptive, or execution artifact.
52
+
53
+ ## 2026-08-08 — Complete the explicit-authority L2 terminal producer
54
+
55
+ - **Decision:** Expose one operational path through
56
+ `lock-m8-l2-development`, `verify-m8-l2-development-lock`,
57
+ `reproduce-m8-l2`, `verify-m8-l2-run`, and `report-m8-l2`. Every stage takes
58
+ explicit bundle paths and independently supplied manifest/checksum SHA-256
59
+ authorities; development and final verification additionally require the
60
+ exact lock and run-control digests. No command discovers a "latest" input.
61
+ - **Terminal semantics:** After both held-out bundles' base authorities are
62
+ verified, any non-`COMPLETE` held-out session publishes aggregate
63
+ `INSUFFICIENT_DATA` without opening either held-out economic frame. If all
64
+ sessions are complete but an endpoint has no eligible held-out labels, the
65
+ same typed terminal is published without predictive, descriptive, or execution
66
+ promotion. Otherwise the producer restores the eight locked states without
67
+ refit, writes all declared evaluation/descriptive/market-scenario artifacts,
68
+ snapshots its external authorities, checksums the exact inventory, writes
69
+ `_SUCCESS` last, and immediately performs recursive verification. The exact
70
+ final marker bytes are `complete\n` for `_SUCCESS` and `terminal\n` for
71
+ `INSUFFICIENT_DATA`.
72
+ - **Reporting:** Both the canonical trade-M8 failure report and live-L2 reports
73
+ are rendered only after verification into a directory outside the immutable
74
+ run. The generated report-input snapshot is checksummed and re-rendered for
75
+ equality; report commands state that the source bundle was not modified.
76
+
77
+ ## 2026-08-08 — Bind one outcome-blind L2 campaign to its runtime and storage root
78
+
79
+ - **Decision:** The first predeclared capture creates one random 256-bit,
80
+ outcome-blind campaign nonce and binds all four sessions to one canonical
81
+ output-root path plus its filesystem device/inode identity. Moving to a
82
+ different root or replacing that directory is rejected before capture rather
83
+ than treated as a continuation of the campaign.
84
+ - **Runtime authority:** Bind the clean commit/source-tree identity, loaded
85
+ package/module origin, Python/platform identity, and the exact versions of the
86
+ eight production dependencies. Persist the canonical runtime payload and its
87
+ SHA-256 and revalidate it throughout orchestration and later input/final-run
88
+ verification.
89
+ - **Reason:** A commit hash alone does not prove that all dates used the same
90
+ interpreter, dependency environment, imported source tree, physical evidence
91
+ root, or prospectively chosen campaign instance.
92
+
93
+ ## 2026-08-08 — Accept the frozen trade-only M8 data-insufficiency terminal
94
+
95
+ - **Observed evidence:** The corrected clean-source run at commit
96
+ `88060613abe211cd8e80a3499678fca830f8ba2d` normalized 2,071,461 BTCUSDT
97
+ training rows with no findings, then normalized 987,297 ETHUSDT training rows
98
+ with zero errors and 53 `temporal.long_silence` warnings. That violated the
99
+ predeclared zero-warning gate.
100
+ - **Decision:** Treat `artifacts/runs/binance-m8-multidate` as the canonical
101
+ `INSUFFICIENT_DATA` terminal. Preserve its complete failed-normalization
102
+ evidence and the earlier noncanonical layout-defect terminal unchanged. Do not
103
+ replace the date, relax the warning rule, or reinterpret insufficiency as a
104
+ failed economic hypothesis.
105
+ - **Boundary proved by the terminal:** Selection did not start; no analysis lock,
106
+ fitted state, prediction, endpoint, held-out member, execution, P&L, capacity,
107
+ or significance result was produced. The trade-only study is closed; live-L2
108
+ evidence remains a separate prospective campaign.
109
+
110
+ ## 2026-08-08 — Freeze the complete live-L2 analysis contract before capture
111
+
112
+ - **Authority:** The exact analysis TOML has source SHA-256
113
+ `71edf7eeb9d5e935a18b0d8e354dc29b5b1132ace8eccd577730572d2caa8617`
114
+ and semantic SHA-256
115
+ `eeb9ac23ff275f26de57533a317d8165a89e99a14e86404a667cc69f6477bdac`.
116
+ It binds capture-config SHA-256
117
+ `491b14727a3e8bad907d1ad64072f6ebc14e407f98a5c31fca7b0a9e6801e758`
118
+ and capture-protocol SHA-256
119
+ `fe6d4aea5af3e9c529486b7e108afefeba623bf5ad3cc0743c0426a5e62e1fa7`.
120
+ Every declared TOML field is rendered without amendment in
121
+ `docs/M8_L2_ANALYSIS_CONTRACT.md` and enforced by a fail-closed loader.
122
+ - **Development boundary:** Fit volatility regimes on Aug 8 only; select each of
123
+ the two-symbol by four-endpoint candidates on Aug 9; persist final fitted model,
124
+ prior, preprocessing, calibration, regimes, and execution reference in eight
125
+ child locks plus one aggregate lock before either held-out session is exposed.
126
+ - **Held-out and claims boundary:** Aug 10/11 restore locked state without fit,
127
+ refit, recalibration, threshold change, or regime update. Evaluation uses the
128
+ four declared horizons and 2,000-draw paired moving blocks. Execution is a
129
+ market-order scenario only. Capacity, realized execution, and profitability
130
+ claims remain forbidden irrespective of the result.
131
+
132
+ ## 2026-08-08 — Keep raw authority separate from derived M8 failure evidence
133
+
134
+ - **Discovery:** The first clean-source development attempt stopped at its
135
+ frozen data-quality gate before selection, locks, or held-out access, but its
136
+ terminal bundle could not be reused: normalized and quality artifacts had
137
+ been written inside the directory that the raw-acquisition verifier correctly
138
+ requires to be an exact raw-only authority.
139
+ - **Decision:** Preserve the bundled raw authority unchanged below
140
+ `data/input`; write normalized and DQ artifacts below
141
+ `data/normalized_input`; root the final cross-stage manifest at `data`.
142
+ `INSUFFICIENT_DATA` inventories must exactly match the physical regular-file
143
+ tree and bind completed or failed normalization evidence. The producer runs
144
+ the external reuse verifier before and after atomic publication.
145
+ - **Evidence policy:** The original source-tagged attempt is retained rather
146
+ than repaired or overwritten. It is not canonical research evidence, and its
147
+ failure opened no declared held-out member. A fresh terminal requires a new
148
+ clean committed source identity; the frozen dates and quality policy do not
149
+ change.
150
+
151
+ ## 2026-08-08 — Lock transparent final fitted state before held-out access
152
+
153
+ - **Decision:** Fit and calibrate the validation-selected model and an independent
154
+ historical prior once on train plus validation. Serialize canonical numeric
155
+ preprocessing, estimator, calibration, feature-order, cutoff, and fallback
156
+ state into each child lock; bind both state hashes into the aggregate lock.
157
+ - **Held-out rule:** Primary and replication prediction restore those numeric
158
+ states. No classifier/calibrator fit, refit, recalibration, or online update is
159
+ permitted after the aggregate lock becomes durable.
160
+ - **Reason:** A lock that committed only a future refit policy did not freeze the
161
+ actual model used on untouched data.
162
+
163
+ ## 2026-08-08 — Separate deterministic acquisition insufficiency from system faults
164
+
165
+ - **Decision:** Declared-object absence and authenticated metadata/CHECKSUM/ZIP,
166
+ response-size, or total-evidence-budget violations produce a typed immutable
167
+ raw-only `INSUFFICIENT_DATA` authority. Transient-network exhaustion,
168
+ permission/local-I/O errors, collisions, and program faults do not terminalize.
169
+ - **Reason:** Deterministic missing/invalid declared evidence consumes the frozen
170
+ study, while an operational failure must remain safely retryable and cannot be
171
+ recorded as an empirical outcome.
172
+
173
+ ## 2026-08-08 — Define prospective L2 coverage by observed book-state intervals
174
+
175
+ - **Decision:** A frozen session counts only consecutive receipt-time intervals
176
+ backed by `OBSERVED` reconstructed states within one continuity epoch. Stale,
177
+ excluded, gapped, invalid, and silent intervals are not bridged. Cross-symbol
178
+ coverage is the intersection of each symbol's interval union.
179
+ - **Publication:** Both symbols share one absolute UTC barrier and one atomic
180
+ terminal authority. Failed data/gates publish `INSUFFICIENT_DATA`; system
181
+ faults preserve nonterminal raw evidence. No failed date is replaced.
182
+ - **Reason:** Raw first/last websocket timestamps can hide reconnects and silent
183
+ holes and therefore cannot prove usable simultaneous book coverage.
184
+
185
+ ## 2026-08-07 — Enforce raw-only acquisition and lock-before-open execution
186
+
187
+ - **Decision:** Split M8 into an immutable raw authority and a one-way research
188
+ producer. Acquisition authenticates exchange metadata, eight ZIPs, eight
189
+ official CHECKSUM responses, and bounded ZIP directory metadata, but cannot
190
+ open a CSV member. The producer normalizes only train/validation, persists two
191
+ symbol locks and an aggregate lock, then revalidates every committed identity
192
+ immediately before each held-out member is opened.
193
+ - **Reason:** Merely delaying a later Parquet scan would not preserve the
194
+ prospective boundary if held-out economic rows had already been decompressed.
195
+ The first decompressed member byte is therefore the enforced boundary.
196
+ - **Failure policy:** Deterministic data insufficiency before or after locking is
197
+ an immutable terminal result with no replacement date, endpoint prediction,
198
+ execution result, or profitability/significance claim. Unexpected system
199
+ failures publish no partial research target.
200
+ - **Protocol effect:** This is operational hardening only. It changes no date,
201
+ feature, candidate, endpoint, hypothesis, estimand, or interpretation rule.
202
+
203
+ ## 2026-08-07 — Count every retained raw-evidence byte and physical copy
204
+
205
+ - **Decision:** Use one reservation ledger for accepted responses, retry/error
206
+ prefixes, CHECKSUM bodies, exchange metadata, and every source sidecar. Raw
207
+ manifests enumerate the exact physical inventory. A self-contained run copy
208
+ is a distinct retained copy and must fit under the same frozen total ceiling
209
+ before its first byte is written.
210
+ - **Reason:** Per-response limits alone do not bound accumulated retries,
211
+ sidecars, or duplicated evidence on a 16 GB local machine. Post-hoc counting
212
+ could leave an oversized partial publication.
213
+ - **Consequence:** Raw response publication is fail-closed and rollback-safe;
214
+ normalized Parquet and machine-generated manifest indexes remain outside the
215
+ raw-response byte ceiling, as declared by the protocol.
216
+
217
+ ## 2026-08-07 — Freeze future live-L2 sessions before observation
218
+
219
+ - **Decision:** Reserve 14:00–15:00 UTC on 2026-08-08 through 2026-08-11 for
220
+ concurrent BTCUSDT/ETHUSDT development, validation, primary-test, and
221
+ replication-test captures.
222
+ - **Acceptance:** Both symbols need at least 3,300 seconds of overlapping
223
+ receipt-time coverage, a 1,800-second continuous valid epoch, zero sequence
224
+ gaps, zero DQ findings, exact row reconciliation, and complete immutable
225
+ capture evidence.
226
+ - **Reason:** Fixed future sessions prevent outcome-based window choice and make
227
+ disconnects or missing data visible failures rather than hidden replacements.
228
+ - **Claim boundary:** The first protocol is book-only. It permits future-mid
229
+ prediction and market-order scenarios, but not limit-fill, realized execution,
230
+ capacity, significance, or profitability claims.
231
+
232
+ ## 2026-08-07 — Record the Jan 6 coverage-metadata race
233
+
234
+ - **Discovery:** Before a stop message reached the parallel feasibility audit,
235
+ it completed the same official archive availability, checksum, byte/row
236
+ count, aggregate-trade-ID boundary, and timestamp-boundary checks for Jan 6.
237
+ It did not inspect or retain price, quantity, maker direction, class balance,
238
+ features, labels, or model results.
239
+ - **Correction:** Protocol 1.0.2 records coverage-only inspection for all four
240
+ dates. The calendar, roles, hypotheses, model grid, and interpretation rules
241
+ were already frozen and remain unchanged.
242
+ - **Boundary:** This metadata helps verify feasibility and completeness only. It
243
+ is not economic evidence and cannot justify changing or dropping a date.
244
+
245
+ ## 2026-08-07 — Correct the M8 freeze claim to outcome-blind
246
+
247
+ - **Discovery:** A parallel feasibility audit read official Jan 3–5 archive
248
+ availability, checksum, byte/row count, aggregate-trade-ID boundary, and
249
+ timestamp-boundary metadata before commit `a34ba13`. It did not inspect or
250
+ retain economic fields, class balance, features, labels, or model results;
251
+ Jan 6 was not inspected.
252
+ - **Correction:** Protocol 1.0.1 describes the study as outcome-blind rather
253
+ than claiming it was fully acquisition/inspection-blind. The calendar and all
254
+ roles remain unchanged because they were selected mechanically before those
255
+ metadata were reported.
256
+ - **Constraint:** No economic field or model outcome from any declared date may
257
+ be inspected until the ingestion, analysis lock, and final-test gates are
258
+ implemented. Coverage-only facts cannot be used to replace a date.
259
+
260
+ ## 2026-08-07 — Freeze the M8 multi-date trade calendar before acquisition
261
+
262
+ - **Decision:** Reserve the complete 2024-01-03 and 2024-01-04 UTC Binance Spot
263
+ daily aggregate-trade archives for training and validation, and reserve the
264
+ adjacent 2024-01-05 and 2024-01-06 archives as primary and replication tests.
265
+ Both BTCUSDT and ETHUSDT are mandatory. The inspected 2024-01-02 sample is
266
+ excluded from all study estimates.
267
+ - **Reason:** Adjacent dates chosen mechanically before acquisition provide an
268
+ auditable barrier against outcome-based date selection. Full daily archives
269
+ remove the current row-cap truncation while remaining feasible on local disk
270
+ with streaming normalization.
271
+ - **Evaluation:** Model selection uses validation log loss only. A locked model
272
+ is then evaluated without refit on both untouched dates, using paired
273
+ 40-trade-block loss differences and explicit direction-replication status.
274
+ - **Claim boundary:** This is a complete-data trade-only study. Execution, book,
275
+ fill, P&L, capacity, significance, and cross-instrument pooling remain
276
+ unauthorized. M8 still requires separately frozen continuous real L2 evidence.
277
+ - **Failure policy:** Missing, oversized, corrupt, noncontiguous, or otherwise
278
+ invalid declared data produces `INSUFFICIENT_DATA`; dates are never replaced.
279
+
280
+ Material choices are appended; prior entries are not rewritten to hide reversals.
281
+
282
+ ## 2026-08-07 — Initialize the empty `Microstructure` directory
283
+
284
+ - **Context:** The requested `microstructure` folder exists as `Microstructure`
285
+ and contains no files or Git metadata.
286
+ - **Decision:** Treat the capitalized directory as the target and initialize a
287
+ clean Python research repository there.
288
+ - **Consequence:** There is no existing user work to merge or preserve inside the
289
+ target; all new paths are scoped to this directory.
290
+
291
+ ## 2026-08-07 — Separate offline software evidence from market evidence
292
+
293
+ - **Context:** A new user must reproduce a small run without a large download,
294
+ while the project must not invent empirical findings.
295
+ - **Decision:** Make the default smoke/reproduction data a deterministic,
296
+ explicitly synthetic fixture generated from declared rules. Keep public
297
+ Binance ingestion as a separate, credential-free command and never describe
298
+ fixture metrics as empirical market results.
299
+ - **Consequence:** The vertical slice can be tested offline. Economic conclusions
300
+ remain deliberately unavailable until a manifested public-data run is made.
301
+
302
+ ## 2026-08-07 — Use trade events for the initial research slice
303
+
304
+ - **Context:** Historical trades are broadly public and compact; historical full
305
+ depth is less consistently public. The objective explicitly permits trades or
306
+ a small book sample for the first slice.
307
+ - **Decision:** Build the first model dataset from signed trades and event-time
308
+ liquidity proxies. Implement and test L2 snapshot/delta reconstruction as a
309
+ separate adapter path, but do not pretend trade-only data identify queue fills.
310
+ - **Consequence:** Initial fill probability and queue position are declared
311
+ assumptions. Later L2 runs can replace them through the same interfaces.
312
+
313
+ ## 2026-08-07 — Prefer integer event ordering plus UTC nanoseconds
314
+
315
+ - **Context:** Exchange timestamps may tie and floating timestamps can obscure
316
+ exact temporal order.
317
+ - **Decision:** Normalize `event_id`, `sequence`, `event_ts_ns`, and
318
+ `received_ts_ns`. Stable event ordering is `(event_ts_ns, sequence, event_id)`;
319
+ receipt time is retained for latency realism.
320
+ - **Consequence:** Features and labels can state observable cutoffs explicitly;
321
+ downstream modules must not reorder tied events arbitrarily.
322
+
323
+ ## 2026-08-07 — Make validation non-mutating
324
+
325
+ - **Context:** Silent repair can erase evidence of feed or clock problems.
326
+ - **Decision:** Validators emit typed findings and summaries but never mutate raw
327
+ or normalized observations. Any later filtering writes a new derived dataset
328
+ and records exclusion counts.
329
+ - **Consequence:** A run can fail on fatal findings or continue on declared
330
+ warnings without altering source evidence.
331
+
332
+ ## 2026-08-07 — Evaluate event-time models with purged walk-forward folds
333
+
334
+ - **Context:** Random splits leak regime information and overlapping future-label
335
+ horizons leak outcomes across adjacent partitions.
336
+ - **Decision:** Use expanding-window, time-ordered folds. Remove training rows
337
+ whose label end reaches the validation/test boundary and support a configurable
338
+ embargo. Reserve the last fold for final comparison, not model selection.
339
+ - **Consequence:** Small fixtures may yield wide uncertainty; that is preferable
340
+ to optimistic metrics.
341
+
342
+ ## 2026-08-07 — Do not infer historical Spot depth from trade archives
343
+
344
+ - **Context:** Binance's credential-free Spot archive exposes trades and
345
+ aggregate trades, but not a complete historical Level-2 feed suitable for book
346
+ reconstruction. REST snapshots are current anchors rather than historical
347
+ depth observations.
348
+ - **Decision:** Use fixed, bounded public REST aggregate trades for historical
349
+ ingestion. Keep Level-2 research behind an optional public live diff-depth
350
+ collector that begins with a locally received snapshot and creates a new epoch
351
+ after every reconnect or gap.
352
+ - **Consequence:** Historical trade research and book research are different
353
+ evidence paths. No queue, cancellation, or depth claim is inferred from the
354
+ downloaded trade sample.
355
+
356
+ ## 2026-08-07 — Derive numerical scales from exchange metadata
357
+
358
+ - **Context:** Fixed decimal precision can misrepresent instruments and can
359
+ change across venue rules. Binance aggregate-trade timestamps also changed
360
+ archive units for newer files, while REST uses its documented request units.
361
+ - **Decision:** Fetch `PRICE_FILTER.tickSize` and `LOT_SIZE.stepSize` from public
362
+ `exchangeInfo` before normalization, retain integer ticks/lots plus the scale,
363
+ and make timestamp-unit conversion explicit at the adapter boundary.
364
+ - **Consequence:** Exact source values are reproducible without assuming a
365
+ universal `1e-8` quantum. Low-level fallback scales are not used by the sample
366
+ workflow.
367
+
368
+ ## 2026-08-07 — Freeze results as immutable atomic bundles
369
+
370
+ - **Context:** A dashboard or report must never read half-written results, and a
371
+ repeated command must not silently revise earlier evidence.
372
+ - **Decision:** Produce into a sibling staging directory, serialize all inputs,
373
+ folds, metrics, ledgers, assumptions and reports, checksum every file, create
374
+ `_SUCCESS` last, verify the bundle, then atomically rename it. A completed
375
+ target is reusable only if verification passes; incomplete or corrupted
376
+ targets are rejected rather than repaired.
377
+ - **Consequence:** Changed configuration or assumptions require a new run. The
378
+ deterministic semantic run key is based on config, immutable input identity,
379
+ Git state and seed, excluding wall-clock generation time.
380
+
381
+ ## 2026-08-07 — Keep execution conditional and out-of-sample
382
+
383
+ - **Context:** Archived public events cannot identify a strategy's true queue
384
+ position, endogenous impact, or colocated latency. Replaying in-sample
385
+ probabilities would further overstate execution evidence.
386
+ - **Decision:** Accept only validation-selected, held-out test predictions in the
387
+ execution simulator. Treat market depth, limit-fill Bernoulli behavior, queue
388
+ ahead, latency, fees, liquidation and capacity as serialized scenario inputs;
389
+ use common keyed randomness for comparable sensitivities.
390
+ - **Consequence:** Predictive and execution tables remain separate. Simulated
391
+ results are conditional diagnostics, not realized or deployable performance.
392
+
393
+ ## 2026-08-07 — Cap and label the first public sample
394
+
395
+ - **Context:** A local Apple Silicon workflow needs a small, auditable public
396
+ acquisition rather than an open-ended download.
397
+ - **Decision:** Request the fixed interval beginning 2024-01-02 00:00 UTC for
398
+ BTCUSDT and ETHUSDT, capped at 5,000 aggregate trades per symbol, and label the
399
+ acquisition `PUBLIC_SAMPLE_PARTIAL`.
400
+ - **Consequence:** The cap was reached for both symbols. All 10,000 normalized
401
+ rows passed the current validators, but both requested ranges are recorded as
402
+ incomplete and no economic hypothesis is promoted from this sample.
403
+
404
+ ## 2026-08-07 — Freeze the trade-only public study before model comparison
405
+
406
+ - **Context:** The already acquired public sample contains aggregate trades but
407
+ no contemporaneous order-book state. Reusing book features or the execution
408
+ simulator would turn missing observations into assumptions and overstate the
409
+ evidence.
410
+ - **Decision:** Freeze a retrospective, explicitly exploratory trade-only
411
+ protocol with per-symbol causal features, strictly later trade labels,
412
+ purged walk-forward folds, validation-only model selection, and a paired
413
+ fixed-block comparison against the historical prior. Require the caller to
414
+ select the ingestion manifest by both path and SHA-256; never scan for a
415
+ "latest" input. Serialize execution artifacts as `NOT_RUN` with a reason.
416
+ - **Consequence:** BTCUSDT and ETHUSDT are reported separately, including failed
417
+ or contradictory outcomes. The run cannot be interpreted as a book, fill,
418
+ P&L, statistical-significance, or persistent-alpha study.
419
+
420
+ ## 2026-08-07 — Make page/batch streaming the default public ingestion path
421
+
422
+ - **Context:** A configurable row cap made the first 10,000-row sample safe, but
423
+ the original downloader, validator, and ingestion composition retained the
424
+ entire acquisition in memory. A cap on observations is not a RAM contract and
425
+ does not satisfy the larger-history requirement.
426
+ - **Decision:** Expose a lazy, page-bounded Binance iterator; feed each page once
427
+ through an incremental validator with disk-backed exact identity state and
428
+ then into a batch-bounded Parquet writer. Keep eager materialization only as an
429
+ explicit compatibility operation with its own finite row guard.
430
+ - **Consequence:** Public acquisition memory is bounded by response/batch and
431
+ validator preview limits rather than total history length. Manifest and part
432
+ metadata may still grow with page count; downstream full-history readers must
433
+ likewise use verified batch scans instead of eager Arrow/Polars copies.
434
+
435
+ ## 2026-08-07 — Verify public history before exposing a bounded canonical stream
436
+
437
+ - **Context:** Hashing only an ingestion manifest does not prove that normalized
438
+ rows still match the declared raw pages, source symbol, exchange metadata, or
439
+ physical arrival order. Sorting first can also conceal source-order defects.
440
+ - **Decision:** Bind the explicit ingestion path+SHA to configuration, raw URI
441
+ semantics and exact aggregate-trade fields; require inverse raw-to-normalized
442
+ coverage; run physical-order incremental DQ; and feed that single verified
443
+ Arrow stream into a memory-limited DuckDB external sort. Keep eager loading as
444
+ a separately guarded compatibility API.
445
+ - **Consequence:** The current 10,000-row input can be materialized for the
446
+ predeclared small study, while larger consumers can iterate bounded canonical
447
+ batches without trusting a global in-memory sort.
448
+
449
+ ## 2026-08-07 — Make quality evidence atomic and ingestion-manifested
450
+
451
+ - **Context:** Reusing a fixed findings filename could truncate a previous
452
+ complete JSONL before a rerun succeeded, leaving an older summary pointing at
453
+ partial/new evidence.
454
+ - **Decision:** Stream findings into a same-directory temporary file, fsync and
455
+ atomically publish only on validator completion, use a distinct per-ingestion
456
+ quality filename, and bind report/findings paths, byte counts and SHA-256 into
457
+ the immutable ingestion manifest.
458
+ - **Consequence:** A failed rerun cannot damage previously published findings;
459
+ complete quality evidence is independently integrity-checkable.
460
+
461
+ ## 2026-08-07 — Treat the exact source tree as part of run identity
462
+
463
+ - **Context:** A Git commit plus `dirty=true` cannot distinguish different local
464
+ patches. It also allowed an old clean bundle to satisfy `make smoke` after the
465
+ implementation changed.
466
+ - **Decision:** Hash the bytes, paths and modes of every tracked and non-ignored
467
+ untracked source file. Include that digest with commit/dirty state in
468
+ provenance and both synthetic/public run keys; refuse completed-target reuse
469
+ when any component differs. Run the `make check` smoke leg in a fresh temporary
470
+ target.
471
+ - **Consequence:** Ignored raw/run artifacts do not perturb identity, but changed
472
+ code, configuration, tests or documentation requires a new immutable bundle.
473
+
474
+ ## 2026-08-07 — Journal live depth before parsing and reconstruct incrementally
475
+
476
+ - **Context:** Retaining every WebSocket payload, delta and reconstructed book
477
+ row in Python made `collect-l2 --max-messages` an in-memory history limit. A
478
+ malformed frame could also fail before its original bytes were preserved.
479
+ - **Decision:** Emit exact raw frames to a typed capture journal before decoding,
480
+ record each reconnect snapshot anchor, enforce per-frame/batch byte ceilings,
481
+ run a bounded-state incremental book reconstructor and incremental DQ, and
482
+ stream capture-scoped Parquet output. Publish one immutable capture-ID summary
483
+ last; keep the fixed summary filename only as a latest-pointer.
484
+ - **Consequence:** Capture memory is bounded by book depth and batch limits rather
485
+ than message count; every epoch is resnapshotted, every message is reconciled
486
+ to an observation/exclusion, and parse/sequence failure leaves explicit raw
487
+ evidence without fabricating a completed capture.
Microstructure/docs/EXPLORATORY_AGGTRADES_2026_08_05_08.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # August 5–8 public aggregate-trade exploratory protocol
2
+
3
+ ## Scope
4
+
5
+ This retrospective, trade-only study uses the complete official Binance Spot
6
+ daily `aggTrades` archives for BTCUSDT and ETHUSDT on 2026-08-05 through
7
+ 2026-08-08. It is independent of the frozen live-L2 campaign. It contains no
8
+ book depth, spread, queue, cancellation, local receipt time, or executable
9
+ order evidence.
10
+
11
+ The date roles are fixed before any archive CSV member is opened:
12
+
13
+ | UTC date | Role |
14
+ | --- | --- |
15
+ | 2026-08-05 | Train |
16
+ | 2026-08-06 | Validation and model selection |
17
+ | 2026-08-07 | Primary test |
18
+ | 2026-08-08 | Replication test |
19
+
20
+ The evidence tier is `PUBLIC_ARCHIVE_EXPLORATORY`. Results cannot be described
21
+ as confirmatory, statistically significant, persistent alpha, executable P&L,
22
+ or an L2 finding.
23
+
24
+ ## Data and quality
25
+
26
+ Each ZIP must match the exchange-published `.CHECKSUM`, contain exactly its
27
+ declared CSV member, remain inside bounded compressed and expanded byte limits,
28
+ and preserve its raw response and source sidecar. Normalization is streamed to
29
+ partitioned Parquet. Aggregate-trade IDs must be contiguous and event time must
30
+ not reverse within each symbol/date.
31
+
32
+ Quality warnings are retained and reported but do not stop this exploratory
33
+ run; any error, checksum failure, archive-contract failure, ID gap, or temporal
34
+ violation stops the run. No observation is repaired or replaced.
35
+
36
+ ## Features, target, and evaluation
37
+
38
+ Features use only the current and prior trades within one UTC-day continuity
39
+ segment: one-trade return; signed volume, total volume, and imbalance over 5,
40
+ 20, and 100 trades; 50-trade count and intensity; and 100-trade realized
41
+ volatility. The target is whether trade price 20 aggregate trades later is
42
+ higher. Segment tails are censored.
43
+
44
+ The candidate ladder is the historical prior, unpenalized logistic regression,
45
+ the declared L2-regularized logistic grid, and the declared shallow-tree grid.
46
+ Only August 5–6 may select and fit the final selected/prior states. Both symbol
47
+ locks and one aggregate lock must be persisted before either August 7 or August
48
+ 8 CSV member opens. No refit is allowed afterward.
49
+
50
+ Selected-minus-prior log-loss differences are reported separately for both test
51
+ dates and with equal-date weighting. Seeded 40-trade paired block intervals are
52
+ descriptive dependence diagnostics only; no p-values or significance claim are
53
+ authorized. BTCUSDT and ETHUSDT are never pooled.
54
+
55
+ ## Explicit exclusions
56
+
57
+ Execution, fills, fees, capacity, queue position, market impact, profitability,
58
+ and live-L2 conclusions are `NOT_RUN` or unauthorized. A favorable point
59
+ estimate is evidence only about these four retrospective trade archives.
Microstructure/docs/M8_L2_ANALYSIS_CONTRACT.md ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # M8 live-L2 analysis contract
2
+
3
+ ## Authority and status
4
+
5
+ This document is a human-readable, field-complete rendering of
6
+ `configs/m8_l2_analysis.toml`. It does not amend or supersede those bytes. The
7
+ strict loader rejects a changed, missing, or additional field.
8
+
9
+ | Authority | SHA-256 |
10
+ | --- | --- |
11
+ | Analysis TOML source bytes | `0d786d5f4109bb5bf773a6197df3fa861c9b7eb61c16c957bd49fb56147fd7d8` |
12
+ | Analysis TOML canonical semantics | `17c91f64765f35195ab03a4caac93d8ff9c5f009c16e785fd84ebd9569d6f84b` |
13
+ | Bound capture-config source bytes | `b1bf3b4e2820e24e4555bfeb9cb0957f9a0bcdef62039f7d92360e0a97d0dd39` |
14
+ | Bound capture-protocol source bytes | `4c77a2099a4cabd049d10e0f8264d3b4c66704d8e87cbaf0c817fd085f4bbd83` |
15
+
16
+ The calendar, capture gates, model candidate grid, fee, and decision/order
17
+ latency event-count grid remain authoritative in the bound capture config and
18
+ `docs/M8_L2_PROTOCOL.md`; they are not silently restated as analysis-config
19
+ fields here. At freeze time, this contract contained no observed session data or
20
+ model outcome. It therefore authorizes no empirical conclusion by itself.
21
+
22
+ ## Operational enforcement
23
+
24
+ The implemented producer consumes four explicit session bundle paths, manifest
25
+ SHA-256 values, and checksum-file SHA-256 values. Development locking additionally
26
+ binds its aggregate SHA, and final verification/reporting additionally binds the
27
+ run manifest and checksum-file SHA. The campaign authority ties every date to one
28
+ outcome-blind nonce, canonical filesystem root identity, clean source/import
29
+ origin, and hashed Python/platform/production-dependency fingerprint. A final
30
+ bundle snapshots these authorities for self-contained audit while recursively
31
+ revalidating the external originals. Report re-rendering occurs outside the
32
+ immutable run and leaves it unchanged. These enforcement facts implement the
33
+ frozen contract; they are not additional TOML fields or empirical outcomes.
34
+
35
+ ## Study fields
36
+
37
+ | TOML path | Frozen value |
38
+ | --- | --- |
39
+ | `study.name` | `binance-m8-live-l2-analysis` |
40
+ | `study.protocol_version` | `1.0.0` |
41
+ | `study.seed` | `20260807` |
42
+ | `study.source` | `verified_m8_l2_session_bundles` |
43
+ | `study.capture_config_source_sha256` | `491b14727a3e8bad907d1ad64072f6ebc14e407f98a5c31fca7b0a9e6801e758` |
44
+ | `study.capture_protocol_sha256` | `fe6d4aea5af3e9c529486b7e108afefeba623bf5ad3cc0743c0426a5e62e1fa7` |
45
+ | `study.symbols` | `BTCUSDT`, `ETHUSDT` |
46
+ | `study.training_role` | `train` |
47
+ | `study.selection_role` | `validation` |
48
+ | `study.primary_endpoint_role` | `primary_test` |
49
+ | `study.replication_endpoint_role` | `replication_test` |
50
+
51
+ Only checksum-verified session bundles with the exact bound capture authorities
52
+ are eligible. All per-symbol decisions operate inside verified observed
53
+ continuity intervals; reconnects, gaps, excluded state, and invalid intervals
54
+ are never bridged.
55
+
56
+ ## Feature and label fields
57
+
58
+ | TOML path | Frozen value |
59
+ | --- | --- |
60
+ | `features.decision_scope` | `per_symbol_verified_observed_intervals` |
61
+ | `features.flat_direction_policy` | `flat_is_non_up` |
62
+ | `features.rolling_windows` | `20`, `100` |
63
+ | `features.volatility_window` | `100` |
64
+ | `features.clock_max_state_age_ms` | `500` |
65
+ | `features.clock_target_policy` | `exact_target_locf_same_valid_observed_interval` |
66
+ | `features.clock_label_information_end` | `exact_target` |
67
+ | `features.clock_record_target_sequence` | `true` |
68
+ | `features.clock_censor_if_no_eligible_state` | `true` |
69
+
70
+ The exact ordered `features.model_feature_columns` value is:
71
+
72
+ 1. `spread_bps`
73
+ 2. `depth_total_l1`
74
+ 3. `depth_total_l5`
75
+ 4. `depth_total_l10`
76
+ 5. `queue_imbalance_l1`
77
+ 6. `queue_imbalance_l5`
78
+ 7. `queue_imbalance_l10`
79
+ 8. `microprice_deviation_bps`
80
+ 9. `ofi_l1`
81
+ 10. `ofi_w20`
82
+ 11. `ofi_w100`
83
+ 12. `cancellation_intensity_w20`
84
+ 13. `cancellation_intensity_w100`
85
+ 14. `realized_volatility_w20`
86
+ 15. `realized_volatility_w100`
87
+ 16. `volatility_regime_low`
88
+ 17. `volatility_regime_high`
89
+ 18. `liquidity_regime_liquid`
90
+ 19. `liquidity_regime_stressed`
91
+
92
+ For a clock endpoint, the target is the exact horizon time. The eligible future
93
+ book is the most recent state at or before that target, must be no more than 500
94
+ ms old, and must belong to the same valid observed interval. Otherwise the label
95
+ is censored. Its information end remains the exact target, and the chosen target
96
+ sequence is recorded. A zero future return is assigned to the non-up class.
97
+
98
+ ## Endpoint fields
99
+
100
+ | `endpoints` row | `domain` | `horizon_value` | `unit` | `paired_block_width` | `paired_block_unit` | `nominal_event_block_width` |
101
+ | --- | --- | ---: | --- | ---: | --- | ---: |
102
+ | `event_20` | `event` | 20 | `events` | 40 | `events` | 40 |
103
+ | `event_100` | `event` | 100 | `events` | 200 | `events` | 200 |
104
+ | `clock_1000ms` | `clock` | 1000 | `milliseconds` | 2000 | `milliseconds` | 20 |
105
+ | `clock_5000ms` | `clock` | 5000 | `milliseconds` | 10000 | `milliseconds` | 100 |
106
+
107
+ These four rows are the complete `[[endpoints]]` array; each table column maps
108
+ one-for-one to a TOML field. Dependency blocks cannot cross a verified observed
109
+ interval.
110
+
111
+ ## Regime, calibration, bootstrap, and signed-impact fields
112
+
113
+ | TOML path | Frozen value |
114
+ | --- | --- |
115
+ | `regimes.fit_role` | `train` |
116
+ | `regimes.feature` | `realized_volatility_w100` |
117
+ | `regimes.quantile_numerators` | `1`, `2` |
118
+ | `regimes.quantile_denominator` | `3` |
119
+ | `calibration.bins` | `10` |
120
+ | `bootstrap.method` | `paired_moving_block` |
121
+ | `bootstrap.samples` | `2000` |
122
+ | `signed_impact.metric` | `ofi_signed_future_mid_markout` |
123
+ | `signed_impact.side_rule` | `sign_of_horizon_matched_ofi` |
124
+ | `signed_impact.price_rule` | `ofi_sign_times_future_log_mid_return_bps` |
125
+
126
+ Regime cutoffs are the training-role one-third and two-thirds quantiles of
127
+ `realized_volatility_w100`. They are fit once and then applied without update.
128
+ Here “horizon-matched OFI” means decision-time observable rolling OFI matched to
129
+ the endpoint window, never OFI measured during or after the label interval:
130
+ `event_20` and `clock_1000ms` use `ofi_w20`; `event_100` and `clock_5000ms` use
131
+ `ofi_w100`.
132
+ Those columns come from the causal decision feature frame, and their maximum
133
+ source timestamp is validated not to exceed the decision timestamp. The signed-
134
+ impact estimand multiplies that decision-time OFI sign by the strictly future
135
+ log-mid return in basis points. The 2,000-draw paired moving-block design uses
136
+ each endpoint's frozen block width; it does not authorize a p-value or a cross-
137
+ symbol pooled significance claim.
138
+
139
+ ## Execution fields
140
+
141
+ | TOML path | Frozen value |
142
+ | --- | --- |
143
+ | `execution.market_orders_only` | `true` |
144
+ | `execution.probability_threshold` | `0.55` |
145
+ | `execution.symmetric_probability_thresholds` | `true` |
146
+ | `execution.order_notional_usd` | `100.0` |
147
+ | `execution.max_l1_participation` | `0.10` |
148
+ | `execution.inventory_order_multiples` | `10` |
149
+ | `execution.reference_price_fit_role` | `train` |
150
+ | `execution.reference_depth_fit_role` | `train` |
151
+ | `execution.reference_price_statistic` | `train_median_mid_price` |
152
+ | `execution.reference_depth_statistic` | `train_q05_min_bid_ask_l1_depth` |
153
+ | `execution.reference_quantity_policy` | `min_100usd_and_10pct_train_q05_l1_depth_rounded_down_to_lot` |
154
+ | `execution.l1_fill_policy` | `fill_up_to_recorded_l1_depth_cancel_remainder` |
155
+ | `execution.scenario_reset_policy` | `per_symbol_session_endpoint_latency_pair` |
156
+ | `execution.extra_slippage_bps` | `0.0` |
157
+ | `execution.liquidate_at_end` | `true` |
158
+
159
+ The symmetric threshold means long above `0.55`, short below `0.45`, and no
160
+ order otherwise. Reference price and depth are fitted on training data only. The
161
+ reference quantity is the smaller of USD 100 at the training median mid and 10%
162
+ of the training fifth percentile of minimum bid/ask L1 depth, rounded down to the
163
+ exchange lot. Recorded L1 depth caps each fill; any residual is cancelled.
164
+ Inventory is capped at ten reference-order multiples. State resets for every
165
+ symbol, session, endpoint, and latency pair, and end inventory is liquidated.
166
+ Latency values and taker fee are consumed from the separately bound capture
167
+ config; latency is measured in events, not milliseconds. Zero extra slippage is
168
+ a frozen scenario assumption, not a claim that endogenous impact is zero.
169
+
170
+ ## Claim fields
171
+
172
+ | TOML path | Frozen value |
173
+ | --- | --- |
174
+ | `claims.allow_capacity_claim` | `false` |
175
+ | `claims.allow_realized_execution_claim` | `false` |
176
+ | `claims.allow_profitability_claim` | `false` |
177
+
178
+ Accordingly, eventual reports may describe predictive diagnostics and
179
+ serialized market-order scenarios only. They cannot call those scenarios
180
+ realized fills, deployable capacity, or evidence of profitability. Any missing
181
+ or invalid declared session may instead produce `INSUFFICIENT_DATA`; that
182
+ terminal is not replaced and does not count as a test of the economic
183
+ hypothesis unless the required evaluation actually occurred.
Microstructure/docs/M8_L2_PROTOCOL.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # M8 prospective live-L2 protocol — replacement campaign v2
2
+
3
+ ## Scope and frozen calendar
4
+
5
+ This replacement protocol was fixed before any v2 live session occurred. Both symbols
6
+ must be captured concurrently from Binance Spot diff-depth at the requested
7
+ 100 ms stream interval:
8
+
9
+ | UTC session | Role |
10
+ | --- | --- |
11
+ | 2026-08-10 14:00–15:00 | Train |
12
+ | 2026-08-11 14:00–15:00 | Validation |
13
+ | 2026-08-12 14:00–15:00 | Primary test |
14
+ | 2026-08-13 14:00–15:00 | Replication test |
15
+
16
+ The dates are the four consecutive UTC dates beginning after the v2 reset on
17
+ 2026-08-09, and the common hour was chosen before observing those sessions. Missing,
18
+ quiet, volatile, disconnected, corrupt, or unfavorable sessions are never
19
+ replaced. They produce an explicit `INSUFFICIENT_DATA` status. The superseded
20
+ Aug 8–11 campaign and its evidence remain immutable and are not inputs to this
21
+ study. The exact config
22
+ bytes in `configs/m8_l2_capture_study.toml`, this protocol, their hashes, and the
23
+ freeze Git commit must enter every resulting bundle.
24
+
25
+ This is a research-only public market-data capture. It authenticates to no
26
+ account and has no order-entry path.
27
+
28
+ ## Capture and continuity acceptance
29
+
30
+ Each symbol receives its own snapshot and diff-depth stream, started as close to
31
+ the common boundary as the public network allows. Raw websocket bytes must be
32
+ journaled before UTF-8/JSON parsing. Every continuity epoch begins from a fresh
33
+ REST snapshot and may use only buffered deltas satisfying Binance `U/u`
34
+ bridging. Gaps, malformed ranges, crossed books, or scale mismatches terminate
35
+ that epoch; they are recorded rather than repaired.
36
+
37
+ A session is usable only when both symbols satisfy all of the following:
38
+
39
+ - capture-specific completion status is `COMPLETE` and reconstruction ends
40
+ `LIVE`;
41
+ - requested duration is 3,600 seconds and overlapping receipt-time coverage is
42
+ at least 3,300 seconds;
43
+ - at least one valid continuity epoch spans 1,800 seconds;
44
+ - sequence gaps and quality errors/warnings are all zero;
45
+ - no raw frame exceeds 1 MiB and no Arrow batch estimate exceeds 16 MiB;
46
+ - message, normalized-row, reconstructed-row, and excluded-row reconciliation
47
+ is exact;
48
+ - every epoch has a raw snapshot anchor and every raw/normalized/quality file is
49
+ checksum-manifested.
50
+
51
+ The 60,000-message ceiling is a safety bound, not a stopping target. A
52
+ duration-aware graceful stop must publish completion evidence; SIGINT/cancellation
53
+ or hitting the message ceiling early is not a complete one-hour session.
54
+
55
+ ## Causal dataset
56
+
57
+ Continuity is never bridged across reconnects or gaps. At each decision book
58
+ event, features may use only locally received snapshot/delta state available at
59
+ or before that event. Frozen features are absolute/relative spread, L1/L5/L10
60
+ depth, OFI, L1/L5/L10 queue imbalance, microprice displacement, observable
61
+ zero-quantity cancellation intensity, short realized volatility, and regimes
62
+ whose thresholds are fit on the training session only.
63
+
64
+ Labels begin strictly after the decision event and are censored at continuity
65
+ boundaries. Report future mid-price direction/return and signed price impact at
66
+ 20/100-event and 1/5-second horizons. Limit-fill and adverse-selection labels are
67
+ not authorized without contemporaneous trade prints that prove depletion; this
68
+ book-only protocol does not infer them from cancellation alone.
69
+
70
+ ## Evaluation and hypotheses
71
+
72
+ Per symbol, train on Aug 10, select the fixed prior/logistic/L2/tree ladder by Aug
73
+ 11 log loss, lock the specification, then evaluate it without refit on Aug 12 and
74
+ Aug 13. Probability calibration and regime thresholds use development data only.
75
+ All declared horizons and model comparison rows are published; no final period
76
+ is used for selection.
77
+
78
+ The primary book hypothesis is that observable OFI, imbalance, microprice, and
79
+ liquidity state reduce future-mid-direction log loss relative to a historical
80
+ prior on both untouched sessions. Report paired dependency-block differences by
81
+ symbol, session, horizon, and train-defined regime, plus equal-session-weighted
82
+ stability. A result is directionally replicated only if both untouched sessions
83
+ favor the selected model. No p-value, H0 rejection, cross-symbol pooled alpha,
84
+ or significance claim is authorized.
85
+
86
+ ## Execution boundary
87
+
88
+ Only scenario-based market-order evaluation is permitted: recorded best quotes,
89
+ frozen taker fee, decision/order latency grids, inventory bounds, and end-of-run
90
+ liquidation. It may show whether a predictive markout survives those serialized
91
+ assumptions, but it is not realized execution. Limit fills, true queue priority,
92
+ hidden liquidity, endogenous impact, and deployable capacity remain unsupported.
93
+ Every report must keep predictive scores, simulated execution assumptions, and
94
+ scenario P&L separate and must state that profitability is not established.
95
+
96
+ ## Immutable outputs
97
+
98
+ The study requires capture-specific raw journals and snapshots, capture and
99
+ normalized manifests, DQ/exclusion summaries, causal frames, analysis lock,
100
+ frozen predictions/comparisons, regime/stability diagnostics, scenario execution
101
+ ledgers, generated reports, config/protocol/input/Git provenance, checksums, and
102
+ `_SUCCESS` written last. A missing session or failed gate may produce a failure
103
+ bundle, but never a promoted result bundle.
Microstructure/docs/M8_MULTIDATE_TRADE_PROTOCOL.md ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # M8 prospective multi-date aggregate-trade protocol
2
+
3
+ ## Freeze and scope
4
+
5
+ This protocol is outcome-blind: it is frozen before inspecting any declared
6
+ date's price, quantity, aggressor side, class balance, feature, label, model, or
7
+ economic result. During a parallel feasibility audit before the first protocol
8
+ commit, the official Jan 3–5 archive availability, checksums, byte/row counts,
9
+ aggregate-trade-ID boundaries, and timestamp boundaries were inspected. A
10
+ stop-message race then allowed the same coverage-only checks for Jan 6 after the
11
+ outcome-blind freeze; no economic field or result was read. These coverage-only
12
+ facts were not supplied when the dates were chosen, and the mechanically
13
+ selected calendar below was not changed after they became known. The previously
14
+ inspected 2024-01-02 sample is
15
+ protocol-development evidence only and is excluded from every fit, threshold,
16
+ validation score, and test result below.
17
+
18
+ The study is a prospective stability test of the trade-only hypothesis. It is
19
+ not an order-book, execution, profitability, or capacity study. Even a favorable
20
+ result cannot answer the repository's book-dependent or trading-cost questions;
21
+ those require separately frozen, contemporaneous, continuous L2 evidence.
22
+
23
+ The machine-readable specification is
24
+ `configs/m8_multidate_trade_study.toml`. Its exact bytes, Git commit, and SHA-256
25
+ must be copied into the final study bundle. Changing a date, role, feature,
26
+ model, endpoint, or interpretation rule creates a new protocol version and may
27
+ not overwrite this study.
28
+
29
+ ### Protocol-boundary clarification
30
+
31
+ The acquisition/locking rules below are an operational hardening of the
32
+ existing outcome-blind protocol, not an outcome-driven amendment. They change
33
+ no date, role, feature, label, candidate, hypothesis, estimand, or interpretation
34
+ rule. No declared economic outcome was opened to motivate this clarification:
35
+ in particular, no declared price, quantity, buyer-maker value, class balance,
36
+ feature, label, fit, score, or test result has been inspected. The historical
37
+ coverage-only disclosure above remains the complete exception. An
38
+ implementation that cannot enforce the hardened boundary does not execute this
39
+ protocol.
40
+
41
+ ## Data calendar and completeness
42
+
43
+ Use the complete Binance Spot daily aggregate-trade archive for both BTCUSDT and
44
+ ETHUSDT on each UTC date:
45
+
46
+ | UTC date | Frozen role | Permitted use |
47
+ | --- | --- | --- |
48
+ | 2024-01-03 | Train | Feature construction, fitting, train-only thresholds |
49
+ | 2024-01-04 | Validation | Candidate selection only |
50
+ | 2024-01-05 | Primary test | Open once after the selected specification is locked |
51
+ | 2024-01-06 | Replication test | Open with the same locked specification; no refit |
52
+
53
+ The dates were chosen mechanically as the four adjacent dates immediately after
54
+ the inspected 2024-01-02 development sample, not because of observed economic
55
+ outcomes. Pre-freeze coverage-only inspection does not authorize any calendar
56
+ change. Do not replace a quiet, volatile, missing, inconvenient, or unfavorable
57
+ date.
58
+
59
+ All eight symbol/date archives must be present, checksum-verified, and complete
60
+ for `[00:00:00Z, 24:00:00Z)`. A missing archive, truncated response, failed
61
+ checksum, row cap, noncontiguous aggregate-trade ID inside a symbol/date, or data
62
+ quality error makes the study `INSUFFICIENT_DATA`. Such a failure is reported;
63
+ it is not repaired by choosing another date. Raw archives remain immutable and
64
+ uncommitted. Normalized data is partitioned by venue, symbol, and UTC date.
65
+
66
+ Acquisition of all eight archives is **raw-only**. It may verify the exact
67
+ official `CHECKSUM` response, response lengths and hashes, and bounded ZIP
68
+ end-of-central-directory/central-directory metadata for exactly one
69
+ expected-name member and its declared sizes. It must not open, extract, or read
70
+ the CSV member; stream decompressed member bytes; parse even its header; expose
71
+ an economic field; or derive row, ID, timestamp, or class-balance coverage.
72
+ Those operations constitute economic-data opening and belong to the staged
73
+ normalization boundary below. Public `exchangeInfo` may be parsed only for the
74
+ declared symbol's status and exact tick/lot filters, with its exact response and
75
+ response sidecar preserved.
76
+
77
+ Archive transfer and later CSV normalization must both be streaming and
78
+ byte-bounded. The byte ceilings in the machine-readable protocol are hard
79
+ safety limits, not sampling rules:
80
+
81
+ - `max_archive_compressed_bytes` bounds each archive ZIP response body while it
82
+ is transferred; an asserted `Content-Length` does not replace streamed byte
83
+ accounting.
84
+ - `max_archive_uncompressed_bytes` bounds both the central-directory-declared
85
+ size and the actual expanded bytes of each sole CSV member. The limit is
86
+ rechecked while the member is normalized.
87
+ - `max_total_download_bytes` bounds the total immutable raw-evidence bytes
88
+ accepted for this study. The total includes every retained ZIP body, official
89
+ `CHECKSUM` body, raw-response sidecar, `exchangeInfo` metadata body and
90
+ sidecar, and every retained rejected-response prefix and its rejection
91
+ sidecar. A failed attempt or retry does not reset this total. A
92
+ content-addressed file is counted once if it is physically retained once;
93
+ distinct retained copies are counted separately. Derived normalized files,
94
+ quality reports, and aggregate manifest/checksum indexes are not raw-response
95
+ evidence and do not enter this ceiling.
96
+
97
+ The smaller `CHECKSUM`, metadata, and rejected-prefix responses also have fixed
98
+ per-response bounds in the adapter and remain subject to the hard total above.
99
+ Before accepting another raw artifact, the acquisition layer must reserve and
100
+ account for its bounded body and sidecar; no published raw acquisition manifest
101
+ may exceed the total. Crossing any per-response, expanded, or total limit fails
102
+ closed before a research result is produced. Every accepted and rejected raw
103
+ artifact is immutable, byte-counted, hashed, and enumerated by the raw
104
+ acquisition manifest.
105
+
106
+ ## Prospective materialization and lock boundary
107
+
108
+ The study executes in the following one-way order:
109
+
110
+ 1. Acquire and authenticate all eight raw ZIPs, all eight official `CHECKSUM`
111
+ responses, and the exact symbol-metadata responses. Publish the immutable raw
112
+ acquisition manifest without opening any CSV member.
113
+ 2. Open, stream-normalize, and quality-check only the train and validation CSV
114
+ members. Publish an immutable development normalized manifest that binds
115
+ every normalized part, sidecar, quality artifact, and its raw source.
116
+ 3. Select and refit using only those development rows. Persist one lock per
117
+ symbol, then an aggregate lock that commits the exact bytes and SHA-256 of
118
+ both symbol locks. Each symbol lock commits its selected specification,
119
+ development-frame identity, and deterministic final-fit policy; the aggregate
120
+ lock also commits the frozen
121
+ protocol/config, raw acquisition manifest, development normalized manifest,
122
+ and clean real Git revision. Close and `fsync` every lock and digest file and
123
+ `fsync` its containing directory. The aggregate lock is not durable until
124
+ all child locks and their directories are durable.
125
+ 4. Immediately before the first decompressed CSV byte of every primary or
126
+ replication archive is read, re-read and re-hash the exact durable aggregate
127
+ lock and all identities it commits. Only then may that member be
128
+ stream-normalized and quality-checked. Both untouched dates use the same
129
+ locked fit and transformation state; there is no reselection, refit,
130
+ recalibration, threshold change, feature change, or model update after the
131
+ lock, including between primary and replication.
132
+ 5. On success, publish a final normalized manifest covering all eight declared
133
+ symbol/dates. Only that final manifest may authorize endpoint evaluation and
134
+ final-bundle publication.
135
+
136
+ For this boundary, "opened" means the first decompressed byte of a CSV member,
137
+ not a later Parquet scan. Inspecting ZIP directory metadata is not opening the
138
+ member. Merely writing a lock path is not persistence: exact bytes, hashes,
139
+ file descriptors, and containing directories must meet the durability rule
140
+ above before a held-out member-open callback can succeed.
141
+
142
+ ## Timing and continuity
143
+
144
+ Each symbol/date is a separate continuity segment. Features reset at its first
145
+ trade, labels are censored at its final trade, and neither lookbacks nor labels
146
+ cross midnight or a sequence gap. Exchange event time is only an availability
147
+ proxy; aggregate-trade ID breaks tied timestamps. No local receipt-time claim is
148
+ permitted.
149
+
150
+ At decision trade `i`, a feature may use `i` and earlier trades from the same
151
+ verified segment. The target is one only when the price at `i + 20` is greater
152
+ than the decision price. The target trade ID and information-end timestamp are
153
+ serialized. The longest 100-trade lookback and 20-trade label tail determine
154
+ feature readiness and right censoring.
155
+
156
+ ## Frozen features, candidates, and selection
157
+
158
+ The feature set is fixed before acquisition:
159
+
160
+ - one-trade log return;
161
+ - signed quantity, absolute quantity, and signed-volume imbalance over 5, 20,
162
+ and 100 trades;
163
+ - trade count and event-time intensity over 50 trades;
164
+ - realized trade-price volatility over 100 trades.
165
+
166
+ Evaluate, separately for each symbol, the historical-prior classifier,
167
+ unpenalized logistic regression, L2 logistic regression with
168
+ `C in {0.1, 1, 10}`, and shallow decision trees with depth in `{2, 4, 6}` and
169
+ minimum leaf size 40. Median imputation, standardization where applicable, and
170
+ sigmoid calibration are learned only from chronologically earlier rows.
171
+
172
+ The 2024-01-03 fit predicts 2024-01-04. Mean validation log loss selects one
173
+ candidate per symbol; stable candidate order is the tie breaker. After selection,
174
+ the selected candidate is refit once on 2024-01-03 plus 2024-01-04 using the
175
+ same chronological calibration rule. The selected specification and its hash
176
+ are written to an analysis lock before either test date is evaluated. The same
177
+ locked fit predicts both test dates; there is no update between primary and
178
+ replication tests. All candidate validation rows and all locked-model test rows
179
+ are published.
180
+
181
+ ## Hypotheses and estimands
182
+
183
+ For each symbol:
184
+
185
+ - **H0:** the validation-selected model does not reduce held-out log loss versus
186
+ the historical-prior classifier on the untouched dates.
187
+ - **H1:** the validation-selected model reduces held-out log loss versus the
188
+ prior on both the primary and replication dates.
189
+
190
+ The primary estimands are selected-model minus prior log loss for each
191
+ symbol/date and the equal-date-weighted mean across the two test dates for each
192
+ symbol. Negative values favor the selected model. A result is
193
+ `directionally_replicated` only when both date-level point differences are
194
+ negative. Otherwise it is `mixed`, `failed`, or `insufficient_data` according to
195
+ the serialized observations. This status is descriptive and is not a
196
+ significance decision.
197
+
198
+ Uncertainty uses paired, contiguous 40-trade blocks, resetting at every UTC date.
199
+ The same resampled blocks are used for selected and prior predictions. Report
200
+ 2,000 seeded percentile draws for each date and an equal-date-weighted paired
201
+ draw for each symbol. Every interval must contain observations from the two
202
+ nonoverlapping test dates before the aggregate is emitted.
203
+
204
+ No p-values are computed and no H0 rejection or statistical-significance claim
205
+ is authorized. The two symbol hypotheses are not pooled. Candidate, feature,
206
+ date, and regime diagnostics beyond the endpoints above are secondary and are
207
+ reported without selective omission.
208
+
209
+ ## Stability and failed-result reporting
210
+
211
+ The run must publish, by symbol and date:
212
+
213
+ - row counts, UTC bounds, class balance, and all exclusions/censoring;
214
+ - prior and selected-model proper scores and paired loss differences;
215
+ - feature distribution stability using bins fitted on the training date only;
216
+ - validation, primary-test, and replication-test direction consistency;
217
+ - every declared model candidate's validation score;
218
+ - explicit `supported`, `mixed`, `failed`, or `insufficient_data` status.
219
+
220
+ No date or instrument may disappear because its result is unfavorable. Any
221
+ aggregate row must be accompanied by its component date rows.
222
+
223
+ If primary or replication normalization, completeness validation, or data
224
+ quality fails after the aggregate lock is durable, the run stops at the first
225
+ deterministic failure and publishes immutable `INSUFFICIENT_DATA` terminal
226
+ evidence. That evidence binds the same protocol/config, clean Git revision, raw
227
+ acquisition manifest, development normalized manifest, per-symbol locks, and
228
+ aggregate lock; it records the failing symbol/date/role, typed reason, retained
229
+ partial evidence hashes, and which later members remained unopened. It contains
230
+ no endpoint result. Its checksum manifest and terminal marker are written last,
231
+ and publication uses a new atomic target followed by directory durability.
232
+
233
+ The same run identity may only verify and reuse that terminal evidence. It may
234
+ not overwrite or delete it, reopen candidate selection, substitute an input,
235
+ replace a date, relax quality, or continue with a partial aggregate. A source
236
+ fix has a different clean Git revision and therefore a different run identity;
237
+ it still cannot erase the original failed evidence. A failure before locking is
238
+ also reported as `INSUFFICIENT_DATA`, but it cannot create a test-evaluation
239
+ bundle or claim that held-out data was opened under a lock.
240
+
241
+ ## Explicit exclusions and promotion boundary
242
+
243
+ Aggregate trades contain no contemporaneous bid/ask, depth, cancellation,
244
+ queue, or local receipt clock. Therefore this study must serialize execution,
245
+ fills, P&L, fees-to-alpha conversion, and capacity as `NOT_RUN`. It cannot
246
+ promote a book, fill, latency, execution, or profitability claim.
247
+
248
+ `FULL_DATA` means only that every byte of every predeclared daily trade archive
249
+ was verified and included for this narrowly defined trade-only study. It does
250
+ not mean full market observability, external validity, or deployable evidence.
251
+ The overall M8 milestone remains incomplete until a separately frozen protocol
252
+ has at least two nonoverlapping, continuous, contemporaneous L2 capture periods
253
+ per reported interval and connects their gap-safe book states to causal research
254
+ and execution artifacts.
255
+
256
+ ## Required immutable outputs
257
+
258
+ The atomic final bundle must contain the frozen protocol and machine spec,
259
+ per-symbol and aggregate analysis locks, raw acquisition manifest, development
260
+ and final normalized manifests, exact official `CHECKSUM` responses and
261
+ sidecars, exact exchange metadata responses and sidecars, per-date quality
262
+ summary, research/evaluation frames, predictions, candidate comparison, paired
263
+ hypothesis artifact, feature stability, generated report/memo/table, resolved
264
+ configuration, and a clean real Git revision/source-tree identity. The final
265
+ manifest binds all of those exact bytes and hashes. The checksum manifest and
266
+ `_SUCCESS` are written last only after atomic publication and directory
267
+ durability. Corruption, input relocation without matching bytes, a dirty,
268
+ unborn, synthetic, or different source identity, or any incomplete date must
269
+ fail verification and reuse.
Microstructure/docs/PROJECT_PLAN.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Project plan
2
+
3
+ ## Objective
4
+
5
+ Answer, with defensible event-time evidence, when order-flow imbalance and
6
+ liquidity conditions predict short-horizon price movement, and how much apparent
7
+ value remains after fees, latency, fill uncertainty, adverse selection, and
8
+ inventory constraints. The system is research-only and has no live-order path.
9
+
10
+ ## Delivery strategy
11
+
12
+ The first deliverable is one narrow, fully reproducible vertical slice. Broader
13
+ market coverage and more sophisticated models follow only after its contracts,
14
+ timing, and execution accounting are tested.
15
+
16
+ | Milestone | State | Depends on | Deliverable | Acceptance evidence |
17
+ |---|---|---|---|---|
18
+ | M0 Repository contract | Complete | None | Instructions, plan, decisions, status, packaging | Required files exist; Python 3.12 environment installed; config/provenance tests, Ruff, and mypy pass |
19
+ | M1 Event data foundation | Complete | M0 | Binance trade adapter, optional L2 collector, schemas, manifest/checksum, partitioned Parquet | Mocked retries/metadata/pagination; UTC/schema and content-addressed storage tests pass |
20
+ | M2 Book and quality controls | Complete | M1 | Snapshot/delta replay, sequence validation, quality findings | Gap, overlap, crossed-book, duplicate, ordering, invalid value, spread, silence, and clock tests pass |
21
+ | M3 Leakage-safe dataset | Complete | M1-M2 | Trade-flow/book features and future labels | Causal lineage, future-label, censoring, and gap-isolation tests pass |
22
+ | M4 Model evaluation | Complete | M3 | Baseline, logistic/regularized linear, tree; purged walk-forward evaluation | Prior/unpenalized/L2/tree ladder, calibration, bootstrap, purge, and OOT tests pass |
23
+ | M5 Execution research | Complete | M3-M4 | Market/limit fills, latency, partial fills, costs, inventory, liquidation, sensitivity | Deterministic accounting, OOS, volume-conservation, continuity, partial-fill, and liquidation tests pass |
24
+ | M6 Reproducible vertical slice | Complete | M1-M5 | One CLI-driven sample run and machine-readable artifacts | Atomic producer and corruption/idempotence tests pass; canonical smoke requires no network |
25
+ | M7 Research communication | Complete | M6 | Generated technical report/table, IC memo, limitations, dashboard, portfolio material | Render/dashboard tests read only verified artifacts and visibly label evidence tier |
26
+ | M8 Broader empirical study | In progress | M6-M7 | Closed trade-only study plus complete software for the replacement four-date live-L2 capture/analysis campaign | Canonical trade and superseded L2-v1 authorities remain immutable; capture Aug 10--13 under one new campaign authority, publish the Aug 10/11 `LOCKED` or `NOT_CREATED` development authority before Aug 12, and publish a recursively verified result or protocol-declared insufficiency |
27
+
28
+ ## First vertical slice
29
+
30
+ ```text
31
+ small documented event fixture
32
+ -> normalized partitioned Parquet + manifest
33
+ -> explicit data-quality findings
34
+ -> causal trade-flow / liquidity-state features
35
+ -> strictly future return and direction labels
36
+ -> purged walk-forward baseline, logistic, and tree models
37
+ -> latency- and cost-aware simulation
38
+ -> JSON/CSV/Markdown run artifacts and dashboard inputs
39
+ ```
40
+
41
+ The offline fixture is an explicitly synthetic smoke test for software
42
+ reproducibility, not empirical market evidence. `make download-sample` adds a
43
+ small public-data path without making the test suite depend on network access.
44
+
45
+ ## Dependencies
46
+
47
+ - Python 3.12; Polars/PyArrow for bounded-memory transformation and Parquet.
48
+ - DuckDB for partition inspection and aggregation.
49
+ - scikit-learn for transparent, CPU-friendly models and calibration.
50
+ - pytest, Ruff, and mypy for verification.
51
+ - Streamlit for a local read-only research dashboard.
52
+ - Public Binance market-data endpoints only; no API key or account connection.
53
+
54
+ ## Risks and mitigations
55
+
56
+ | Risk | Consequence | Mitigation / acceptance test |
57
+ |---|---|---|
58
+ | Snapshot/delta mismatch or sequence gap | Corrupt book state and false imbalance | Halt the affected segment, emit a finding, require a new snapshot; replay gap tests |
59
+ | Exchange timestamp is not local observability | Optimistic latency and feature timing | Retain event and receipt times; model configurable decision/order latency |
60
+ | Trade-only fixture cannot identify queue dynamics | Fill estimates are assumption-driven | Label fill results as proxy-based; keep book model interface separate |
61
+ | Overlapping horizons leak across folds | Inflated validation estimates | Purge by label end time plus optional embargo; boundary tests |
62
+ | Small/nonstationary sample | Unstable or meaningless inference | Report uncertainty and evidence tier; defer economic claims until M8 |
63
+ | Class imbalance/calibration drift | Misleading probabilities | Persist class rates, Brier/log loss, calibration diagnostics by fold/regime |
64
+ | Fee/latency/fill assumptions dominate P&L | Fragile strategy result | Publish assumption grid and sensitivity; never collapse it into model quality |
65
+ | Public endpoint/schema changes | Broken ingestion | Version adapter/schema, capture response metadata/checksum, contract tests |
66
+ | Memory/disk pressure | Local run failure | Byte-bounded response streams, hard retained-evidence reservations, disk-backed incremental DQ, batch Parquet, verified spill-capable scans, explicit eager guards; measure peak RSS on any successful full L2 production before promotion |
67
+ | Multiple testing | False discoveries | Predeclare core hypotheses, report all tested variants, use adjusted interpretation |
68
+ | Missed or invalid prospective L2 session | Outcome-driven replacement or false continuity | One frozen calendar and campaign identity; atomic `INSUFFICIENT_DATA`; no replacement date; require observed-interval and cross-symbol coverage gates |
69
+ | Source/runtime/root changes across the four captures | Sessions are not one prospective campaign | Root campaign authority binds config/protocol, outcome-blind nonce, canonical output-root filesystem identity, clean source/import origin, and hashed Python/platform/dependency runtime; reject drift before network access |
70
+ | Held-out L2 economic access without a development authority | Selection leakage | Verify Aug 10/11 control authorities and first persist either eight child locks plus one aggregate `LOCKED` authority or a control-only `NOT_CREATED` authority; only the `LOCKED` branch may expose Aug 12/13 frames, and its evaluator has no fit path |
71
+
72
+ ## Acceptance test matrix
73
+
74
+ 1. **Reproduction:** a clean environment follows `README.md`, runs
75
+ `make reproduce-sample`, and receives a run directory with provenance,
76
+ validation, folds, metrics, trades, sensitivities, and reports.
77
+ 2. **Data:** normalization is deterministic; timestamps are UTC; manifest hashes
78
+ match bytes on disk; Parquet is partitioned by source/symbol/date.
79
+ 3. **Book:** snapshot-plus-delta replay enforces side sorting, nonnegative depth,
80
+ sequence continuity, and uncrossed top of book.
81
+ 4. **Timing:** deliberately shifted future values cause leakage tests to fail;
82
+ label intervals never enter feature windows or training folds.
83
+ 5. **Models:** historical/majority, logistic or regularized linear, and tree models
84
+ run on identical time folds without selecting on the final test set.
85
+ 6. **Execution:** fees, two latency components, fill probability/queue proxy,
86
+ partial fills, adverse selection, inventory cap, liquidation, turnover, and
87
+ size/capacity sensitivity are represented and unit tested.
88
+ 7. **Reports:** model table and technical report are rendered from serialized
89
+ results; each carries data interval, config hash, manifests, and Git state.
90
+ 8. **Claims:** synthetic and smoke outputs contain an explicit non-empirical
91
+ banner; no unverified profitability or significance claim is emitted.
92
+
93
+ ## Definition of done
94
+
95
+ The objective's ten acceptance criteria have reproducible evidence for M0-M7:
96
+
97
+ 1. `README.md` provides a clean setup and reproduction path.
98
+ 2. The canonical workflow is deterministic synthetic data and needs no download.
99
+ 3. Snapshot/delta sequence, stale/overlap/gap, crossed-book, and invariant tests pass.
100
+ 4. Feature/label lineage, strict-before joins, censoring, and deliberate leakage tests pass.
101
+ 5. Unpenalized and regularized logistic models plus a shallow tree share frozen OOT folds.
102
+ 6. Execution records fees, two latency stages, queue/fill uncertainty, partial fills,
103
+ adverse selection, inventory, liquidation, turnover, and size sensitivity.
104
+ 7. Reports are rendered from serialized, checksum-verified outputs.
105
+ 8. Run provenance records actual UTC coverage, config/input hashes, seed, runtime,
106
+ Git revision, dirty state, and exact tracked/non-ignored source-tree digest.
107
+ 9. Synthetic watermarks and claim checks prevent an unverified profitability claim.
108
+ 10. Limitations, evidence promotion rules, and the absence of evaluable failed
109
+ hypotheses are documented.
110
+
111
+ Passing M0-M7 completes the portfolio-quality system and first vertical slice.
112
+ M8 remains the active empirical milestone. Its prospective calendar,
113
+ hypotheses, selection rule, untouched tests, uncertainty, failure policy, and
114
+ lock-before-open boundary are frozen in
115
+ `docs/M8_MULTIDATE_TRADE_PROTOCOL.md`. The raw-only acquirer and terminal
116
+ producer are implemented and adversarially tested. All eight full daily archives
117
+ and their official evidence are bound by one verified raw-only manifest, without
118
+ opening a CSV member during acquisition. The subsequent clean-commit economic
119
+ run reached a verified `INSUFFICIENT_DATA` terminal at the ETHUSDT training DQ
120
+ gate: no selection or held-out member access occurred, so the trade hypothesis
121
+ was not evaluated and the date/policy cannot be replaced.
122
+
123
+ Book claims now depend on the separately frozen live-L2 campaign. The immutable
124
+ capture rules are in `docs/M8_L2_PROTOCOL.md`; the exhaustive downstream rules
125
+ and their exact source/semantic hashes are in
126
+ `docs/M8_L2_ANALYSIS_CONTRACT.md`. Remaining acceptance evidence is: the four
127
+ exact session terminals sharing one clean campaign authority; a durable
128
+ `LOCKED | NOT_CREATED` development authority before held-out access; unchanged
129
+ no-refit evaluation on the `LOCKED` branch;
130
+ generated descriptive/predictive/execution artifacts or an honest
131
+ `INSUFFICIENT_DATA` terminal; peak-RSS evidence below the local ceiling; and
132
+ clean-room reproduction. The producer, recursive verifier, CLI/Make interfaces,
133
+ self-contained authority snapshots, and external non-mutating report renderer
134
+ are implemented and covered by offline tests. The existing public sample remains
135
+ exploratory only.
Microstructure/docs/PUBLICATION.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Publication policy
2
+
3
+ ## Approved public scope
4
+
5
+ The Git-reachable source history is approved for public release under the MIT
6
+ License. The release includes source code, tests, configuration, documentation,
7
+ and small non-market fixtures or placeholders only.
8
+
9
+ Ignored local exchange data, normalized and derived tables, fitted states,
10
+ ingestion authorities, generated dashboards, and run artifacts are excluded.
11
+ The detailed boundary is recorded in [DATA_POLICY.md](DATA_POLICY.md).
12
+
13
+ ## Evidence language
14
+
15
+ - `SYNTHETIC_SMOKE` verifies software behavior only.
16
+ - `PUBLIC_SAMPLE_PARTIAL` supports bounded pipeline observations, not persistent
17
+ alpha, profitability, or capacity claims.
18
+ - The frozen trade-only M8 study ended at `INSUFFICIENT_DATA` after a predeclared
19
+ zero-warning gate failed. Selection, held-out evaluation, execution, and P&L
20
+ did not run.
21
+ - Superseded campaign calendars remain historical records and are not presented
22
+ as current authority.
23
+
24
+ ## Permanent destinations
25
+
26
+ - Website: <https://yangxiaoshawn.github.io/projects/microstructure/>
27
+ - GitHub: <https://github.com/YangXiaoShawn/open-economic-quant-microstructure>
28
+ - Dataset mirror: <https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/Microstructure>
29
+ - Interactive Space: <https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory>
Microstructure/docs/PUBLIC_TRADE_PROTOCOL.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Public aggregate-trade exploratory protocol
2
+
3
+ ## Evidence status
4
+
5
+ This protocol governs the first real-data research run built from the fixed,
6
+ capped Binance Spot aggregate-trade sample already acquired for 2024-01-02. It
7
+ is **retrospective and exploratory**, not a preregistered confirmatory study. The
8
+ data availability, per-symbol coverage, and class balance were inspected before
9
+ this document was frozen; model comparison and held-out results were not.
10
+
11
+ Every output must retain the `PUBLIC_SAMPLE_PARTIAL` evidence tier. The run may
12
+ support a sample-specific data and predictability diagnostic, but it cannot
13
+ support a claim about persistent alpha, statistical significance, execution,
14
+ profitability, or capacity.
15
+
16
+ ## Question and hypotheses
17
+
18
+ The narrow question is whether recently observed aggregate-trade direction and
19
+ size contain out-of-time information about the sign of the trade price 20
20
+ aggregate trades later.
21
+
22
+ - **H0:** the transparent model ladder does not improve held-out log loss over a
23
+ historical-prior classifier in this capped sample.
24
+ - **H1 (exploratory):** causal signed-volume and trade-imbalance features improve
25
+ held-out log loss relative to that prior.
26
+
27
+ All tested model rows are published. The final test is not used for feature,
28
+ hyperparameter, calibration, or model selection. A favorable point estimate is
29
+ not called significant; the block bootstrap is a dependence diagnostic, not a
30
+ confirmatory p-value procedure.
31
+
32
+ ## Data and coverage policy
33
+
34
+ - Instruments are BTCUSDT and ETHUSDT, evaluated separately because the fixed
35
+ 5,000-row caps produce different observed clock-time endpoints.
36
+ - The exact ingestion manifest and normalized part hashes are inputs to the run.
37
+ - Internal aggregate-trade IDs must be unique and step by one within each symbol;
38
+ the availability clock must not reverse. Only after those checks may the
39
+ derived research view assign one continuity epoch per symbol. Raw normalized
40
+ rows remain unchanged.
41
+ - Exchange event time is the only historical availability proxy. No local
42
+ receipt-time or colocated-latency claim is allowed.
43
+ - Tied exchange timestamps retain aggregate-trade-ID ordering and remain in the
44
+ same time split.
45
+
46
+ ## Causal feature and label contract
47
+
48
+ At decision trade `i`, features may use trade `i` and earlier trades from the
49
+ same verified continuity epoch:
50
+
51
+ - signed trade volume and absolute volume over 5, 20, and 100 trades;
52
+ - signed-volume imbalance over the same windows;
53
+ - trade count and event-time intensity;
54
+ - one-trade log return;
55
+ - realized trade-price volatility over 100 trades.
56
+
57
+ The target is `1` when the trade price at `i + 20` is above the price at `i`, and
58
+ `0` otherwise. The target trade ID and availability timestamp are serialized.
59
+ Segment tails are right-censored. Feature-ready rows require the full longest
60
+ lookback.
61
+
62
+ ## Evaluation
63
+
64
+ - Each instrument receives its own expanding time-ordered walk-forward plan.
65
+ - Configuration: 1,200 initial decision-time buckets, 400 validation buckets,
66
+ 400 final-test buckets, 400-bucket steps, and a 20-bucket embargo.
67
+ - Label information ending at or after an evaluation boundary is purged.
68
+ - The model ladder is historical prior, unpenalized logistic regression, the
69
+ declared L2 grid, and the declared shallow-tree grid.
70
+ - Selection metric is validation log loss. Calibration is trained only from the
71
+ chronological training/calibration region.
72
+ - The primary H0/H1 diagnostic is the paired difference in held-out log loss:
73
+ validation-selected model minus historical prior on identical `row_id`
74
+ observations. It uses the same seeded resample draw for both models within
75
+ each fixed, contiguous 40-trade block (twice the label horizon), separately
76
+ by instrument. Five hundred draws, the seed, row count, block count, point
77
+ difference, and percentile interval are serialized. Marginal per-model
78
+ intervals are secondary and are never compared as a substitute for the
79
+ paired loss difference.
80
+
81
+ ## Explicit exclusions
82
+
83
+ There is no contemporaneous bid/ask, depth, cancellation, queue, or local
84
+ receipt-time history in this dataset. Therefore this run does not calculate:
85
+
86
+ - order-book imbalance, microprice, spread, or liquidity recovery;
87
+ - limit-fill probability or queue position;
88
+ - market/limit execution, fees-to-alpha conversion, P&L, or capacity.
89
+
90
+ Those analyses require continuous snapshot-plus-delta L2 epochs collected and
91
+ validated separately.
92
+
93
+ ## Promotion criteria
94
+
95
+ This exploratory run cannot be promoted to `FULL_DATA`. A later confirmatory
96
+ study must freeze its protocol before model outcomes are inspected, use multiple
97
+ complete nontruncated dates, preserve adjacent untouched dates for final testing,
98
+ report per-date and cross-instrument stability, and add continuous L2 evidence
99
+ before making book-dependent or execution claims.
Microstructure/docs/RESEARCH_PROTOCOL.md ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Research protocol
2
+
3
+ ## Question and estimands
4
+
5
+ The primary question is not whether a classifier can fit event data. It is
6
+ whether an order-flow or liquidity signal predicts a strictly future price state
7
+ out of time, whether that relationship is stable across symbols and regimes, and
8
+ whether its scale exceeds execution frictions under declared—not inferred—fill
9
+ assumptions.
10
+
11
+ The primary predictive estimands are:
12
+
13
+ 1. the change in future mid-price direction probability associated with a
14
+ one-standard-deviation change in causal order-flow imbalance;
15
+ 2. the conditional future log-mid return across predeclared event horizons;
16
+ 3. the decay of that relationship as the horizon increases;
17
+ 4. the interaction of order flow with contemporaneous spread, depth, volatility,
18
+ and trade intensity.
19
+
20
+ Economic evaluation is a separate conditional exercise: given frozen OOS
21
+ predictions and a declared execution model, measure gross edge, explicit fees,
22
+ arrival cost, post-fill adverse selection, fill fraction, turnover, inventory,
23
+ and marked or liquidated net P&L. It is not an estimate of deployable capacity.
24
+
25
+ ## Predeclared core hypotheses
26
+
27
+ - **H1 — Order-flow direction:** positive trailing signed flow and L1 OFI are
28
+ associated with positive strictly future mid returns, and vice versa.
29
+ - **H2 — Decay:** predictive association is strongest at short horizons and
30
+ decays rather than monotonically increasing with horizon.
31
+ - **H3 — Liquidity interaction:** a given flow shock has larger price impact when
32
+ displayed depth is low or relative spread/volatility is high.
33
+ - **H4 — Recovery:** after a large signed trade or spread/depth shock, liquidity
34
+ recovery time varies with the pre-shock volatility/liquidity regime.
35
+ - **H5 — Stability:** effect direction is not assumed transferable; BTCUSDT and
36
+ ETHUSDT are reported separately before any pooled conclusion.
37
+
38
+ Rejecting or failing to support a hypothesis is a valid result and belongs in
39
+ the generated report. Synthetic smoke data cannot support or reject any market
40
+ hypothesis; it can only verify that the estimands and controls are computed.
41
+
42
+ ## Descriptive analysis contract
43
+
44
+ The run producer persists intraday liquidity, OFI/return association, signal
45
+ decay and half-life, event-time signed impact, large-trade impact, liquidity
46
+ recovery, market regimes, model diagnostics by regime, cross-instrument effect
47
+ stability, and train-versus-test feature stability. Large-trade, shock, recovery,
48
+ and regime thresholds are fitted on the final training rows only and serialized.
49
+ These outputs carry `descriptive_only=true`; synthetic values cannot support or
50
+ reject the hypotheses above.
51
+
52
+ ## Information set
53
+
54
+ A decision sample is keyed by `(available_ts_ns, sequence, event_id)` within a
55
+ continuous segment. A source timestamp is only an availability proxy unless a
56
+ local receipt timestamp exists. Features use observations whose availability key
57
+ is no later than the decision key. Labels start after the decision and end at
58
+ their persisted information-end key. No feature, label, or fold crosses a known
59
+ feed gap.
60
+
61
+ Tied observations from different streams have no assumed causal ordering unless
62
+ the source supplies one. As-of joins therefore use the last strictly observable
63
+ state. Missing future targets are right-censored; they are never filled with the
64
+ last observation.
65
+
66
+ ## Evaluation protocol
67
+
68
+ - Splits follow global UTC/event order with expanding training windows.
69
+ - Training observations whose label interval overlaps the next evaluation
70
+ boundary are purged; a configured embargo adds separation.
71
+ - Imputation, scaling, regime thresholds, feature selection, calibration, and
72
+ hyperparameter choice use training/calibration/validation data only.
73
+ - The final held-out period is evaluated once after model choice is frozen.
74
+ - Baseline, unpenalized/regularized linear, and shallow tree models share the same
75
+ features, folds, and final test observations.
76
+ - Classification reporting includes class support, log loss, Brier score,
77
+ ROC-AUC when defined, accuracy/balanced accuracy, and calibration diagnostics.
78
+ - Return models, when supported, report MAE and rank correlation without treating
79
+ statistical fit as tradable value.
80
+ - Dependent uncertainty uses contiguous event or UTC-day blocks. Fewer than two
81
+ independent blocks produces an `insufficient_blocks` result rather than a
82
+ confidence interval.
83
+
84
+ ## Multiple testing and model selection
85
+
86
+ The core family is the two symbols × predeclared horizons × core OFI association.
87
+ Exploratory regimes, feature variants, model variants, and sensitivity grids are
88
+ reported as exploratory and are not promoted to confirmatory evidence. Where
89
+ p-values are later added for a full-data study, false-discovery-rate adjustment
90
+ is applied within the declared family and both raw and adjusted values are kept.
91
+
92
+ Models are selected on aggregate validation log loss (classification) or MAE
93
+ (regression). Prefer the simpler model when performance is statistically
94
+ indistinguishable under the predeclared rule. The final test cannot change the
95
+ model, signal threshold, calibration, size, latency, or fee assumption.
96
+
97
+ The frozen trade-only public protocol is narrower and is specified separately
98
+ in `docs/PUBLIC_TRADE_PROTOCOL.md`. It evaluates each symbol independently and
99
+ uses the same held-out rows and identical contiguous bootstrap draws for the
100
+ validation-selected model-minus-historical-prior log-loss difference. Marginal
101
+ model intervals are not substituted for that paired estimand. Because the input
102
+ has no contemporaneous book, execution, fill, P&L, and capacity artifacts are
103
+ serialized as `NOT_RUN`, not zero.
104
+
105
+ ## Execution scenarios
106
+
107
+ Base market orders use the book observable at order-arrival time after separate
108
+ decision and order latencies. Available L1 depth caps fills; missing deeper depth
109
+ is not extrapolated. Passive orders join behind a declared queue proxy, fill only
110
+ against eligible opposing printed flow, can fill partially, and remain exposed
111
+ during cancel latency. Maker/taker fees, inventory caps, and end liquidation are
112
+ explicit.
113
+
114
+ Latency, queue position, cancellation ordering, and endogenous impact are not
115
+ identified by archived exchange data. They are scenario inputs and must be shown
116
+ as sensitivity axes. A strategy that works only under the most favorable fill or
117
+ latency scenario fails the economic robustness test.
118
+
119
+ ## Promotion criteria for empirical claims
120
+
121
+ No market conclusion may appear in “main findings” until a manifested public or
122
+ institutional data run has:
123
+
124
+ - at least two non-overlapping UTC dates per reported confidence interval;
125
+ - a frozen final test period not used for selection;
126
+ - acceptable sequence/data-quality coverage for every book-based feature;
127
+ - results for both default instruments or an explicit single-instrument scope;
128
+ - cost/latency/fill sensitivity and failed-hypothesis disclosure;
129
+ - a clean evidence label, config hash, input checksums, and Git state.
Microstructure/portfolio/interview_story.md ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Interview story: Order Flow to Price Impact
2
+
3
+ > **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in
4
+ > this narrative is superseded by the v2 Aug 10–13 protocol recorded in the
5
+ > README and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research
6
+ > history, not current campaign authority.
7
+
8
+ ## One-sentence version
9
+
10
+ I designed a reproducibility-first market-microstructure research system that
11
+ keeps leakage-safe prediction, execution assumptions, and simulated performance
12
+ separate—and refuses to turn synthetic smoke output into an alpha claim.
13
+
14
+ ## The problem
15
+
16
+ Short-horizon market prediction is unusually easy to overstate. Events are
17
+ serially dependent, labels overlap, exchange time is not necessarily receipt
18
+ time, and an accurate forecast can still be untradeable after spread, fees,
19
+ latency, queue uncertainty, adverse selection, and inventory liquidation. Public
20
+ data also varies in depth and quality, while the target machine has 16 GB of RAM
21
+ and no paid data feed.
22
+
23
+ The research question therefore had two parts: under what observable conditions
24
+ does order flow predict a future price change, and how much of that relationship
25
+ survives a separately specified execution model?
26
+
27
+ ## My approach
28
+
29
+ I organized the project around immutable event and run contracts rather than a
30
+ large notebook. Raw observations remain unchanged. Normalized timestamps and
31
+ sequence identifiers make ordering explicit. Features stop at decision event
32
+ `t`; labels begin after `t`. Time-ordered folds purge overlapping label horizons
33
+ and apply an embargo before held-out evaluation.
34
+
35
+ The model ladder begins with a historical or majority baseline, then transparent
36
+ linear and regularized alternatives, followed by bounded nonlinear models. The
37
+ execution layer records fees, two latency components, fill and queue proxies,
38
+ partial fills, adverse selection, inventory limits, liquidation, turnover, and
39
+ size sensitivity independently of predictive metrics.
40
+
41
+ Each run freezes its resolved configuration, input checksums, actual UTC period,
42
+ random seed, runtime, and Git state. Reports and the read-only Streamlit dashboard
43
+ consume that bundle; they cannot retrain a preferred model. Synthetic input
44
+ forces a prominent software-test watermark everywhere.
45
+
46
+ ## A difficult design choice
47
+
48
+ The initial compact data path may contain trades without complete historical
49
+ depth. It would have been easy to present a precise-looking queue simulator, but
50
+ the data cannot identify true queue priority. I treated queue position and fills
51
+ as explicit assumptions, kept the interface replaceable by later Level-2 data,
52
+ and made sensitivity—not a single fill estimate—the relevant output.
53
+
54
+ That decision reduced the apparent sophistication of the first result while
55
+ making the inference more honest.
56
+
57
+ ## Verification strategy
58
+
59
+ The offline smoke path is deterministic and network-free. Focused tests cover
60
+ bundle completion, checksum integrity, evidence-tier consistency, synthetic
61
+ watermarks, held-out-only comparison tables, deterministic rendering, and clear
62
+ dashboard failures for incomplete runs. Research tests separately target event
63
+ ordering, leakage, purged folds, fee accounting, latency, partial fills, and
64
+ inventory constraints.
65
+
66
+ ## What the empirical work actually produced
67
+
68
+ The capped public trade sample remained exploratory and explicitly skipped
69
+ execution because it had no contemporaneous book. The predeclared full-archive
70
+ trade study then produced a useful negative operational result: BTCUSDT training
71
+ data passed, while ETHUSDT training data produced 53 long-silence warnings
72
+ against a zero-warning gate. The pipeline published a checksummed
73
+ `INSUFFICIENT_DATA` terminal before selection and before either held-out date was
74
+ opened. I did not relax the rule, substitute a date, or describe the absence of
75
+ a model result as a failed market hypothesis.
76
+
77
+ For the book extension I froze four simultaneous BTCUSDT/ETHUSDT sessions and a
78
+ field-complete analysis contract before capture. The implementation binds all
79
+ dates to one outcome-blind campaign, clean source/import/runtime identity, and
80
+ canonical storage root; limits features and labels to verified observed
81
+ intervals; locks the Aug 8/9 development state before Aug 10/11; and provides
82
+ no-refit evaluation and market-only scenarios. The final producer recursively
83
+ verifies explicit path and digest authorities, snapshots them into an immutable
84
+ terminal, and renders reports externally without changing the run. Those are
85
+ software controls, not empirical L2 evidence: at the pre-capture source freeze,
86
+ no declared L2 result had been promoted. Tracked source remains unchanged during
87
+ the four-session campaign; immutable session/final bundles carry live status.
88
+
89
+ ## Evidence boundary
90
+
91
+ No empirical economic result is claimed merely because a pipeline ran. A
92
+ synthetic smoke run proves only that the software contracts and accounting
93
+ execute as intended. The bounded public trade run supports exploratory,
94
+ interval-specific diagnostics but no execution or broad claim. The canonical
95
+ full-archive result supports only data insufficiency because evaluation never
96
+ began. Generalization still requires valid adjacent periods, both instruments,
97
+ regimes, uncertainty, and transparent failed hypotheses.
98
+
99
+ ## What I would do next
100
+
101
+ I would operate the completed producer on the already-frozen Aug 8--11 sessions
102
+ without changing their calendar or analysis contract, then complete the
103
+ clean-room and peak-memory audits on the resulting terminal. Aug 8/9 choices
104
+ must be durably locked before Aug 10/11 data is exposed. I would accept a missed
105
+ or invalid session as `INSUFFICIENT_DATA`, not search for a replacement. Only
106
+ after stable no-refit evidence would I consider point-process models; the
107
+ criterion for complexity would be out-of-time economic evidence, not an improved
108
+ in-sample score.
109
+
110
+ ## Likely follow-up questions
111
+
112
+ **Why not random cross-validation?** It mixes regimes and leaks information across
113
+ overlapping future horizons. Walk-forward folds better match deployment order.
114
+
115
+ **Why report calibration?** Thresholded execution decisions consume
116
+ probabilities, so ranking alone is insufficient. Miscalibration changes trade
117
+ frequency, inventory, and cost exposure.
118
+
119
+ **What would make you stop?** Leakage, an invalid book reconstruction, failure on
120
+ the untouched period, instability without an economic explanation, or economics
121
+ that require implausible fills or latency.
122
+
123
+ **What makes this portfolio-quality?** The result is auditable: assumptions,
124
+ failures, provenance, and evidence boundaries are first-class artifacts rather
125
+ than caveats added after seeing performance.
Microstructure/portfolio/resume_bullets.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Resume bullet variants
2
+
3
+ These bullets intentionally make no unverified claim about alpha, profitability,
4
+ statistical significance, throughput, or data volume. Add a measured result only
5
+ after a checksum-verified public-data run supports it.
6
+
7
+ ## Research-focused
8
+
9
+ - Designed a leakage-aware event-time market-microstructure study of order-flow
10
+ imbalance, liquidity state, future price impact, and recovery, using purged
11
+ walk-forward evaluation, calibrated baselines, uncertainty, and explicit
12
+ evidence tiers to separate synthetic tests from empirical findings.
13
+
14
+ ## Quant-trading-focused
15
+
16
+ - Built a research-only signal-to-execution framework that separates predictive
17
+ diagnostics from fee-, latency-, fill-, adverse-selection-, inventory-, and
18
+ liquidation-aware simulation, with gross-to-net and capacity sensitivities
19
+ designed to falsify fragile short-horizon strategies.
20
+
21
+ ## Data-engineering-focused
22
+
23
+ - Engineered a reproducible Python 3.12 microstructure platform around typed
24
+ configuration, immutable manifests, UTC event ordering, partitioned columnar
25
+ data, checksummed run bundles, deterministic reports, and a read-only Streamlit
26
+ dashboard suitable for bounded-memory local analysis.
Microstructure/portfolio/ten_minute_presentation_outline.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ten-minute presentation outline
2
+
3
+ > **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in
4
+ > this outline is superseded by the v2 Aug 10–13 protocol recorded in the
5
+ > README and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research
6
+ > history, not current campaign authority.
7
+
8
+ ## 0:00–0:50 — The question and the trap
9
+
10
+ - Ask when order-flow imbalance and liquidity predict a strictly future move.
11
+ - Then ask whether the effect survives costs and uncertain execution.
12
+ - State the central trap: predictability, executability, and profitability are
13
+ different claims.
14
+
15
+ ## 0:50–1:50 — Evidence hierarchy
16
+
17
+ - `SYNTHETIC_SMOKE`: software behavior only.
18
+ - `PUBLIC_SAMPLE_PARTIAL`: fixed interval, limited inference.
19
+ - `FULL_DATA`: broader manifested study, still simulated and venue-specific.
20
+ - `INSUFFICIENT_DATA`: a declared gate prevented evaluation; no missing estimate
21
+ is replaced with zero or a substitute date.
22
+ - Pre-capture source-freeze status: synthetic vertical slice and bounded public trade
23
+ study completed at their stated tiers; full-archive trade M8 stopped on 53
24
+ ETHUSDT training warnings before selection or held-out access; no performance
25
+ claim and no promoted L2 result.
26
+
27
+ ## 1:50–3:05 — Event-driven data architecture
28
+
29
+ - Public trades and optional Level-2 snapshot/delta adapters.
30
+ - UTC nanoseconds plus sequence/event identifiers establish stable order.
31
+ - Streaming normalization and partitioned Parquet keep memory bounded.
32
+ - Manifests retain source, actual period, schema version, row counts, and hashes.
33
+
34
+ ## 3:05–4:15 — Data quality and leakage controls
35
+
36
+ - Detect duplicates, ordering and sequence gaps, crossed books, invalid values,
37
+ abnormal spreads, silence, and clock discontinuities without silent repair.
38
+ - Features use observations available through decision event `t`; labels start
39
+ after `t`.
40
+ - Use expanding walk-forward folds with purge and embargo for overlapping labels.
41
+
42
+ ## 4:15–5:30 — Economic features and model ladder
43
+
44
+ - Spread, depth, OFI, queue imbalance, microprice, signed volume, intensity,
45
+ volatility, impact, recovery, and regimes when observable.
46
+ - Compare historical/majority, linear or logistic, regularized, and tree models.
47
+ - Select on validation only; report calibration and uncertainty on held-out data.
48
+
49
+ ## 5:30–6:55 — From prediction to execution
50
+
51
+ - Keep model metrics and execution artifacts separate.
52
+ - Record maker/taker fees, decision and order latency, market versus limit fills,
53
+ queue proxy, partial fills, adverse selection, inventory cap, and liquidation.
54
+ - Show gross-to-net and fee/fill/latency/size sensitivity rather than one favored
55
+ P&L number.
56
+
57
+ ## 6:55–8:05 — Reproducibility and reporting
58
+
59
+ - One frozen run bundle records resolved config, input hashes, actual UTC period,
60
+ seed, runtime, Git commit or `UNBORN`, and dirty state.
61
+ - Checksums plus exact `_SUCCESS` or typed `INSUFFICIENT_DATA` markers prevent
62
+ readers from treating partial output as a terminal bundle.
63
+ - Technical report, model table, IC memo, and Streamlit app read frozen artifacts;
64
+ they do not retrain or backfill missing metrics.
65
+ - The four-date L2 path adds an outcome-blind campaign/runtime/storage identity,
66
+ explicit session/lock/run digests, recursive verification, and external report
67
+ rendering that never mutates the empirical bundle.
68
+
69
+ ## 8:05–9:10 — What would count as evidence?
70
+
71
+ - Stable held-out effect across BTCUSDT and ETHUSDT, adjacent periods, and regimes.
72
+ - Calibration and uncertainty, not ROC-AUC alone.
73
+ - Net economics robust to defensible fees, latency, fills, and liquidation.
74
+ - Transparent failures and multiplicity-aware interpretation.
75
+ - For frozen L2: one clean campaign identity, valid simultaneous observed
76
+ intervals, and an Aug 8/9 `LOCKED | NOT_CREATED` development authority that
77
+ predates all Aug 10/11 access; only `LOCKED` permits economic-frame access.
78
+
79
+ ## 9:10–10:00 — Limitations and next experiment
80
+
81
+ - Public event time, queue visibility, hidden liquidity, and venue generalization
82
+ remain limitations.
83
+ - Next: use the completed frozen L2 producer to capture only the Aug 8--11
84
+ simultaneous sessions, then run all four horizons without refit or a
85
+ replacement date and complete peak-memory/clean-room verification. Market-only
86
+ scenarios are not realized execution; capacity and profitability claims
87
+ remain forbidden.
88
+ - Close with the governance boundary: research and simulation only; no live-order
89
+ path.
Microstructure/project.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ title: Order Flow to Price Impact
2
+ slug: microstructure
3
+ summary: Reproducibility-first market-microstructure research that separates data quality, leakage-safe prediction, execution assumptions, and simulated outcomes.
4
+ research_question: When do order-flow imbalance, liquidity, and limit-order-book conditions predict short-horizon price movement, and which claims survive predeclared data-quality and execution gates?
5
+ why_it_matters: Short-horizon market research is easy to overstate. The project makes observability, temporal leakage, data gaps, fees, latency, uncertain fills, adverse selection, and inventory risk explicit before any economic claim is promoted.
6
+ research_fields:
7
+ - Market microstructure
8
+ - Quantitative finance
9
+ - Time-series machine learning
10
+ project_type: empirical-research-system
11
+ status: public-live
12
+ authors:
13
+ - Repository owner and maintainer
14
+ original_source: Microstructure workspace project
15
+ original_sample_period: Public BTCUSDT and ETHUSDT market-data studies use fixed UTC intervals declared in their protocols; deterministic synthetic fixtures exercise the software path.
16
+ updated_sample_period: The published source snapshot includes the frozen trade-only M8 terminal and the replacement live-L2 protocol through the current repository HEAD.
17
+ data_sources:
18
+ - Binance Spot public aggregate-trade endpoints and official archive metadata
19
+ - Optional public live diff-depth and REST snapshots for locally captured L2 sessions
20
+ - Deterministic synthetic fixtures for software verification
21
+ data_license: No exchange raw observations, normalized events, derived tables, fitted models, or generated run bundles are redistributed. Users obtain public market data independently under provider terms; see docs/DATA_POLICY.md.
22
+ code_license: MIT
23
+ reproduction_command: make reproduce-sample
24
+ expected_runtime: The deterministic synthetic vertical slice is suitable for a local laptop. Public-data and live-L2 studies require independent acquisition, explicit immutable authorities, and substantially more storage and compute.
25
+ outputs:
26
+ - src/
27
+ - tests/
28
+ - configs/
29
+ - reports/
30
+ - dashboard/
31
+ - docs/
32
+ github_url: https://github.com/YangXiaoShawn/open-economic-quant-microstructure
33
+ site_url: https://yangxiaoshawn.github.io/projects/microstructure/
34
+ dataset_url: https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/Microstructure
35
+ space_url: https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory
36
+ last_updated: 2026-08-23
37
+ limitations: The public package contains code and documentation, not exchange observations or generated run bundles. Synthetic results are software evidence only. The full-archive trade study terminated at a predeclared data-quality gate, so it published no prediction, execution, profit, capacity, or significance claim.
38
+ catalog:
39
+ field: market-microstructure
40
+ accent: violet
41
+ tags:
42
+ - Market Microstructure
43
+ - Order Flow
44
+ - Reproducible Research
45
+ metric: Predeclared evidence gates
Microstructure/pyproject.toml ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "event-driven-microstructure"
7
+ version = "0.1.0"
8
+ description = "Research-only event-driven order-flow and price-impact platform"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Microstructure Research Project" }]
13
+ dependencies = [
14
+ "duckdb>=1.1,<2",
15
+ "numpy>=2,<3",
16
+ "polars>=1.20,<2",
17
+ "pyarrow>=18,<24",
18
+ "requests>=2.32,<3",
19
+ "scikit-learn>=1.5,<2",
20
+ "streamlit>=1.40,<2",
21
+ "websockets>=14,<17",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "mypy>=1.13,<2",
27
+ "pytest>=8.3,<10",
28
+ "pytest-cov>=6,<8",
29
+ "ruff>=0.8,<1",
30
+ "types-requests>=2.32,<3",
31
+ ]
32
+
33
+ [project.scripts]
34
+ microstructure = "microstructure.cli:main"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/microstructure"]
38
+
39
+ [tool.pytest.ini_options]
40
+ addopts = "-ra --strict-markers --strict-config"
41
+ testpaths = ["tests"]
42
+ markers = [
43
+ "integration: exercises more than one package boundary",
44
+ ]
45
+
46
+ [tool.ruff]
47
+ target-version = "py312"
48
+ line-length = 100
49
+ src = ["src", "tests", "dashboard"]
50
+
51
+ [tool.ruff.lint]
52
+ select = ["E", "F", "I", "B", "UP", "SIM", "RUF"]
53
+ ignore = ["E501"]
54
+
55
+ [tool.ruff.lint.per-file-ignores]
56
+ "tests/**/*.py" = ["S101"]
57
+
58
+ [tool.mypy]
59
+ python_version = "3.12"
60
+ strict = true
61
+ packages = ["microstructure"]
62
+ warn_unreachable = true
Microstructure/reports/executive_memo.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Investment committee research memo
2
+
3
+ > **STATUS: SOURCE-CONTROLLED GOVERNANCE MEMO — RUN-SPECIFIC MEMOS ARE GENERATED BY CODE**
4
+
5
+ > **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in
6
+ > this memo is superseded by the v2 Aug 10–13 protocol recorded in the README
7
+ > and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research history, not
8
+ > current campaign authority.
9
+
10
+ ## Page 1 — Decision and current evidence
11
+
12
+ **Recommendation:** Continue research construction only. Authorize no capital
13
+ allocation, live trading, or connection to an account capable of placing orders.
14
+
15
+ **Decision requested.** The proposed research asks whether order-flow imbalance
16
+ and liquidity state forecast short-horizon price movements and, separately,
17
+ whether any measured effect can survive realistic implementation frictions. The
18
+ decision today is not whether to trade a strategy. It is whether the research
19
+ design is sufficiently falsifiable, reproducible, and execution-aware to finish
20
+ the frozen four-session live-L2 campaign without changing its specification.
21
+
22
+ **Current evidence.** The completed synthetic vertical slice supports a software
23
+ reproducibility claim only. The bounded public acquisition supports a data-
24
+ pipeline observation plus exploratory per-symbol diagnostics only: both symbol
25
+ ranges reached their declared row cap, and execution was `NOT_RUN`. The complete-
26
+ archive trade study reached a valid `INSUFFICIENT_DATA` terminal when ETHUSDT
27
+ training normalization produced 53 warnings against a zero-warning gate.
28
+ Selection never started and neither held-out date was opened. This is a supported
29
+ data-insufficiency conclusion, not an economic-model result. There is no
30
+ supported simulated return, capacity, profitability, or statistical-significance
31
+ claim. This source document therefore contains no substituted performance
32
+ figures; run-specific memos are rendered from frozen artifacts.
33
+
34
+ **Required analytical separation.** The work will preserve three distinct layers.
35
+ First, predictive quality asks whether features observable at decision time
36
+ forecast strictly future labels on time-ordered held-out data. Second, economic
37
+ stability asks whether the relationship persists across horizons, instruments,
38
+ and liquidity or volatility regimes. Third, execution research applies fees,
39
+ spread, decision and order latency, uncertain or partial fills, adverse
40
+ selection, inventory constraints, liquidation, turnover, and size sensitivity.
41
+ Success in one layer does not establish success in another.
42
+
43
+ **Evidence standard.** Model selection must use training and validation periods,
44
+ with purging and embargo where labels overlap. Final test results remain untouched
45
+ until specifications are fixed. Reports must identify every tested model or
46
+ sensitivity relevant to interpretation, include uncertainty, and avoid presenting
47
+ an isolated favorable specification. Every published number must trace to a
48
+ checksum-verified bundle containing actual UTC coverage, configuration and input
49
+ hashes, code state, and evidence tier.
50
+
51
+ <div style="page-break-after: always;"></div>
52
+
53
+ ## Page 2 — Risks, kill criteria, and next evidence
54
+
55
+ **Principal risks.** Exchange timestamps may not represent local observability.
56
+ Public trade data may be adequate for signed-flow research but cannot reveal true
57
+ queue position, hidden liquidity, or cancellation priority. Snapshot and delta
58
+ gaps can corrupt reconstructed books. A short or selected interval can confound
59
+ signal with regime. Repeated features, horizons, and thresholds create
60
+ multiple-testing risk. Fee, latency, fill, and liquidation assumptions can
61
+ dominate simulated results. Venue-specific cryptocurrency behavior may not
62
+ generalize to institutional instruments or other matching engines.
63
+
64
+ **Controls.** Preserve raw events; emit validation findings without silent repair;
65
+ make ordering and label boundaries explicit; persist fold definitions; compare
66
+ against simple baselines; calibrate probabilities; report bootstrap intervals;
67
+ and show results by regime and instrument. Execution assumptions must be
68
+ configuration-controlled and shown alongside gross-to-net attribution. The
69
+ dashboard must read frozen, bounded artifacts and cannot trigger trading or
70
+ recompute a preferred result. The four L2 sessions must share one clean
71
+ campaign, runtime/import fingerprint, and canonical storage-root identity. Every
72
+ development/final command consumes explicit path plus manifest/checksum/lock
73
+ authorities. Reports are re-rendered outside the immutable run only after
74
+ recursive verification.
75
+
76
+ **Kill criteria.** Do not escalate the research if a result depends on future
77
+ information, fails sequence or checksum validation, disappears on the untouched
78
+ test period, reverses across instruments or adjacent periods without an economic
79
+ explanation, requires implausibly favorable latency or fills, or fails to remain
80
+ competitive with the declared baseline after recorded costs. A high predictive
81
+ score without calibration or executable economics is also insufficient.
82
+
83
+ **Next evidence requested.** Preserve the trade insufficiency terminal without a
84
+ replacement date or relaxed quality rule. Use the completed frozen
85
+ BTCUSDT/ETHUSDT live-L2 software path to collect only the declared Aug 8--11 UTC
86
+ sessions under one clean campaign identity. Publish every session gate and
87
+ quality exception; lock Aug 8/9 model, regime, calibration, and execution-
88
+ reference state before either Aug 10/11 frame is opened; then publish all
89
+ predeclared horizons, dependency-block uncertainty, equal-session stability,
90
+ market-only sensitivity scenarios, failed hypotheses, and remaining
91
+ limitations—or publish `INSUFFICIENT_DATA` if a declared gate fails. At this
92
+ pre-capture source freeze, no L2 data or metric had been promoted; the tracked
93
+ memo remains unchanged during the campaign. Only after those checks should the
94
+ committee consider broader research. Live deployment remains outside scope
95
+ regardless of the outcome.
Microstructure/reports/methodology_limitations.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Methodology and limitations
2
+
3
+ > **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in
4
+ > this document is superseded by the v2 Aug 10–13 protocol recorded in the
5
+ > README and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research
6
+ > history, not current campaign authority.
7
+
8
+ ## Evidence tiers
9
+
10
+ - `SYNTHETIC_SMOKE` verifies deterministic software behavior only. Its values are
11
+ neither market observations nor investment evidence.
12
+ - `PUBLIC_SAMPLE_PARTIAL` describes a fixed, bounded public-data interval. It may
13
+ support interval-specific research observations but not broad generalization.
14
+ - `FULL_DATA` is reserved for a manifested empirical study meeting its declared
15
+ coverage and acceptance tests. It still represents research and simulation,
16
+ not realized live performance.
17
+ - `INSUFFICIENT_DATA` is a terminal evidence status, not a lower-quality set of
18
+ model estimates. It means a predeclared input or quality gate prevented the
19
+ required evaluation; absent predictions and execution fields remain absent
20
+ rather than being imputed, rerun on replacement dates, or reported as zeros.
21
+
22
+ Evidence tier is derived from data manifests. A synthetic source cannot be
23
+ promoted by changing a report label.
24
+
25
+ ## Time and observability
26
+
27
+ All reported intervals are UTC. Stable event ordering uses the normalized event
28
+ timestamp plus sequence and event identifiers; tied timestamps are not reordered
29
+ arbitrarily. Exchange event time is not automatically equivalent to local receipt
30
+ time. A feature at decision event `t` may contain only values observable at or
31
+ before `t`; its label begins strictly after `t`. Decision and order latency are
32
+ separate assumptions.
33
+
34
+ Time-ordered evaluation is necessary but not sufficient. When label intervals
35
+ overlap a fold boundary, affected training rows must be purged. Configured embargo
36
+ separates adjacent folds. The final test period is not used for model selection,
37
+ feature selection, hyperparameter tuning, threshold choice, or probability
38
+ calibration.
39
+
40
+ ## Data lineage and quality
41
+
42
+ External raw data is immutable and excluded from Git. Each download or fixture
43
+ requires a source, retrieval time or deterministic generation rule, requested and
44
+ observed period, schema version, row count, and checksum. Normalization and later
45
+ exclusions create new artifacts rather than rewriting raw observations.
46
+
47
+ Validation covers duplicates, out-of-order timestamps, missing sequence ranges,
48
+ crossed books, nonpositive price or quantity, abnormal spread, long silence, and
49
+ clock discontinuities. A warning does not prove an observation is harmless. A
50
+ fatal gap can require abandoning an affected reconstruction segment rather than
51
+ interpolating it.
52
+
53
+ Public endpoints can change schema, retention, throttling, or geographic
54
+ availability. Download success does not establish completeness. Exchange
55
+ maintenance, symbol-rule changes, clock behavior, delistings, and missing markets
56
+ can bias a selected sample.
57
+
58
+ The canonical full-archive trade M8 result illustrates this boundary. BTCUSDT
59
+ training normalization completed on 2,071,461 rows with no findings. ETHUSDT
60
+ training normalization completed on 987,297 rows with zero errors but 53 long-
61
+ silence warnings, violating the frozen zero-warning gate. Selection did not
62
+ start, neither held-out date was opened, and execution was not run. This supports
63
+ the conclusion that the declared trade study was data-insufficient; it neither
64
+ supports nor refutes the economic hypothesis. Relaxing the warning rule or
65
+ choosing another date after seeing that terminal would invalidate the protocol.
66
+
67
+ ## Market-state and feature measurement
68
+
69
+ Order-flow imbalance, signed volume, intensity, spread, depth, queue imbalance,
70
+ microprice, volatility, price impact, liquidity recovery, and regime features are
71
+ conditional on the event types actually observed. Trade signing can be wrong.
72
+ Displayed depth can be cancelled before execution. Aggregated or trade-only data
73
+ cannot identify hidden orders, matching-engine priority, or individual queue
74
+ position. Cancellation intensity is unavailable unless the feed exposes enough
75
+ book history to measure it defensibly.
76
+
77
+ Feature windows create serial dependence, and overlapping future labels reduce
78
+ effective sample size. Intraday and volatility regimes may be unbalanced. A
79
+ relationship can reflect a common response to news rather than a causal effect of
80
+ order flow on price.
81
+
82
+ ## Statistical modeling
83
+
84
+ Simple historical or majority baselines anchor the model ladder. Linear and
85
+ regularized models provide interpretable comparisons; a tree model tests bounded
86
+ nonlinearity. More complex time-series or point-process models require a stated
87
+ economic reason and evidence that simpler models leave meaningful structure.
88
+
89
+ ROC-AUC alone can obscure calibration and class imbalance. Classification reports
90
+ should include log loss, Brier score, precision-recall diagnostics where useful,
91
+ class rates, and calibration. Regression reports require scale-aware errors and a
92
+ baseline comparison. Bootstrap confidence intervals must respect temporal
93
+ dependence. Repeated instruments, horizons, regimes, features, thresholds, and
94
+ models create multiplicity; an unadjusted favorable result is exploratory.
95
+
96
+ Model importance is not structural causality. Feature rankings can be unstable
97
+ under correlation or regime shift. A selected model may decay after the observed
98
+ period, and cryptocurrency venue behavior may not transfer to equities, futures,
99
+ or fragmented markets.
100
+
101
+ ## Execution and fills
102
+
103
+ Predictive metrics are not execution results. Simulated economics depend on maker
104
+ and taker fees, half-spread and slippage, decision and order latency, order size,
105
+ fill probability, queue proxy, partial fills, adverse selection, inventory cap,
106
+ liquidation, and capacity assumptions. Each assumption must be serialized and
107
+ sensitivity-tested.
108
+
109
+ A queue proxy is not true priority. A fill inferred from subsequent traded volume
110
+ can be optimistic when cancellations, hidden liquidity, competing orders, and
111
+ matching rules are unknown. Limit-order simulations can suffer severe adverse
112
+ selection; market-order simulations can understate impact. Forced end-of-period
113
+ liquidation may dominate a short sample. Capacity extrapolation from public top-of-
114
+ book data is especially uncertain.
115
+
116
+ Annualized return or Sharpe-like statistics are inappropriate for synthetic or
117
+ very short runs. Simulated P&L excludes operational failures, exchange outages,
118
+ funding and financing where omitted, taxes, custody, counterparty risk, and live
119
+ model drift. The project contains no order-entry path and is not a deployment
120
+ system.
121
+
122
+ The frozen live-L2 extension narrows execution further. It permits market-order
123
+ scenarios only, with threshold, reference notional/depth, lot rounding, L1 fill
124
+ cap, inventory, liquidation, fee, and decision/order latency rules fixed before
125
+ held-out access. Latencies in this campaign are event counts, not milliseconds.
126
+ Recorded L1 limits the scenario fill and any residual is cancelled; no deeper
127
+ walk, hidden liquidity, endogenous reaction, or true impact is modeled. The
128
+ frozen zero-extra-slippage setting is one transparent scenario, not evidence
129
+ that slippage is zero. Capacity, realized execution, limit-fill, queue-priority,
130
+ and profitability claims remain forbidden.
131
+
132
+ ## Prospective live-L2 boundary
133
+
134
+ The Aug 8--11 BTCUSDT/ETHUSDT sessions must share one clean capture runtime
135
+ identity and pass the exact simultaneous observed-interval gates. Raw websocket
136
+ receipt time is available, but it is internet-path receipt time—not a colocated
137
+ clock or matching-engine acknowledgment. A long nominal session cannot conceal
138
+ gaps: features and labels are limited to verified observed intervals, and clock
139
+ targets are censored if no sufficiently fresh same-interval state exists.
140
+
141
+ The campaign authority also binds an outcome-blind nonce, the one canonical
142
+ output-root path and filesystem identity, the loaded package/module origin, and
143
+ a hashed Python/platform/production-dependency fingerprint. These controls make
144
+ environment and storage substitution visible, but they do not make public-
145
+ internet latency colocated or prove that the exchange feed was complete.
146
+
147
+ Regime thresholds are fit on Aug 8 only. When both development sessions are
148
+ complete, model selection and calibration use Aug 8/9 only and must be committed
149
+ in eight symbol-by-endpoint child locks plus one aggregate `LOCKED` authority
150
+ before Aug 10/11 frames are exposed. If either development session is
151
+ insufficient, a control-only `NOT_CREATED` authority is committed instead and no
152
+ economic frame from any session is opened. Held-out evaluation restores only a
153
+ `LOCKED` state without refit. Paired moving-block intervals
154
+ partially address serial dependence but do not prove independence, solve all
155
+ overlapping-horizon dependence, correct every model/horizon/regime comparison,
156
+ or authorize a p-value. Directional agreement across two adjacent one-hour
157
+ sessions is still a narrow venue- and period-specific result.
158
+
159
+ At the pre-capture source freeze, these were software and governance controls,
160
+ not book evidence: no declared L2 session bundle or downstream L2 metric had
161
+ been promoted. This tracked file is intentionally unchanged during the four-day
162
+ campaign. The exact field-level authority is
163
+ `docs/M8_L2_ANALYSIS_CONTRACT.md`; any eventual numbers must come from a verified
164
+ generated bundle rather than this source-controlled limitations file.
165
+
166
+ The completed final producer takes four explicit session path/manifest/checksum
167
+ authorities plus the development-authority path and SHA. A development or
168
+ held-out session failure
169
+ or no eligible label produces a checksummed `INSUFFICIENT_DATA` terminal with no
170
+ promoted evaluation or execution, rather than an opportunistic retry. A complete
171
+ run copies exact control authorities into a self-contained snapshot but still
172
+ revalidates their external originals. Reports are re-rendered from a checksummed
173
+ report-input snapshot into a separate directory; report generation cannot mutate
174
+ the immutable empirical bundle. These are integrity and governance guarantees,
175
+ not proof that the economic design or market conclusion is correct.
176
+
177
+ ## Reporting and generalizability
178
+
179
+ Generated reports read serialized artifacts; they do not recalculate statistics.
180
+ Every surface shows evidence tier, observed UTC interval, configuration hash,
181
+ input-manifest hashes, Git commit or `UNBORN`, and dirty state. Missing values are
182
+ `N/A`, never zero. Checksums demonstrate byte integrity, not correctness of the
183
+ economic design.
184
+
185
+ Results from BTCUSDT and ETHUSDT on one venue cannot be assumed to apply to other
186
+ symbols, venues, asset classes, tick sizes, participant mixes, or regulatory
187
+ settings. Robustness requires predeclared adjacent periods, cross-instrument and
188
+ regime comparisons, alternative defensible execution assumptions, and careful
189
+ documentation of results that fail.
Microstructure/reports/model_comparison.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model comparison
2
+
3
+ > **STATUS: SOURCE-CONTROLLED TEMPLATE — RUN-SPECIFIC TABLES ARE GENERATED BY CODE**
4
+
5
+ This file intentionally contains no copied model or execution numbers. Run-
6
+ specific held-out tables are rendered from the frozen bundle by `make report`.
7
+
8
+ The generated table will be built from serialized run artifacts and will include
9
+ the evidence tier, instrument, horizon, model, held-out split, sample count,
10
+ actual UTC test period, predictive diagnostics, gross and net execution
11
+ diagnostics, fill rate, turnover, drawdown, and the validation-only selection
12
+ criterion. Unsupported values will render as `N/A`, not zero.
Microstructure/reports/technical_report.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Technical report
2
+
3
+ > **STATUS: SOURCE-CONTROLLED TEMPLATE — RUN-SPECIFIC REPORTS ARE GENERATED BY CODE**
4
+
5
+ This is the canonical report location for *Order Flow to Price Impact*. It does
6
+ not contain manually copied empirical or synthetic performance results.
7
+ `make reproduce-sample` produces a checksum-verified frozen bundle containing its
8
+ evidence tier, configuration/input hashes, observed UTC interval and Git state;
9
+ `make report` then renders a run-specific document without retraining or
10
+ recomputing statistics.
11
+
12
+ ## Research question
13
+
14
+ When do order-flow imbalance, liquidity, and observable limit-order-book state
15
+ predict short-horizon price changes, and how much apparent predictive value
16
+ survives fees, latency, uncertain fills, adverse selection, and inventory risk?
17
+
18
+ ## Planned evidence structure
19
+
20
+ The study separates three questions that are often conflated:
21
+
22
+ 1. Does an observable feature predict a strictly future outcome on an untouched,
23
+ time-ordered test period?
24
+ 2. Is the effect stable across instruments, horizons, and liquidity or volatility
25
+ regimes, with uncertainty and multiple testing acknowledged?
26
+ 3. Does any apparent effect survive a separately specified execution model?
27
+
28
+ The model ladder begins with historical-mean or majority baselines, followed by
29
+ transparent linear and regularized models and a bounded tree model. Model choice
30
+ uses training and validation data only. Overlapping label intervals require
31
+ purging and embargo before final held-out comparison.
32
+
33
+ ## Data and temporal integrity
34
+
35
+ No data period is hard-coded in this source template. A generated report takes
36
+ its actual minimum and maximum event timestamps from the frozen bundle—not merely
37
+ from requested configuration dates. Raw observations remain
38
+ unchanged; validation findings and any downstream exclusions are recorded
39
+ separately.
40
+
41
+ At decision event `t`, features may use only information proven observable at or
42
+ before `t`. Labels begin strictly after `t`. Exchange event time and local receipt
43
+ time are distinct where both exist.
44
+
45
+ ## Predictive model quality
46
+
47
+ No model metrics are embedded in this template. The generated comparison reports
48
+ held-out sample size and period, ROC-AUC or regression diagnostics as applicable,
49
+ log loss, Brier score, expected calibration error, and serialized fixed-block
50
+ bootstrap intervals. Regime-level outcomes and model diagnostics are persisted as
51
+ separate descriptive analysis artifacts rather than folded into the comparison
52
+ table. Missing metrics will display as `N/A`, never as zero.
53
+
54
+ ## Execution and simulated performance
55
+
56
+ No execution result is embedded here. Generated simulation results state maker
57
+ and taker fees, decision and order latency, queue/fill proxy, partial fills,
58
+ adverse selection, inventory limits, liquidation, turnover, and trade-size or
59
+ capacity sensitivity. Predictive metrics and execution metrics remain separate.
60
+
61
+ ## Economic interpretation
62
+
63
+ There is currently no supported claim about predictability, profitability,
64
+ statistical significance, or deployability. The synthetic smoke run validates
65
+ software plumbing only and carries the mandatory
66
+ `SYNTHETIC_SMOKE` warning on every output surface.
67
+
68
+ ## Limitations
69
+
70
+ See [methodology_limitations.md](methodology_limitations.md) for the maintained
71
+ methodology and limitations register. Even a completed public-data analysis will
72
+ remain venue-specific, sensitive to timestamp and fill assumptions, and distinct
73
+ from realized live execution.
74
+
75
+ ## Reproduction record
76
+
77
+ Run `make reproduce-sample && make verify-run && make report`. The generated
78
+ report records run ID, evidence tier, observed UTC period, configuration SHA-256,
79
+ input-manifest SHA-256 values, Git commit, dirty state and runtime metadata. The
80
+ source-controlled template intentionally remains free of copied metrics.
Microstructure/src/microstructure/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Event-driven market-microstructure research package."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("event-driven-microstructure")
7
+ except PackageNotFoundError: # pragma: no cover - editable source without metadata
8
+ __version__ = "0+unknown"
9
+
10
+ __all__ = ["__version__"]
Microstructure/src/microstructure/cli.py ADDED
@@ -0,0 +1,2003 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Command-line interface for research data, reproduction, and reporting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import base64
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
15
+ from contextlib import suppress
16
+ from dataclasses import asdict, dataclass
17
+ from decimal import Decimal
18
+ from pathlib import Path
19
+ from typing import Any, Literal, cast
20
+
21
+ import pyarrow as pa # type: ignore[import-untyped]
22
+
23
+ from microstructure import __version__
24
+ from microstructure.config import ProjectConfig, datetime_to_ns, load_config
25
+ from microstructure.data.binance import (
26
+ BinanceLiveDepthCollector,
27
+ BinancePublicClient,
28
+ CapturedDepth,
29
+ RawDepthFrame,
30
+ )
31
+ from microstructure.data.book import BookSnapshot, IncrementalBookReconstructor
32
+ from microstructure.data.quality import IncrementalQualityValidator, ValidationReport
33
+ from microstructure.data.schemas import get_schema, table_from_records
34
+ from microstructure.data.storage import write_capture_parquet, write_source_manifest
35
+ from microstructure.data.synthetic import generate_synthetic_market
36
+ from microstructure.ingestion import (
37
+ IngestionResult,
38
+ ingest_from_config,
39
+ validate_configured_input,
40
+ )
41
+ from microstructure.m8_acquisition import (
42
+ M8AcquisitionFailureResult,
43
+ M8AcquisitionResult,
44
+ acquire_m8_archives,
45
+ )
46
+ from microstructure.m8_config import load_m8_config
47
+ from microstructure.m8_l2_analysis_config import (
48
+ M8L2AnalysisConfig,
49
+ load_m8_l2_analysis_config,
50
+ )
51
+ from microstructure.m8_l2_binance import BinanceM8L2Capture
52
+ from microstructure.m8_l2_capture import (
53
+ M8L2SessionBundle,
54
+ capture_m8_l2_session,
55
+ verify_m8_l2_session_bundle,
56
+ )
57
+ from microstructure.m8_l2_config import M8L2StudyConfig, load_m8_l2_config
58
+ from microstructure.m8_l2_development import (
59
+ L2DevelopmentInputVerifier,
60
+ L2DevelopmentLockResult,
61
+ lock_m8_l2_development,
62
+ verify_m8_l2_development_lock,
63
+ )
64
+ from microstructure.m8_l2_inputs import (
65
+ L2CampaignRuntimeIdentity,
66
+ L2SessionFileAuthority,
67
+ verify_m8_l2_development_input,
68
+ )
69
+ from microstructure.m8_l2_pipeline import (
70
+ L2StudySessionAuthority,
71
+ M8L2StudyRunResult,
72
+ load_m8_l2_report_data,
73
+ reproduce_m8_l2_study,
74
+ verify_m8_l2_study_run,
75
+ )
76
+ from microstructure.m8_pipeline import M8RunResult, reproduce_m8, verify_m8_result
77
+ from microstructure.pipeline import reproduce
78
+ from microstructure.provenance import read_json, sha256_file, utc_now_iso, write_json
79
+ from microstructure.reporting import (
80
+ canonical_report_data_sha256,
81
+ load_run_bundle,
82
+ verify_checksums,
83
+ write_l2_report_set,
84
+ write_report_set,
85
+ )
86
+
87
+
88
+ def _json_default(value: object) -> object:
89
+ if isinstance(value, Path):
90
+ return str(value)
91
+ if isinstance(value, Decimal):
92
+ return str(value)
93
+ raise TypeError(f"cannot serialize {type(value).__name__}")
94
+
95
+
96
+ def _print_json(payload: object) -> None:
97
+ print(json.dumps(payload, indent=2, sort_keys=True, default=_json_default))
98
+
99
+
100
+ def _ingestion_payload(result: IngestionResult) -> dict[str, Any]:
101
+ return {
102
+ "mode": result.mode,
103
+ "evidence_tier": result.evidence_tier,
104
+ "output_root": result.output_root,
105
+ "ingestion_manifest": result.ingestion_manifest_path,
106
+ "ingestion_manifest_sha256": result.ingestion_manifest_sha256,
107
+ "rows": result.rows,
108
+ "datasets": [
109
+ {
110
+ "schema": dataset.schema_name,
111
+ "rows": dataset.rows,
112
+ "manifest": dataset.storage.manifest_path,
113
+ "manifest_sha256": dataset.storage.manifest_sha256,
114
+ "quality_errors": dataset.validation.error_count,
115
+ "quality_warnings": dataset.validation.warning_count,
116
+ }
117
+ for dataset in result.datasets
118
+ ],
119
+ "raw_artifacts": len(result.raw_artifacts),
120
+ "symbols": [
121
+ {
122
+ "symbol": item.symbol,
123
+ "rows": item.rows,
124
+ "complete_range": item.complete_range,
125
+ "tick_size": item.metadata.tick_size,
126
+ "lot_size": item.metadata.lot_size,
127
+ }
128
+ for item in result.symbols
129
+ ],
130
+ "quality": {
131
+ "passed": result.validation.passed,
132
+ "rows_checked": result.validation.rows_checked,
133
+ "errors": result.validation.error_count,
134
+ "warnings": result.validation.warning_count,
135
+ },
136
+ }
137
+
138
+
139
+ def _cmd_ingest(args: argparse.Namespace) -> int:
140
+ config = load_config(args.config)
141
+ output_root = (
142
+ Path(args.output_root).resolve() if args.output_root else config.data.partition_root.parent
143
+ )
144
+ result = ingest_from_config(config, output_root)
145
+ _print_json(_ingestion_payload(result))
146
+ return 0
147
+
148
+
149
+ def _m8_acquisition_payload(result: M8AcquisitionResult) -> dict[str, Any]:
150
+ return {
151
+ "status": "acquired",
152
+ "scope": "raw_only",
153
+ "output_root": result.output_root,
154
+ "raw_manifest": result.manifest_path,
155
+ "raw_manifest_sha256": result.manifest_sha256,
156
+ "metadata_responses": result.metadata_count,
157
+ "archives": result.archive_count,
158
+ "total_raw_evidence_bytes": result.total_raw_evidence_bytes,
159
+ "csv_members_opened": False,
160
+ "economic_fields_inspected": False,
161
+ }
162
+
163
+
164
+ def _m8_acquisition_failure_payload(result: M8AcquisitionFailureResult) -> dict[str, Any]:
165
+ failed_date = result.failed_date
166
+ return {
167
+ "status": "INSUFFICIENT_DATA",
168
+ "scope": "raw_only",
169
+ "output_root": result.output_root,
170
+ "attempt_dir": result.attempt_dir,
171
+ "failure_manifest": result.attempt_manifest_path,
172
+ "failure_manifest_sha256": result.attempt_manifest_sha256,
173
+ "checksums": result.checksums_path,
174
+ "checksums_sha256": result.checksums_sha256,
175
+ "terminal_marker": result.terminal_path,
176
+ "reason_code": result.reason_code,
177
+ "diagnostic": result.diagnostic,
178
+ "failed_symbol": result.failed_symbol,
179
+ "failed_date": None if failed_date is None else failed_date.isoformat(),
180
+ "failed_role": result.failed_role,
181
+ "completed_steps": result.completed_count,
182
+ "remaining_steps": result.remaining_count,
183
+ "retained_inventory_sha256": result.retained_inventory_sha256,
184
+ "retained_artifacts": result.retained_artifact_count,
185
+ "total_raw_evidence_bytes": result.total_raw_evidence_bytes,
186
+ "csv_members_opened": False,
187
+ "economic_fields_inspected": False,
188
+ }
189
+
190
+
191
+ def _cmd_acquire_m8(args: argparse.Namespace) -> int:
192
+ config = load_m8_config(args.config)
193
+ result = acquire_m8_archives(config, Path(args.output_root).resolve())
194
+ if isinstance(result, M8AcquisitionFailureResult):
195
+ _print_json(_m8_acquisition_failure_payload(result))
196
+ return 1
197
+ _print_json(_m8_acquisition_payload(result))
198
+ return 0
199
+
200
+
201
+ def _synthetic_tables(config: ProjectConfig) -> dict[str, Any]:
202
+ events = config.data.events_per_symbol
203
+ if events is None:
204
+ raise ValueError("synthetic validation requires data.events_per_symbol")
205
+ generated = generate_synthetic_market(
206
+ symbols=config.data.symbols,
207
+ events_per_symbol=events,
208
+ start_ts_ns=datetime_to_ns(config.data.start),
209
+ seed=config.run.seed,
210
+ )
211
+ return {"trades": generated.trades, "book_observations": generated.book_observations}
212
+
213
+
214
+ def _cmd_validate(args: argparse.Namespace) -> int:
215
+ config = load_config(args.config)
216
+ tables = _synthetic_tables(config) if config.data.mode == "synthetic" else None
217
+ summary = validate_configured_input(config, tables=tables)
218
+ _print_json(
219
+ {
220
+ "passed": summary.passed,
221
+ "rows_checked": summary.rows_checked,
222
+ "errors": summary.error_count,
223
+ "warnings": summary.warning_count,
224
+ "reports": [
225
+ {
226
+ "dataset": report.dataset,
227
+ "rows_checked": report.rows_checked,
228
+ "errors": report.error_count,
229
+ "warnings": report.warning_count,
230
+ }
231
+ for report in summary.reports
232
+ ],
233
+ "mutation_policy": "validation did not repair or replace observations",
234
+ }
235
+ )
236
+ return 0 if summary.passed else 1
237
+
238
+
239
+ def _cmd_reproduce(args: argparse.Namespace) -> int:
240
+ config = load_config(args.config)
241
+ output = reproduce(
242
+ config,
243
+ Path(args.run_dir),
244
+ ingestion_manifest_path=args.ingestion_manifest,
245
+ ingestion_manifest_sha256=args.ingestion_manifest_sha256,
246
+ )
247
+ bundle = load_run_bundle(output)
248
+ _print_json(
249
+ {
250
+ "run_dir": output,
251
+ "run_id": bundle.run_id,
252
+ "evidence_tier": bundle.evidence_tier,
253
+ "observed_start_utc": bundle.observed_start_utc,
254
+ "observed_end_utc": bundle.observed_end_utc,
255
+ "status": "complete",
256
+ }
257
+ )
258
+ return 0
259
+
260
+
261
+ def _cmd_reproduce_m8(args: argparse.Namespace) -> int:
262
+ config = load_m8_config(args.config)
263
+ result = reproduce_m8(
264
+ config,
265
+ Path(args.run_dir),
266
+ raw_manifest_path=Path(args.raw_manifest),
267
+ raw_manifest_sha256=str(args.raw_manifest_sha256),
268
+ )
269
+ if result.status == "INSUFFICIENT_DATA":
270
+ _print_json(_m8_run_result_payload(result))
271
+ return 1
272
+ bundle = load_run_bundle(result.path)
273
+ _print_json(
274
+ {
275
+ "run_dir": result.path,
276
+ "run_id": bundle.run_id,
277
+ "evidence_tier": bundle.evidence_tier,
278
+ "observed_start_utc": bundle.observed_start_utc,
279
+ "observed_end_utc": bundle.observed_end_utc,
280
+ "status": result.status,
281
+ "raw_manifest_sha256": result.raw_manifest_sha256,
282
+ "normalized_manifest_sha256": result.normalized_manifest_sha256,
283
+ }
284
+ )
285
+ return 0
286
+
287
+
288
+ def _m8_run_result_payload(result: M8RunResult) -> dict[str, Any]:
289
+ return {
290
+ "run_dir": result.path,
291
+ "status": result.status,
292
+ "raw_manifest_sha256": result.raw_manifest_sha256,
293
+ "normalized_manifest_sha256": result.normalized_manifest_sha256,
294
+ }
295
+
296
+
297
+ def _cmd_verify_m8(args: argparse.Namespace) -> int:
298
+ config = load_m8_config(args.config)
299
+ result = verify_m8_result(
300
+ args.run_dir,
301
+ config,
302
+ raw_manifest_path=args.raw_manifest,
303
+ raw_manifest_sha256=args.raw_manifest_sha256,
304
+ )
305
+ payload = _m8_run_result_payload(result)
306
+ payload.update(
307
+ {
308
+ "integrity": "verified",
309
+ "protected_files": verify_checksums(result.path),
310
+ }
311
+ )
312
+ _print_json(payload)
313
+ return 0
314
+
315
+
316
+ def _external_report_dir(run_root: Path, requested: Path | None) -> Path:
317
+ frozen_root = run_root.resolve()
318
+ output = (
319
+ requested.resolve()
320
+ if requested is not None
321
+ else frozen_root.with_name(f"{frozen_root.name}-reports")
322
+ )
323
+ if output == frozen_root or frozen_root in output.parents:
324
+ raise ValueError("report output directory must be outside the immutable run bundle")
325
+ return output
326
+
327
+
328
+ def _atomic_text(path: Path, content: str) -> None:
329
+ path.parent.mkdir(parents=True, exist_ok=True)
330
+ descriptor, temporary_name = tempfile.mkstemp(
331
+ dir=path.parent,
332
+ prefix=f".{path.name}.",
333
+ suffix=".tmp",
334
+ text=True,
335
+ )
336
+ temporary = Path(temporary_name)
337
+ try:
338
+ with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
339
+ handle.write(content)
340
+ handle.flush()
341
+ os.fsync(handle.fileno())
342
+ os.replace(temporary, path)
343
+ directory = os.open(path.parent, os.O_RDONLY)
344
+ try:
345
+ os.fsync(directory)
346
+ finally:
347
+ os.close(directory)
348
+ except BaseException:
349
+ temporary.unlink(missing_ok=True)
350
+ raise
351
+
352
+
353
+ def _report_mapping(value: object, label: str) -> Mapping[str, Any]:
354
+ if not isinstance(value, Mapping):
355
+ raise ValueError(f"verified M8 {label} is not a JSON object")
356
+ return cast(Mapping[str, Any], value)
357
+
358
+
359
+ def _report_value(value: object) -> str:
360
+ if isinstance(value, (dict, list, tuple)):
361
+ rendered = json.dumps(value, sort_keys=True, separators=(",", ":"))
362
+ elif value is None:
363
+ rendered = "null"
364
+ elif value is True:
365
+ rendered = "true"
366
+ elif value is False:
367
+ rendered = "false"
368
+ else:
369
+ rendered = str(value)
370
+ return " ".join(rendered.replace("`", "'").split())
371
+
372
+
373
+ def _m8_failure_period(failure: Mapping[str, Any]) -> tuple[str, str]:
374
+ dates: list[str] = []
375
+ for key in ("completed_normalizations", "stopped_before"):
376
+ rows = failure.get(key)
377
+ if isinstance(rows, list):
378
+ dates.extend(
379
+ str(row["date"])
380
+ for row in rows
381
+ if isinstance(row, Mapping)
382
+ and isinstance(row.get("date"), str)
383
+ and len(str(row["date"])) == 10
384
+ )
385
+ failed_date = failure.get("failed_date")
386
+ if isinstance(failed_date, str) and len(failed_date) == 10:
387
+ dates.append(failed_date)
388
+ if not dates:
389
+ raise ValueError("verified M8 failure does not declare its study period")
390
+ return min(dates), max(dates)
391
+
392
+
393
+ def _render_m8_insufficient_report(run_root: Path) -> str:
394
+ failure = _report_mapping(read_json(run_root / "failure.json"), "failure record")
395
+ provenance = _report_mapping(read_json(run_root / "provenance.json"), "provenance")
396
+ manifest = _report_mapping(read_json(run_root / "run_manifest.json"), "run manifest")
397
+ research = _report_mapping(manifest.get("research"), "run research section")
398
+ execution = _report_mapping(
399
+ manifest.get("execution_assumptions"),
400
+ "execution-assumptions section",
401
+ )
402
+ git = _report_mapping(provenance.get("git"), "Git identity")
403
+ period_start, period_end = _m8_failure_period(failure)
404
+ completed_symbols = failure.get("selection_completed_symbols")
405
+ evaluated_symbols = failure.get("endpoint_evaluation_completed_symbols")
406
+ heldout_member = failure.get("held_out_member_opened", "not separately recorded")
407
+ return f"""# M8 study result: INSUFFICIENT_DATA
408
+
409
+ > VERIFIED TERMINAL TRADE-ONLY RESEARCH RESULT — NO DATE REPLACEMENT, LIVE TRADING, OR PERFORMANCE CLAIM
410
+
411
+ ## Frozen scope and failure
412
+
413
+ - Observed/attempted archive date span: `{period_start}` through `{period_end}` (UTC daily archives)
414
+ - Failed coordinate: symbol=`{_report_value(failure.get("failed_symbol"))}`, date=`{_report_value(failure.get("failed_date"))}`, role=`{_report_value(failure.get("failed_role"))}`
415
+ - Failure stage: `{_report_value(failure.get("failure_stage"))}`
416
+ - Reason code: `{_report_value(failure.get("reason_code"))}`
417
+ - Diagnostic: `{_report_value(failure.get("reason"))}`
418
+ - Replacement date selected: `{_report_value(failure.get("replacement_date_selected"))}`; reselection performed: `{_report_value(failure.get("reselection_performed"))}`
419
+
420
+ ## Immutable authority
421
+
422
+ - Config semantic SHA-256: `{_report_value(failure.get("config_sha256"))}`
423
+ - Config source SHA-256: `{_report_value(failure.get("config_source_sha256"))}`
424
+ - Raw acquisition manifest SHA-256: `{_report_value(failure.get("raw_acquisition_manifest_sha256"))}`
425
+ - Bundled raw acquisition manifest SHA-256: `{_report_value(failure.get("bundled_raw_acquisition_manifest_sha256"))}`
426
+ - Protocol SHA-256: `{_report_value(failure.get("protocol_sha256"))}`
427
+ - Git commit: `{_report_value(git.get("commit"))}`
428
+ - Git dirty: `{_report_value(git.get("dirty"))}`
429
+ - Source-tree SHA-256: `{_report_value(git.get("source_tree_sha256"))}`
430
+
431
+ ## Terminal analysis states
432
+
433
+ - Candidate selection started: `{_report_value(failure.get("selection_started"))}`; completed symbols: `{_report_value(completed_symbols)}`
434
+ - Aggregate analysis lock committed: `{_report_value(failure.get("aggregate_lock_committed"))}`
435
+ - Held-out member opened: `{_report_value(heldout_member)}`
436
+ - Endpoint evaluation started: `{_report_value(failure.get("endpoint_evaluation_started"))}`; completed: `{_report_value(failure.get("endpoint_evaluation_completed"))}`; completed symbols: `{_report_value(evaluated_symbols)}`
437
+ - Predictions published: `{_report_value(failure.get("predictions_published"))}`; endpoint artifacts published: `{_report_value(failure.get("endpoint_artifacts_published"))}`
438
+ - Research endpoint status: `{_report_value(research.get("endpoint_status"))}`
439
+ - Execution status: `{_report_value(execution.get("status"))}`; fills calculated: `{_report_value(execution.get("fills_calculated"))}`; P&L calculated: `{_report_value(execution.get("pnl_calculated"))}`; capacity calculated: `{_report_value(execution.get("capacity_calculated"))}`
440
+
441
+ This terminal result preserves the frozen calendar and failure evidence. It authorizes no execution, profitability, capacity, statistical-significance, or persistent-alpha claim.
442
+ """
443
+
444
+
445
+ def _cmd_report_m8(args: argparse.Namespace) -> int:
446
+ config = load_m8_config(args.config)
447
+ result = verify_m8_result(
448
+ args.run_dir,
449
+ config,
450
+ raw_manifest_path=args.raw_manifest,
451
+ raw_manifest_sha256=args.raw_manifest_sha256,
452
+ )
453
+ output = _external_report_dir(result.path, args.output_dir)
454
+ if result.status == "COMPLETE":
455
+ bundle = load_run_bundle(result.path)
456
+ paths = write_report_set(bundle, output)
457
+ _print_json(
458
+ {
459
+ **_m8_run_result_payload(result),
460
+ "output_dir": output,
461
+ "reports_regenerated": True,
462
+ **asdict(paths),
463
+ }
464
+ )
465
+ else:
466
+ rendered = _render_m8_insufficient_report(result.path)
467
+ confirmed = verify_m8_result(
468
+ args.run_dir,
469
+ config,
470
+ raw_manifest_path=args.raw_manifest,
471
+ raw_manifest_sha256=args.raw_manifest_sha256,
472
+ )
473
+ if (
474
+ confirmed.status != "INSUFFICIENT_DATA"
475
+ or confirmed.path.resolve() != result.path.resolve()
476
+ or confirmed.raw_manifest_sha256 != result.raw_manifest_sha256
477
+ or confirmed.normalized_manifest_sha256 is not None
478
+ ):
479
+ raise ValueError("M8 failure authority changed while rendering its report")
480
+ failure_report = output / "insufficient_data.md"
481
+ _atomic_text(failure_report, rendered)
482
+ _print_json(
483
+ {
484
+ **_m8_run_result_payload(result),
485
+ "output_dir": output,
486
+ "report": failure_report,
487
+ "report_sha256": sha256_file(failure_report),
488
+ "reports_regenerated": True,
489
+ "source_bundle_modified": False,
490
+ }
491
+ )
492
+ return 0
493
+
494
+
495
+ def _lowercase_sha256(value: str) -> str:
496
+ if len(value) != 64 or any(character not in "0123456789abcdef" for character in value):
497
+ raise argparse.ArgumentTypeError("must be a 64-character lowercase SHA-256 digest")
498
+ return value
499
+
500
+
501
+ def _cmd_verify(args: argparse.Namespace) -> int:
502
+ bundle = load_run_bundle(args.run_dir)
503
+ protected = verify_checksums(args.run_dir)
504
+ _print_json(
505
+ {
506
+ "run_dir": bundle.root,
507
+ "run_id": bundle.run_id,
508
+ "evidence_tier": bundle.evidence_tier,
509
+ "protected_files": protected,
510
+ "integrity": "verified",
511
+ }
512
+ )
513
+ return 0
514
+
515
+
516
+ def _cmd_report(args: argparse.Namespace) -> int:
517
+ bundle = load_run_bundle(args.run_dir)
518
+ output = (
519
+ Path(args.output_dir).resolve()
520
+ if args.output_dir
521
+ else bundle.root.with_name(f"{bundle.root.name}-reports")
522
+ )
523
+ paths = write_report_set(bundle, output)
524
+ _print_json({"run_id": bundle.run_id, "output_dir": output, **asdict(paths)})
525
+ return 0
526
+
527
+
528
+ _LIVE_BATCH_ROWS = 1_024
529
+ _MAX_LIVE_RAW_MESSAGE_BYTES = 1 * 1024 * 1024
530
+ _LIVE_BATCH_ESTIMATED_BYTES = 16 * 1024 * 1024
531
+ _VARIABLE_RECORD_OVERHEAD_FACTOR = 8
532
+
533
+
534
+ @dataclass(frozen=True, slots=True)
535
+ class DepthCaptureResult:
536
+ symbol: str
537
+ messages: int
538
+ continuity_epochs: int
539
+ reconstruction_status: Literal["LIVE", "GAPPED", "INVALID"]
540
+ book_observations: int
541
+ sequence_gaps: int
542
+ stale_events: int
543
+ excluded_messages: int
544
+ final_update_id: int
545
+ quality_errors: int
546
+ quality_warnings: int
547
+ raw_path: Path
548
+ raw_manifest_path: Path
549
+ raw_manifest_sha256: str
550
+ summary_path: Path
551
+ completion_reason: str
552
+ requested_duration_seconds: float | None
553
+ elapsed_monotonic_seconds: float
554
+ receipt_coverage_seconds: float
555
+ max_continuity_epoch_seconds: float
556
+
557
+
558
+ @dataclass(slots=True)
559
+ class _DepthCaptureStop:
560
+ reason: str = "not_started"
561
+ elapsed_monotonic_seconds: float = 0.0
562
+
563
+
564
+ @dataclass(slots=True)
565
+ class _DepthEpochCoverage:
566
+ continuity_id: str
567
+ snapshot_id: str
568
+ first_received_ns: int
569
+ last_received_ns: int
570
+ messages: int = 0
571
+ book_observations: int = 0
572
+ excluded_messages: int = 0
573
+ sequence_gaps: int = 0
574
+ reconstruction_status: Literal["LIVE", "GAPPED", "INVALID"] = "LIVE"
575
+ final_update_id: int = 0
576
+
577
+ @property
578
+ def duration_seconds(self) -> float:
579
+ return max(0.0, (self.last_received_ns - self.first_received_ns) / 1_000_000_000.0)
580
+
581
+ def to_dict(self) -> dict[str, object]:
582
+ return {
583
+ "continuity_id": self.continuity_id,
584
+ "snapshot_id": self.snapshot_id,
585
+ "first_received_ns": self.first_received_ns,
586
+ "last_received_ns": self.last_received_ns,
587
+ "duration_seconds": self.duration_seconds,
588
+ "messages": self.messages,
589
+ "book_observations": self.book_observations,
590
+ "excluded_messages": self.excluded_messages,
591
+ "sequence_gaps": self.sequence_gaps,
592
+ "reconstruction_status": self.reconstruction_status,
593
+ "final_update_id": self.final_update_id,
594
+ }
595
+
596
+
597
+ async def _bounded_depth_items(
598
+ collector: BinanceLiveDepthCollector,
599
+ *,
600
+ max_messages: int,
601
+ duration_seconds: float | None,
602
+ stop: _DepthCaptureStop,
603
+ ) -> AsyncIterator[CapturedDepth]:
604
+ """Yield a live stream until its safety cap or a graceful duration deadline."""
605
+
606
+ started = time.monotonic()
607
+ yielded = 0
608
+ iterator = collector.stream(max_messages=max_messages).__aiter__()
609
+ try:
610
+ if duration_seconds is None:
611
+ async for item in iterator:
612
+ yielded += 1
613
+ yield item
614
+ stop.reason = "message_limit" if yielded == max_messages else "stream_ended_early"
615
+ return
616
+
617
+ deadline = started + duration_seconds
618
+ while True:
619
+ remaining = deadline - time.monotonic()
620
+ if remaining <= 0:
621
+ stop.reason = "duration_elapsed"
622
+ return
623
+ try:
624
+ item = await asyncio.wait_for(anext(iterator), timeout=remaining)
625
+ except TimeoutError:
626
+ stop.reason = "duration_elapsed"
627
+ return
628
+ except StopAsyncIteration:
629
+ stop.reason = (
630
+ "message_safety_ceiling" if yielded == max_messages else "stream_ended_early"
631
+ )
632
+ return
633
+ yielded += 1
634
+ yield item
635
+ finally:
636
+ stop.elapsed_monotonic_seconds = max(0.0, time.monotonic() - started)
637
+ with suppress(BaseException):
638
+ closer = getattr(iterator, "aclose", None)
639
+ if callable(closer):
640
+ await closer()
641
+
642
+
643
+ @dataclass(frozen=True, slots=True)
644
+ class _PublishedRawCapture:
645
+ path: Path
646
+ sha256: str
647
+ manifest_path: Path
648
+ manifest_sha256: str
649
+
650
+
651
+ class _ArrowBatchSpool:
652
+ """Bounded record buffer backed by a temporary Arrow IPC stream."""
653
+
654
+ def __init__(
655
+ self,
656
+ *,
657
+ root: Path,
658
+ schema_name: str,
659
+ batch_rows: int,
660
+ max_buffer_bytes: int,
661
+ on_batch: Callable[[pa.RecordBatch], None] | None = None,
662
+ ) -> None:
663
+ if batch_rows < 1:
664
+ raise ValueError("batch_rows must be positive")
665
+ if max_buffer_bytes < 1:
666
+ raise ValueError("max_buffer_bytes must be positive")
667
+ self.schema_name = schema_name
668
+ self.batch_rows = batch_rows
669
+ self.max_buffer_bytes = max_buffer_bytes
670
+ self.path = root / f"{schema_name}.arrow"
671
+ self._handle = self.path.open("wb")
672
+ self._writer = pa.ipc.new_stream(self._handle, get_schema(schema_name))
673
+ self._on_batch = on_batch
674
+ self._records: list[Mapping[str, object]] = []
675
+ self.rows = 0
676
+ self.max_buffered_rows = 0
677
+ self.max_buffered_estimated_bytes = 0
678
+ self._buffered_estimated_bytes = 0
679
+ self._closed = False
680
+
681
+ def append(self, record: Mapping[str, object], *, estimated_bytes: int) -> None:
682
+ if self._closed:
683
+ raise RuntimeError("cannot append to a closed Arrow spool")
684
+ if estimated_bytes < 1:
685
+ raise ValueError("estimated_bytes must be positive")
686
+ if estimated_bytes > self.max_buffer_bytes:
687
+ raise RuntimeError(f"one {self.schema_name} record exceeds the bounded batch estimate")
688
+ if (
689
+ self._records
690
+ and self._buffered_estimated_bytes + estimated_bytes > self.max_buffer_bytes
691
+ ):
692
+ self._flush()
693
+ self._records.append(record)
694
+ self._buffered_estimated_bytes += estimated_bytes
695
+ self.max_buffered_rows = max(self.max_buffered_rows, len(self._records))
696
+ self.max_buffered_estimated_bytes = max(
697
+ self.max_buffered_estimated_bytes,
698
+ self._buffered_estimated_bytes,
699
+ )
700
+ if len(self._records) >= self.batch_rows:
701
+ self._flush()
702
+
703
+ def _flush(self) -> None:
704
+ if not self._records:
705
+ return
706
+ table = table_from_records(self.schema_name, self._records)
707
+ batches = table.to_batches(max_chunksize=self.batch_rows)
708
+ if len(batches) != 1 or batches[0].num_rows > self.batch_rows:
709
+ raise RuntimeError(f"failed to construct one bounded {self.schema_name} batch")
710
+ batch = batches[0]
711
+ if self._on_batch is not None:
712
+ self._on_batch(batch)
713
+ self._writer.write_batch(batch)
714
+ self.rows += batch.num_rows
715
+ self._records.clear()
716
+ self._buffered_estimated_bytes = 0
717
+
718
+ def close(self) -> None:
719
+ if self._closed:
720
+ return
721
+ self._flush()
722
+ self._writer.close()
723
+ if not self._handle.closed:
724
+ self._handle.flush()
725
+ os.fsync(self._handle.fileno())
726
+ self._handle.close()
727
+ self._closed = True
728
+
729
+ def iter_batches(self) -> Iterator[pa.RecordBatch]:
730
+ if not self._closed:
731
+ raise RuntimeError("Arrow spool must be closed before it can be read")
732
+ with self.path.open("rb") as handle:
733
+ reader = pa.ipc.open_stream(handle)
734
+ for batch in reader:
735
+ if batch.num_rows > self.batch_rows:
736
+ raise RuntimeError(
737
+ f"spooled {self.schema_name} batch exceeds {self.batch_rows} rows"
738
+ )
739
+ yield batch
740
+
741
+
742
+ class _RawMessageSpool:
743
+ """Incrementally persist an exact, typed live-capture journal."""
744
+
745
+ def __init__(self, *, root: Path, symbol: str, source_uri: str) -> None:
746
+ self.root = root
747
+ self.symbol = symbol
748
+ self.source_uri = source_uri
749
+ self.directory = root / "raw" / "binance_spot" / "depth_stream" / symbol
750
+ self.directory.mkdir(parents=True, exist_ok=True)
751
+ descriptor, temporary_name = tempfile.mkstemp(
752
+ dir=self.directory,
753
+ prefix=".capture-",
754
+ suffix=".ndjson.tmp",
755
+ text=True,
756
+ )
757
+ self._temporary_path = Path(temporary_name)
758
+ self._handle = os.fdopen(descriptor, "w", encoding="utf-8", newline="\n")
759
+ self.messages = 0
760
+ self.snapshot_anchors = 0
761
+ self.first_received_ns: int | None = None
762
+ self.last_received_ns: int | None = None
763
+ self._closed = False
764
+ self.published_path: Path | None = None
765
+ self._last_frame_identity: tuple[str, int, int, str] | None = None
766
+
767
+ @property
768
+ def evidence_path(self) -> Path:
769
+ """Return the durable path, or the fsynced temporary path after publish failure."""
770
+ return self.published_path or self._temporary_path
771
+
772
+ def _write_event(self, event: Mapping[str, object]) -> None:
773
+ if self._closed:
774
+ raise RuntimeError("cannot append to a closed raw capture")
775
+ json.dump(event, self._handle, sort_keys=True, separators=(",", ":"))
776
+ self._handle.write("\n")
777
+
778
+ def append_frame(self, frame: RawDepthFrame) -> int:
779
+ """Journal one exact frame before any UTF-8 or JSON parsing."""
780
+ payload_size = len(frame.payload)
781
+ payload_sha256 = hashlib.sha256(frame.payload).hexdigest()
782
+ self._write_event(
783
+ {
784
+ "capture_seq": frame.capture_seq,
785
+ "continuity_id": frame.continuity_id,
786
+ "event_kind": "websocket_frame",
787
+ "payload_base64": base64.b64encode(frame.payload).decode("ascii"),
788
+ "payload_bytes": payload_size,
789
+ "payload_sha256": payload_sha256,
790
+ "received_ts_ns": frame.received_ts_ns,
791
+ "websocket_message_type": "text" if frame.was_text else "binary",
792
+ }
793
+ )
794
+ self.messages += 1
795
+ if self.first_received_ns is None:
796
+ self.first_received_ns = frame.received_ts_ns
797
+ self.last_received_ns = frame.received_ts_ns
798
+ self._last_frame_identity = (
799
+ frame.continuity_id,
800
+ frame.capture_seq,
801
+ frame.received_ts_ns,
802
+ payload_sha256,
803
+ )
804
+ # The oversize frame is intentionally journaled before capture fails.
805
+ if payload_size > _MAX_LIVE_RAW_MESSAGE_BYTES:
806
+ raise RuntimeError(
807
+ f"live depth message exceeds {_MAX_LIVE_RAW_MESSAGE_BYTES} raw bytes"
808
+ )
809
+ return payload_size
810
+
811
+ def append_captured(self, item: CapturedDepth) -> int:
812
+ """Verify callback lineage, with a fallback for injected legacy collectors."""
813
+ received_ts_ns = item.delta.received_ts_ns
814
+ capture_seq = item.delta.capture_seq
815
+ if received_ts_ns is None or capture_seq is None:
816
+ raise RuntimeError("captured depth messages require receipt time and capture sequence")
817
+ payload = item.raw_payload.encode("utf-8")
818
+ payload_sha256 = hashlib.sha256(payload).hexdigest()
819
+ identity = (
820
+ item.delta.continuity_id,
821
+ capture_seq,
822
+ received_ts_ns,
823
+ payload_sha256,
824
+ )
825
+ if self._last_frame_identity != identity:
826
+ self.append_frame(
827
+ RawDepthFrame(
828
+ payload=payload,
829
+ was_text=True,
830
+ received_ts_ns=received_ts_ns,
831
+ capture_seq=capture_seq,
832
+ continuity_id=item.delta.continuity_id,
833
+ )
834
+ )
835
+ if item.delta.source_artifact_id != payload_sha256:
836
+ raise RuntimeError("normalized depth delta is not bound to its raw frame SHA-256")
837
+ return len(payload)
838
+
839
+ def append_snapshot(self, snapshot: BookSnapshot) -> None:
840
+ """Bind one REST snapshot raw artifact into the capture journal."""
841
+ raw_path = (
842
+ self.root
843
+ / "raw"
844
+ / "binance_spot"
845
+ / "depth_snapshots"
846
+ / snapshot.symbol
847
+ / f"{snapshot.source_artifact_id}.json"
848
+ )
849
+ if not raw_path.is_file() or sha256_file(raw_path) != snapshot.source_artifact_id:
850
+ raise RuntimeError("book snapshot is not bound to its preserved raw response")
851
+ manifest_path: Path | None = None
852
+ for candidate in raw_path.parent.glob(f"{raw_path.name}.manifest-*.json"):
853
+ payload = read_json(candidate)
854
+ if (
855
+ isinstance(payload, dict)
856
+ and payload.get("path") == raw_path.name
857
+ and isinstance(payload.get("checksum"), dict)
858
+ and payload["checksum"].get("value") == snapshot.source_artifact_id
859
+ and (manifest_path is None or candidate.name > manifest_path.name)
860
+ ):
861
+ manifest_path = candidate
862
+ if manifest_path is None:
863
+ raise RuntimeError("book snapshot raw response has no valid source manifest")
864
+ self._write_event(
865
+ {
866
+ "continuity_id": snapshot.continuity_id,
867
+ "event_kind": "rest_snapshot_anchor",
868
+ "last_update_id": snapshot.last_update_id,
869
+ "raw_manifest_path": str(manifest_path),
870
+ "raw_manifest_sha256": sha256_file(manifest_path),
871
+ "raw_path": str(raw_path),
872
+ "raw_sha256": snapshot.source_artifact_id,
873
+ "received_ts_ns": snapshot.received_ts_ns,
874
+ "snapshot_id": snapshot.snapshot_id,
875
+ }
876
+ )
877
+ self.snapshot_anchors += 1
878
+
879
+ def _close(self) -> None:
880
+ if self._closed:
881
+ return
882
+ self._handle.flush()
883
+ os.fsync(self._handle.fileno())
884
+ self._handle.close()
885
+ self._closed = True
886
+
887
+ def publish(
888
+ self,
889
+ *,
890
+ status: str,
891
+ error: BaseException | None = None,
892
+ ) -> _PublishedRawCapture:
893
+ self._close()
894
+ if self.published_path is not None:
895
+ destination = self.published_path
896
+ digest = sha256_file(destination)
897
+ else:
898
+ digest = sha256_file(self._temporary_path)
899
+ prefix = "capture" if status == "raw_capture_complete" else "capture-failed"
900
+ destination = self.directory / f"{prefix}-{digest}.ndjson"
901
+ if destination.exists():
902
+ if sha256_file(destination) != digest:
903
+ raise RuntimeError(f"raw depth capture collision at {destination}")
904
+ self._temporary_path.unlink(missing_ok=True)
905
+ else:
906
+ os.replace(self._temporary_path, destination)
907
+ self.published_path = destination
908
+ response_headers = {
909
+ "x-local-capture-status": status,
910
+ "x-local-journal-format": "typed-base64-frames-v1",
911
+ "x-local-message-count": str(self.messages),
912
+ "x-local-snapshot-anchor-count": str(self.snapshot_anchors),
913
+ }
914
+ if error is not None:
915
+ response_headers["x-local-error-type"] = type(error).__name__
916
+ response_headers["x-local-error"] = str(error)[:512]
917
+ manifest_path, manifest_sha = write_source_manifest(
918
+ destination,
919
+ source="binance_spot_public_live_capture_journal",
920
+ source_uri=self.source_uri,
921
+ downloaded_at_utc=utc_now_iso(),
922
+ requested_start_ns=self.first_received_ns,
923
+ requested_end_ns=(
924
+ self.last_received_ns + 1 if self.last_received_ns is not None else None
925
+ ),
926
+ response_headers=response_headers,
927
+ )
928
+ return _PublishedRawCapture(
929
+ path=destination,
930
+ sha256=digest,
931
+ manifest_path=manifest_path,
932
+ manifest_sha256=manifest_sha,
933
+ )
934
+
935
+ def close_without_deleting(self) -> None:
936
+ self._close()
937
+
938
+
939
+ def _status_max(
940
+ current: Literal["LIVE", "GAPPED", "INVALID"],
941
+ observed: Literal["LIVE", "GAPPED", "INVALID"],
942
+ ) -> Literal["LIVE", "GAPPED", "INVALID"]:
943
+ rank = {"LIVE": 0, "GAPPED": 1, "INVALID": 2}
944
+ return observed if rank[observed] > rank[current] else current
945
+
946
+
947
+ def _failure_record(
948
+ *,
949
+ output_root: Path,
950
+ capture_id: str,
951
+ symbol: str,
952
+ raw_spool: _RawMessageSpool,
953
+ raw_evidence: _PublishedRawCapture | None,
954
+ error: BaseException,
955
+ ) -> None:
956
+ write_json(
957
+ output_root / "quality" / f"live_depth_capture.{capture_id}.failed.json",
958
+ {
959
+ "generated_at_utc": utc_now_iso(),
960
+ "capture_id": capture_id,
961
+ "capture_status": "FAILED",
962
+ "symbol": symbol,
963
+ "messages_preserved": raw_spool.messages,
964
+ "raw_path": str(
965
+ raw_evidence.path if raw_evidence is not None else raw_spool.evidence_path
966
+ ),
967
+ "raw_manifest": (str(raw_evidence.manifest_path) if raw_evidence is not None else None),
968
+ "error_type": type(error).__name__,
969
+ "error": str(error),
970
+ "completion_manifest_published": False,
971
+ },
972
+ )
973
+
974
+
975
+ async def _capture_depth(
976
+ *,
977
+ symbol: str,
978
+ max_messages: int,
979
+ output_root: Path,
980
+ duration_seconds: float | None = None,
981
+ ) -> DepthCaptureResult:
982
+ if max_messages < 1:
983
+ raise ValueError("max_messages must be positive")
984
+ if duration_seconds is not None and duration_seconds <= 0:
985
+ raise ValueError("duration_seconds must be positive when supplied")
986
+ output_root.mkdir(parents=True, exist_ok=True)
987
+ capture_id = f"{symbol.lower()}-{time.time_ns()}"
988
+ client = BinancePublicClient()
989
+ metadata = client.fetch_exchange_info(symbol=symbol, raw_root=output_root / "raw")
990
+ raw_spool_holder: list[_RawMessageSpool] = []
991
+
992
+ def preserve_raw_frame(frame: RawDepthFrame) -> None:
993
+ if not raw_spool_holder: # pragma: no cover - collector cannot run during construction
994
+ raise RuntimeError("raw capture journal is not initialized")
995
+ raw_spool_holder[0].append_frame(frame)
996
+
997
+ collector = BinanceLiveDepthCollector(
998
+ symbols=(symbol,),
999
+ tick_size=metadata.tick_size,
1000
+ lot_size=metadata.lot_size,
1001
+ on_raw_frame=preserve_raw_frame,
1002
+ )
1003
+ raw_spool = _RawMessageSpool(root=output_root, symbol=symbol, source_uri=collector.url)
1004
+ raw_spool_holder.append(raw_spool)
1005
+ raw_evidence: _PublishedRawCapture | None = None
1006
+ delta_validator = IncrementalQualityValidator(
1007
+ "depth_deltas",
1008
+ row_chunk_size=_LIVE_BATCH_ROWS,
1009
+ )
1010
+ observation_validator = IncrementalQualityValidator(
1011
+ "book_observations",
1012
+ row_chunk_size=_LIVE_BATCH_ROWS,
1013
+ )
1014
+ validators_finished = False
1015
+ with tempfile.TemporaryDirectory(
1016
+ dir=output_root,
1017
+ prefix=f".{capture_id}.spool-",
1018
+ ) as temporary_root_name:
1019
+ temporary_root = Path(temporary_root_name)
1020
+ spools = {
1021
+ "book_snapshots": _ArrowBatchSpool(
1022
+ root=temporary_root,
1023
+ schema_name="book_snapshots",
1024
+ batch_rows=_LIVE_BATCH_ROWS,
1025
+ max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES,
1026
+ ),
1027
+ "depth_deltas": _ArrowBatchSpool(
1028
+ root=temporary_root,
1029
+ schema_name="depth_deltas",
1030
+ batch_rows=_LIVE_BATCH_ROWS,
1031
+ max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES,
1032
+ on_batch=delta_validator.update,
1033
+ ),
1034
+ "book_observations": _ArrowBatchSpool(
1035
+ root=temporary_root,
1036
+ schema_name="book_observations",
1037
+ batch_rows=_LIVE_BATCH_ROWS,
1038
+ max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES,
1039
+ on_batch=observation_validator.update,
1040
+ ),
1041
+ "sequence_gaps": _ArrowBatchSpool(
1042
+ root=temporary_root,
1043
+ schema_name="sequence_gaps",
1044
+ batch_rows=_LIVE_BATCH_ROWS,
1045
+ max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES,
1046
+ ),
1047
+ }
1048
+ current_continuity_id: str | None = None
1049
+ reconstructor: IncrementalBookReconstructor | None = None
1050
+ continuity_epochs = 0
1051
+ status: Literal["LIVE", "GAPPED", "INVALID"] = "LIVE"
1052
+ stale_events = 0
1053
+ excluded_messages = 0
1054
+ final_update_id = 0
1055
+ capture_stop = _DepthCaptureStop()
1056
+ epoch_coverage: list[_DepthEpochCoverage] = []
1057
+ current_epoch_coverage: _DepthEpochCoverage | None = None
1058
+ try:
1059
+ async for item in _bounded_depth_items(
1060
+ collector,
1061
+ max_messages=max_messages,
1062
+ duration_seconds=duration_seconds,
1063
+ stop=capture_stop,
1064
+ ):
1065
+ raw_message_bytes = raw_spool.append_captured(item)
1066
+ if item.delta.continuity_id != current_continuity_id:
1067
+ snapshot = client.fetch_depth_snapshot(
1068
+ symbol=symbol,
1069
+ raw_root=output_root / "raw",
1070
+ continuity_id=item.delta.continuity_id,
1071
+ tick_size=metadata.tick_size,
1072
+ lot_size=metadata.lot_size,
1073
+ )
1074
+ raw_spool.append_snapshot(snapshot)
1075
+ snapshot_estimated_bytes = max(
1076
+ 4_096,
1077
+ 128 * (len(snapshot.bids) + len(snapshot.asks)),
1078
+ )
1079
+ spools["book_snapshots"].append(
1080
+ snapshot.to_record(),
1081
+ estimated_bytes=snapshot_estimated_bytes,
1082
+ )
1083
+ reconstructor = IncrementalBookReconstructor(snapshot)
1084
+ current_continuity_id = item.delta.continuity_id
1085
+ continuity_epochs += 1
1086
+ received_ts_ns = item.delta.received_ts_ns
1087
+ if received_ts_ns is None: # pragma: no cover - append_captured validates
1088
+ raise RuntimeError("live depth delta has no receipt timestamp")
1089
+ current_epoch_coverage = _DepthEpochCoverage(
1090
+ continuity_id=item.delta.continuity_id,
1091
+ snapshot_id=snapshot.snapshot_id,
1092
+ first_received_ns=received_ts_ns,
1093
+ last_received_ns=received_ts_ns,
1094
+ )
1095
+ epoch_coverage.append(current_epoch_coverage)
1096
+ if reconstructor is None: # pragma: no cover - guarded by epoch creation
1097
+ raise RuntimeError("live depth epoch has no reconstructor")
1098
+ if current_epoch_coverage is None: # pragma: no cover - guarded by epoch creation
1099
+ raise RuntimeError("live depth epoch has no coverage tracker")
1100
+ spools["depth_deltas"].append(
1101
+ item.delta.to_record(),
1102
+ estimated_bytes=max(
1103
+ 4_096,
1104
+ raw_message_bytes * _VARIABLE_RECORD_OVERHEAD_FACTOR,
1105
+ ),
1106
+ )
1107
+ step = reconstructor.update(item.delta)
1108
+ if step.observation is not None:
1109
+ spools["book_observations"].append(
1110
+ step.observation,
1111
+ estimated_bytes=4_096,
1112
+ )
1113
+ else:
1114
+ excluded_messages += 1
1115
+ if step.gap is not None:
1116
+ spools["sequence_gaps"].append(
1117
+ step.gap.to_record(),
1118
+ estimated_bytes=2_048,
1119
+ )
1120
+ if step.outcome == "STALE":
1121
+ stale_events += 1
1122
+ status = _status_max(status, reconstructor.status)
1123
+ final_update_id = reconstructor.final_update_id
1124
+ received_ts_ns = item.delta.received_ts_ns
1125
+ if received_ts_ns is None: # pragma: no cover - append_captured validates
1126
+ raise RuntimeError("live depth delta has no receipt timestamp")
1127
+ current_epoch_coverage.last_received_ns = received_ts_ns
1128
+ current_epoch_coverage.messages += 1
1129
+ current_epoch_coverage.book_observations += int(step.observation is not None)
1130
+ current_epoch_coverage.excluded_messages += int(step.observation is None)
1131
+ current_epoch_coverage.sequence_gaps += int(step.gap is not None)
1132
+ current_epoch_coverage.reconstruction_status = reconstructor.status
1133
+ current_epoch_coverage.final_update_id = reconstructor.final_update_id
1134
+
1135
+ if duration_seconds is None:
1136
+ if raw_spool.messages != max_messages or capture_stop.reason != "message_limit":
1137
+ raise RuntimeError(
1138
+ f"live depth stream ended after {raw_spool.messages} of "
1139
+ f"{max_messages} requested messages"
1140
+ )
1141
+ else:
1142
+ if capture_stop.reason == "message_safety_ceiling":
1143
+ raise RuntimeError(
1144
+ "live depth message safety ceiling was reached before the requested "
1145
+ "capture duration elapsed"
1146
+ )
1147
+ if capture_stop.reason != "duration_elapsed":
1148
+ raise RuntimeError(
1149
+ "live depth stream ended before the requested capture duration "
1150
+ f"({capture_stop.reason})"
1151
+ )
1152
+ if raw_spool.messages == 0:
1153
+ raise RuntimeError("duration-bounded live depth capture received no messages")
1154
+ if raw_spool.snapshot_anchors != continuity_epochs:
1155
+ raise RuntimeError("not every continuity epoch has a raw snapshot anchor")
1156
+ for spool in spools.values():
1157
+ spool.close()
1158
+ if spools["depth_deltas"].rows != raw_spool.messages:
1159
+ raise RuntimeError("captured and normalized depth-message counts diverged")
1160
+ if spools["book_observations"].rows + excluded_messages != raw_spool.messages:
1161
+ raise RuntimeError("not every normalized depth message has an explicit outcome")
1162
+ delta_quality = delta_validator.finish()
1163
+ observation_quality = observation_validator.finish()
1164
+ validators_finished = True
1165
+ raw_evidence = raw_spool.publish(status="raw_capture_complete")
1166
+
1167
+ normalized_root = output_root / "normalized" / "captures" / capture_id
1168
+ time_columns = {
1169
+ "book_snapshots": "received_ts_ns",
1170
+ "depth_deltas": "event_ts_ns",
1171
+ "book_observations": "event_ts_ns",
1172
+ "sequence_gaps": "detected_ts_ns",
1173
+ }
1174
+ dataset_manifests: dict[str, dict[str, object]] = {}
1175
+ for schema_name, spool in spools.items():
1176
+ stored = write_capture_parquet(
1177
+ spool.iter_batches(),
1178
+ root=normalized_root,
1179
+ dataset=schema_name,
1180
+ schema_name=schema_name,
1181
+ venue="binance_spot",
1182
+ symbol=symbol,
1183
+ capture_id=capture_id,
1184
+ source="binance_spot_public_live_capture_journal",
1185
+ source_uri=str(raw_evidence.path),
1186
+ source_checksum_sha256=raw_evidence.sha256,
1187
+ requested_start_ns=raw_spool.first_received_ns,
1188
+ requested_end_ns=(
1189
+ raw_spool.last_received_ns + 1
1190
+ if raw_spool.last_received_ns is not None
1191
+ else None
1192
+ ),
1193
+ time_column=time_columns[schema_name],
1194
+ max_input_batch_rows=_LIVE_BATCH_ROWS,
1195
+ )
1196
+ if stored.rows != spool.rows:
1197
+ raise RuntimeError(
1198
+ f"stored {schema_name} row count does not match its verified spool"
1199
+ )
1200
+ dataset_manifests[schema_name] = {
1201
+ "data_path": str(stored.data_path) if stored.data_path is not None else None,
1202
+ "data_sha256": stored.data_sha256,
1203
+ "manifest_path": str(stored.manifest_path),
1204
+ "manifest_sha256": stored.manifest_sha256,
1205
+ "rows": stored.rows,
1206
+ }
1207
+
1208
+ quality_reports: tuple[ValidationReport, ...] = (
1209
+ delta_quality,
1210
+ observation_quality,
1211
+ )
1212
+ quality_errors = sum(report.error_count for report in quality_reports)
1213
+ quality_warnings = sum(report.warning_count for report in quality_reports)
1214
+ quality_root = output_root / "quality"
1215
+ quality_root.mkdir(parents=True, exist_ok=True)
1216
+ quality_report_paths: dict[str, str] = {}
1217
+ for report in quality_reports:
1218
+ report_path = quality_root / f"live_{report.dataset}.{capture_id}.validation.json"
1219
+ report.write_json(report_path)
1220
+ quality_report_paths[report.dataset] = str(report_path)
1221
+ summary_path = quality_root / f"live_depth_capture.{capture_id}.summary.json"
1222
+ receipt_coverage_seconds = (
1223
+ (raw_spool.last_received_ns - raw_spool.first_received_ns) / 1_000_000_000.0
1224
+ if raw_spool.first_received_ns is not None
1225
+ and raw_spool.last_received_ns is not None
1226
+ else 0.0
1227
+ )
1228
+ max_continuity_epoch_seconds = max(
1229
+ (epoch.duration_seconds for epoch in epoch_coverage),
1230
+ default=0.0,
1231
+ )
1232
+ summary_payload = {
1233
+ "generated_at_utc": utc_now_iso(),
1234
+ "capture_id": capture_id,
1235
+ "capture_status": "COMPLETE",
1236
+ "messages": raw_spool.messages,
1237
+ "continuity_epochs": continuity_epochs,
1238
+ "normalized_messages": spools["depth_deltas"].rows,
1239
+ "book_observations": spools["book_observations"].rows,
1240
+ "sequence_gaps": spools["sequence_gaps"].rows,
1241
+ "stale_events": stale_events,
1242
+ "excluded_messages": excluded_messages,
1243
+ "reconstruction_status": status,
1244
+ "quality_errors": quality_errors,
1245
+ "quality_warnings": quality_warnings,
1246
+ "completion_reason": capture_stop.reason,
1247
+ "requested_duration_seconds": duration_seconds,
1248
+ "message_safety_ceiling": max_messages,
1249
+ "elapsed_monotonic_seconds": capture_stop.elapsed_monotonic_seconds,
1250
+ "receipt_coverage_seconds": receipt_coverage_seconds,
1251
+ "continuity_epoch_coverage": [epoch.to_dict() for epoch in epoch_coverage],
1252
+ "max_continuity_epoch_seconds": max_continuity_epoch_seconds,
1253
+ "quality_reports": quality_report_paths,
1254
+ "raw_path": str(raw_evidence.path),
1255
+ "raw_manifest": str(raw_evidence.manifest_path),
1256
+ "raw_manifest_sha256": raw_evidence.manifest_sha256,
1257
+ "normalized_dataset_manifests": dataset_manifests,
1258
+ "max_buffered_rows_per_dataset": {
1259
+ name: spool.max_buffered_rows for name, spool in spools.items()
1260
+ },
1261
+ "max_buffered_estimated_bytes_per_dataset": {
1262
+ name: spool.max_buffered_estimated_bytes for name, spool in spools.items()
1263
+ },
1264
+ "policy": (
1265
+ "every continuity transition receives a fresh snapshot; every captured "
1266
+ "delta is normalized, and non-observed deltas are counted or gap-audited"
1267
+ ),
1268
+ }
1269
+ # The capture-ID-specific completion marker is authoritative and published last.
1270
+ write_json(summary_path, summary_payload)
1271
+ with suppress(BaseException):
1272
+ write_json(
1273
+ quality_root / "live_depth_capture.summary.json",
1274
+ {
1275
+ **summary_payload,
1276
+ "capture_status": "LATEST_POINTER",
1277
+ "latest_capture_status": summary_payload["capture_status"],
1278
+ "authoritative_summary_path": str(summary_path),
1279
+ "authoritative_summary_sha256": sha256_file(summary_path),
1280
+ },
1281
+ )
1282
+ return DepthCaptureResult(
1283
+ symbol=symbol,
1284
+ messages=raw_spool.messages,
1285
+ continuity_epochs=continuity_epochs,
1286
+ reconstruction_status=status,
1287
+ book_observations=spools["book_observations"].rows,
1288
+ sequence_gaps=spools["sequence_gaps"].rows,
1289
+ stale_events=stale_events,
1290
+ excluded_messages=excluded_messages,
1291
+ final_update_id=final_update_id,
1292
+ quality_errors=quality_errors,
1293
+ quality_warnings=quality_warnings,
1294
+ raw_path=raw_evidence.path,
1295
+ raw_manifest_path=raw_evidence.manifest_path,
1296
+ raw_manifest_sha256=raw_evidence.manifest_sha256,
1297
+ summary_path=summary_path,
1298
+ completion_reason=capture_stop.reason,
1299
+ requested_duration_seconds=duration_seconds,
1300
+ elapsed_monotonic_seconds=capture_stop.elapsed_monotonic_seconds,
1301
+ receipt_coverage_seconds=receipt_coverage_seconds,
1302
+ max_continuity_epoch_seconds=max_continuity_epoch_seconds,
1303
+ )
1304
+ except BaseException as error:
1305
+ if raw_evidence is None:
1306
+ try:
1307
+ raw_evidence = raw_spool.publish(
1308
+ status="incomplete_capture_failure",
1309
+ error=error,
1310
+ )
1311
+ except BaseException:
1312
+ raw_spool.close_without_deleting()
1313
+ else:
1314
+ with suppress(BaseException):
1315
+ raw_evidence = raw_spool.publish(
1316
+ status="normalization_failure",
1317
+ error=error,
1318
+ )
1319
+ with suppress(BaseException):
1320
+ _failure_record(
1321
+ output_root=output_root,
1322
+ capture_id=capture_id,
1323
+ symbol=symbol,
1324
+ raw_spool=raw_spool,
1325
+ raw_evidence=raw_evidence,
1326
+ error=error,
1327
+ )
1328
+ raise
1329
+ finally:
1330
+ for spool in spools.values():
1331
+ with suppress(BaseException):
1332
+ spool.close()
1333
+ if not validators_finished:
1334
+ delta_validator.close()
1335
+ observation_validator.close()
1336
+
1337
+
1338
+ def _cmd_collect_l2(args: argparse.Namespace) -> int:
1339
+ output_root = Path(args.output_root).resolve()
1340
+ result = asyncio.run(
1341
+ _capture_depth(
1342
+ symbol=str(args.symbol).upper(),
1343
+ max_messages=int(args.max_messages),
1344
+ output_root=output_root,
1345
+ duration_seconds=(
1346
+ float(args.duration_seconds) if args.duration_seconds is not None else None
1347
+ ),
1348
+ )
1349
+ )
1350
+ _print_json(
1351
+ {
1352
+ "symbol": result.symbol,
1353
+ "messages": result.messages,
1354
+ "reconstruction_status": result.reconstruction_status,
1355
+ "book_observations": result.book_observations,
1356
+ "sequence_gaps": result.sequence_gaps,
1357
+ "stale_events": result.stale_events,
1358
+ "excluded_messages": result.excluded_messages,
1359
+ "final_update_id": result.final_update_id,
1360
+ "quality_errors": result.quality_errors,
1361
+ "quality_warnings": result.quality_warnings,
1362
+ "raw_manifest": result.raw_manifest_path,
1363
+ "raw_manifest_sha256": result.raw_manifest_sha256,
1364
+ "capture_summary": result.summary_path,
1365
+ "completion_reason": result.completion_reason,
1366
+ "requested_duration_seconds": result.requested_duration_seconds,
1367
+ "elapsed_monotonic_seconds": result.elapsed_monotonic_seconds,
1368
+ "receipt_coverage_seconds": result.receipt_coverage_seconds,
1369
+ "max_continuity_epoch_seconds": result.max_continuity_epoch_seconds,
1370
+ "output_root": output_root,
1371
+ "live_trading": False,
1372
+ }
1373
+ )
1374
+ return 0 if result.reconstruction_status == "LIVE" and result.quality_errors == 0 else 1
1375
+
1376
+
1377
+ def _m8_l2_session_payload(result: M8L2SessionBundle) -> dict[str, object]:
1378
+ return {
1379
+ "status": result.status,
1380
+ "session_id": result.session_id,
1381
+ "session_date": result.session_date,
1382
+ "role": result.role,
1383
+ "output_root": result.root,
1384
+ "session_manifest": result.manifest_path,
1385
+ "session_manifest_sha256": result.manifest_sha256,
1386
+ "checksums": result.checksum_path,
1387
+ "terminal_marker": result.marker_path,
1388
+ "reason_codes": list(getattr(result, "reason_codes", ())),
1389
+ "source": "binance_spot_public_live_diff_depth",
1390
+ "live_trading": False,
1391
+ }
1392
+
1393
+
1394
+ def _cmd_capture_m8_l2_session(args: argparse.Namespace) -> int:
1395
+ config = load_m8_l2_config(args.config)
1396
+ result = asyncio.run(
1397
+ capture_m8_l2_session(
1398
+ config,
1399
+ str(args.date),
1400
+ Path(args.output_root).resolve(),
1401
+ BinanceM8L2Capture(),
1402
+ )
1403
+ )
1404
+ _print_json(_m8_l2_session_payload(result))
1405
+ return 0 if result.status == "COMPLETE" else 1
1406
+
1407
+
1408
+ def _cmd_verify_m8_l2_session(args: argparse.Namespace) -> int:
1409
+ config = load_m8_l2_config(args.config)
1410
+ result = verify_m8_l2_session_bundle(args.bundle_dir, expected_config=config)
1411
+ payload = _m8_l2_session_payload(result)
1412
+ payload["integrity"] = "verified"
1413
+ _print_json(payload)
1414
+ return 0
1415
+
1416
+
1417
+ def _m8_l2_development_payload(
1418
+ result: L2DevelopmentLockResult,
1419
+ *,
1420
+ integrity: str | None = None,
1421
+ ) -> dict[str, object]:
1422
+ payload: dict[str, object] = {
1423
+ "status": getattr(result, "status", "LOCKED"),
1424
+ "development_lock_dir": result.root,
1425
+ "development_lock": result.aggregate_path,
1426
+ "development_lock_sha256": result.aggregate_sha256,
1427
+ "terminal_marker": result.marker_path,
1428
+ "created_at_utc": result.created_at_utc,
1429
+ "children": [
1430
+ {
1431
+ "symbol": child.symbol,
1432
+ "endpoint": child.endpoint,
1433
+ "lock": child.path,
1434
+ "lock_sha256": child.sha256,
1435
+ "selection_lock_sha256": child.selection_lock_sha256,
1436
+ "fitted_state_sha256": child.fitted_state_sha256,
1437
+ }
1438
+ for child in result.children
1439
+ ],
1440
+ "reason_codes": list(getattr(result, "reason_codes", ())),
1441
+ "heldout_accessed": False,
1442
+ "source": "binance_spot_public_live_diff_depth",
1443
+ "live_trading": False,
1444
+ }
1445
+ if integrity is not None:
1446
+ payload["integrity"] = integrity
1447
+ return payload
1448
+
1449
+
1450
+ def _verify_m8_l2_session_authority(
1451
+ bundle_dir: Path,
1452
+ *,
1453
+ expected_config: M8L2StudyConfig,
1454
+ expected_date: str,
1455
+ expected_role: str,
1456
+ manifest_sha256: str,
1457
+ checksums_sha256: str,
1458
+ ) -> M8L2SessionBundle:
1459
+ bundle = verify_m8_l2_session_bundle(bundle_dir, expected_config=expected_config)
1460
+ if bundle.session_date != expected_date or bundle.role != expected_role:
1461
+ raise ValueError(
1462
+ f"explicit L2 session coordinate differs from {expected_date} {expected_role}"
1463
+ )
1464
+ if bundle.manifest_sha256 != manifest_sha256:
1465
+ raise ValueError(f"explicit {expected_role} session manifest differs from expected SHA-256")
1466
+ if sha256_file(bundle.checksum_path) != checksums_sha256:
1467
+ raise ValueError(f"explicit {expected_role} session checksums differ from expected SHA-256")
1468
+ return bundle
1469
+
1470
+
1471
+ def _m8_l2_insufficient_development_payload(
1472
+ sessions: Sequence[M8L2SessionBundle],
1473
+ ) -> dict[str, object]:
1474
+ return {
1475
+ "status": "INSUFFICIENT_DATA",
1476
+ "stage": "development_lock",
1477
+ "reason_code": "DEVELOPMENT_SESSION_NOT_COMPLETE",
1478
+ "sessions": [
1479
+ {
1480
+ "session_id": session.session_id,
1481
+ "session_date": session.session_date,
1482
+ "role": session.role,
1483
+ "status": session.status,
1484
+ "session_manifest": session.manifest_path,
1485
+ "session_manifest_sha256": session.manifest_sha256,
1486
+ "checksums": session.checksum_path,
1487
+ "checksums_sha256": sha256_file(session.checksum_path),
1488
+ "reason_codes": list(session.reason_codes),
1489
+ }
1490
+ for session in sessions
1491
+ ],
1492
+ "heldout_accessed": False,
1493
+ "source": "binance_spot_public_live_diff_depth",
1494
+ "live_trading": False,
1495
+ }
1496
+
1497
+
1498
+ def _development_session_authorities(
1499
+ args: argparse.Namespace,
1500
+ ) -> dict[str, L2SessionFileAuthority]:
1501
+ return {
1502
+ "2026-08-10": L2SessionFileAuthority(
1503
+ manifest_sha256=args.train_manifest_sha256,
1504
+ checksums_sha256=args.train_checksums_sha256,
1505
+ ),
1506
+ "2026-08-11": L2SessionFileAuthority(
1507
+ manifest_sha256=args.validation_manifest_sha256,
1508
+ checksums_sha256=args.validation_checksums_sha256,
1509
+ ),
1510
+ }
1511
+
1512
+
1513
+ def _explicit_development_input_loader(
1514
+ authorities: Mapping[str, L2SessionFileAuthority],
1515
+ ) -> L2DevelopmentInputVerifier:
1516
+ def load(
1517
+ bundle_dir: str | Path,
1518
+ *,
1519
+ expected_config: M8L2StudyConfig,
1520
+ expected_date: str,
1521
+ expected_role: str,
1522
+ expected_file_authority: object | None = None,
1523
+ expected_campaign: object | None = None,
1524
+ ) -> Any:
1525
+ authority = authorities.get(expected_date)
1526
+ if authority is None:
1527
+ raise ValueError("development input date is outside the explicit authority set")
1528
+ if expected_role not in ("train", "validation"):
1529
+ raise ValueError("development input role is outside the explicit authority set")
1530
+ if expected_file_authority is not None and expected_file_authority != authority:
1531
+ raise ValueError("development input authority differs from the explicit CLI authority")
1532
+ return verify_m8_l2_development_input(
1533
+ bundle_dir,
1534
+ expected_config=expected_config,
1535
+ expected_date=expected_date,
1536
+ expected_role=cast(Literal["train", "validation"], expected_role),
1537
+ expected_file_authority=authority,
1538
+ expected_campaign=cast(L2CampaignRuntimeIdentity | None, expected_campaign),
1539
+ )
1540
+
1541
+ return load
1542
+
1543
+
1544
+ def _load_explicit_development_sessions(
1545
+ args: argparse.Namespace,
1546
+ capture_config: M8L2StudyConfig,
1547
+ ) -> tuple[M8L2SessionBundle, M8L2SessionBundle]:
1548
+ train = _verify_m8_l2_session_authority(
1549
+ args.train_bundle_dir.absolute(),
1550
+ expected_config=capture_config,
1551
+ expected_date="2026-08-10",
1552
+ expected_role="train",
1553
+ manifest_sha256=args.train_manifest_sha256,
1554
+ checksums_sha256=args.train_checksums_sha256,
1555
+ )
1556
+ validation = _verify_m8_l2_session_authority(
1557
+ args.validation_bundle_dir.absolute(),
1558
+ expected_config=capture_config,
1559
+ expected_date="2026-08-11",
1560
+ expected_role="validation",
1561
+ manifest_sha256=args.validation_manifest_sha256,
1562
+ checksums_sha256=args.validation_checksums_sha256,
1563
+ )
1564
+ return train, validation
1565
+
1566
+
1567
+ def _cmd_lock_m8_l2_development(args: argparse.Namespace) -> int:
1568
+ capture_config = load_m8_l2_config(args.capture_config)
1569
+ analysis_config = load_m8_l2_analysis_config(args.analysis_config)
1570
+ _load_explicit_development_sessions(args, capture_config)
1571
+ result = lock_m8_l2_development(
1572
+ capture_config,
1573
+ analysis_config,
1574
+ args.train_bundle_dir.absolute(),
1575
+ args.validation_bundle_dir.absolute(),
1576
+ args.lock_dir.absolute(),
1577
+ input_loader=_explicit_development_input_loader(_development_session_authorities(args)),
1578
+ expected_session_file_authorities=_development_session_authorities(args),
1579
+ )
1580
+ _print_json(_m8_l2_development_payload(result))
1581
+ return 0 if getattr(result, "status", "LOCKED") == "LOCKED" else 1
1582
+
1583
+
1584
+ def _cmd_verify_m8_l2_development_lock(args: argparse.Namespace) -> int:
1585
+ capture_config = load_m8_l2_config(args.capture_config)
1586
+ analysis_config = load_m8_l2_analysis_config(args.analysis_config)
1587
+ _load_explicit_development_sessions(args, capture_config)
1588
+ result = verify_m8_l2_development_lock(
1589
+ capture_config,
1590
+ analysis_config,
1591
+ args.train_bundle_dir.absolute(),
1592
+ args.validation_bundle_dir.absolute(),
1593
+ args.lock_dir.absolute(),
1594
+ expected_lock_sha256=args.development_lock_sha256,
1595
+ )
1596
+ _print_json(_m8_l2_development_payload(result, integrity="verified"))
1597
+ return 0 if getattr(result, "status", "LOCKED") == "LOCKED" else 1
1598
+
1599
+
1600
+ def _m8_l2_study_authorities(
1601
+ args: argparse.Namespace,
1602
+ ) -> tuple[
1603
+ L2StudySessionAuthority,
1604
+ L2StudySessionAuthority,
1605
+ L2StudySessionAuthority,
1606
+ L2StudySessionAuthority,
1607
+ ]:
1608
+ def authority(role: str) -> L2StudySessionAuthority:
1609
+ return L2StudySessionAuthority(
1610
+ bundle_path=getattr(args, f"{role}_bundle_dir").absolute(),
1611
+ manifest_sha256=getattr(args, f"{role}_manifest_sha256"),
1612
+ checksums_sha256=getattr(args, f"{role}_checksums_sha256"),
1613
+ )
1614
+
1615
+ return (
1616
+ authority("train"),
1617
+ authority("validation"),
1618
+ authority("primary"),
1619
+ authority("replication"),
1620
+ )
1621
+
1622
+
1623
+ def _m8_l2_study_payload(
1624
+ result: M8L2StudyRunResult,
1625
+ *,
1626
+ integrity: str | None = None,
1627
+ ) -> dict[str, object]:
1628
+ payload: dict[str, object] = {
1629
+ "status": result.status,
1630
+ "run_dir": result.root,
1631
+ "run_manifest": result.manifest_path,
1632
+ "run_manifest_sha256": result.manifest_sha256,
1633
+ "checksums": result.checksum_path,
1634
+ "checksums_sha256": result.checksum_sha256,
1635
+ "terminal_marker": result.marker_path,
1636
+ "reason_codes": list(result.reason_codes),
1637
+ "source": "binance_spot_public_live_diff_depth",
1638
+ "live_trading": False,
1639
+ }
1640
+ if integrity is not None:
1641
+ payload["integrity"] = integrity
1642
+ return payload
1643
+
1644
+
1645
+ def _m8_l2_study_arguments(
1646
+ args: argparse.Namespace,
1647
+ capture_config: M8L2StudyConfig,
1648
+ analysis_config: M8L2AnalysisConfig,
1649
+ ) -> tuple[
1650
+ M8L2StudyConfig,
1651
+ M8L2AnalysisConfig,
1652
+ L2StudySessionAuthority,
1653
+ L2StudySessionAuthority,
1654
+ Path,
1655
+ str,
1656
+ L2StudySessionAuthority,
1657
+ L2StudySessionAuthority,
1658
+ Path,
1659
+ ]:
1660
+ train, validation, primary, replication = _m8_l2_study_authorities(args)
1661
+ return (
1662
+ capture_config,
1663
+ analysis_config,
1664
+ train,
1665
+ validation,
1666
+ args.development_lock_dir.absolute(),
1667
+ args.development_lock_sha256,
1668
+ primary,
1669
+ replication,
1670
+ args.run_dir.absolute(),
1671
+ )
1672
+
1673
+
1674
+ def _cmd_reproduce_m8_l2(args: argparse.Namespace) -> int:
1675
+ capture_config = load_m8_l2_config(args.capture_config)
1676
+ analysis_config = load_m8_l2_analysis_config(args.analysis_config)
1677
+ result = reproduce_m8_l2_study(*_m8_l2_study_arguments(args, capture_config, analysis_config))
1678
+ _print_json(_m8_l2_study_payload(result))
1679
+ return 0 if result.status == "COMPLETE" else 1
1680
+
1681
+
1682
+ def _verify_m8_l2_study_from_args(
1683
+ args: argparse.Namespace,
1684
+ *,
1685
+ capture_config: M8L2StudyConfig,
1686
+ analysis_config: M8L2AnalysisConfig,
1687
+ ) -> M8L2StudyRunResult:
1688
+ return verify_m8_l2_study_run(
1689
+ *_m8_l2_study_arguments(args, capture_config, analysis_config),
1690
+ expected_manifest_sha256=args.run_manifest_sha256,
1691
+ expected_checksums_sha256=args.run_checksums_sha256,
1692
+ )
1693
+
1694
+
1695
+ def _cmd_verify_m8_l2_run(args: argparse.Namespace) -> int:
1696
+ capture_config = load_m8_l2_config(args.capture_config)
1697
+ analysis_config = load_m8_l2_analysis_config(args.analysis_config)
1698
+ result = _verify_m8_l2_study_from_args(
1699
+ args,
1700
+ capture_config=capture_config,
1701
+ analysis_config=analysis_config,
1702
+ )
1703
+ _print_json(_m8_l2_study_payload(result, integrity="verified"))
1704
+ return 0 if result.status == "COMPLETE" else 1
1705
+
1706
+
1707
+ def _cmd_report_m8_l2(args: argparse.Namespace) -> int:
1708
+ capture_config = load_m8_l2_config(args.capture_config)
1709
+ analysis_config = load_m8_l2_analysis_config(args.analysis_config)
1710
+ positional = _m8_l2_study_arguments(args, capture_config, analysis_config)
1711
+ result = verify_m8_l2_study_run(
1712
+ *positional,
1713
+ expected_manifest_sha256=args.run_manifest_sha256,
1714
+ expected_checksums_sha256=args.run_checksums_sha256,
1715
+ )
1716
+ output = _external_report_dir(result.root, args.output_dir)
1717
+ report_data = load_m8_l2_report_data(
1718
+ *positional,
1719
+ expected_manifest_sha256=args.run_manifest_sha256,
1720
+ expected_checksums_sha256=args.run_checksums_sha256,
1721
+ )
1722
+ technical, memo, comparison = write_l2_report_set(output, report_data)
1723
+ payload = _m8_l2_study_payload(result, integrity="verified")
1724
+ payload.update(
1725
+ {
1726
+ "output_dir": output,
1727
+ "technical_report": technical,
1728
+ "executive_memo": memo,
1729
+ "model_comparison": comparison,
1730
+ "report_inputs_sha256": canonical_report_data_sha256(report_data),
1731
+ "source_bundle_modified": False,
1732
+ }
1733
+ )
1734
+ _print_json(payload)
1735
+ return 0 if result.status == "COMPLETE" else 1
1736
+
1737
+
1738
+ def _add_m8_l2_development_authority_args(parser: argparse.ArgumentParser) -> None:
1739
+ parser.add_argument("--capture-config", required=True, type=Path)
1740
+ parser.add_argument("--analysis-config", required=True, type=Path)
1741
+ parser.add_argument("--train-bundle-dir", required=True, type=Path)
1742
+ parser.add_argument(
1743
+ "--train-manifest-sha256",
1744
+ required=True,
1745
+ type=_lowercase_sha256,
1746
+ )
1747
+ parser.add_argument(
1748
+ "--train-checksums-sha256",
1749
+ required=True,
1750
+ type=_lowercase_sha256,
1751
+ )
1752
+ parser.add_argument("--validation-bundle-dir", required=True, type=Path)
1753
+ parser.add_argument(
1754
+ "--validation-manifest-sha256",
1755
+ required=True,
1756
+ type=_lowercase_sha256,
1757
+ )
1758
+ parser.add_argument(
1759
+ "--validation-checksums-sha256",
1760
+ required=True,
1761
+ type=_lowercase_sha256,
1762
+ )
1763
+ parser.add_argument("--lock-dir", required=True, type=Path)
1764
+
1765
+
1766
+ def _add_m8_l2_study_authority_args(
1767
+ parser: argparse.ArgumentParser,
1768
+ *,
1769
+ require_run_authority: bool,
1770
+ ) -> None:
1771
+ parser.add_argument("--capture-config", required=True, type=Path)
1772
+ parser.add_argument("--analysis-config", required=True, type=Path)
1773
+ for role in ("train", "validation", "primary", "replication"):
1774
+ parser.add_argument(f"--{role}-bundle-dir", required=True, type=Path)
1775
+ parser.add_argument(
1776
+ f"--{role}-manifest-sha256",
1777
+ required=True,
1778
+ type=_lowercase_sha256,
1779
+ )
1780
+ parser.add_argument(
1781
+ f"--{role}-checksums-sha256",
1782
+ required=True,
1783
+ type=_lowercase_sha256,
1784
+ )
1785
+ parser.add_argument("--development-lock-dir", required=True, type=Path)
1786
+ parser.add_argument(
1787
+ "--development-lock-sha256",
1788
+ required=True,
1789
+ type=_lowercase_sha256,
1790
+ )
1791
+ parser.add_argument("--run-dir", required=True, type=Path)
1792
+ if require_run_authority:
1793
+ parser.add_argument(
1794
+ "--run-manifest-sha256",
1795
+ required=True,
1796
+ type=_lowercase_sha256,
1797
+ )
1798
+ parser.add_argument(
1799
+ "--run-checksums-sha256",
1800
+ required=True,
1801
+ type=_lowercase_sha256,
1802
+ )
1803
+
1804
+
1805
+ def build_parser() -> argparse.ArgumentParser:
1806
+ parser = argparse.ArgumentParser(
1807
+ prog="microstructure",
1808
+ description="Research-only event-driven market-microstructure system",
1809
+ )
1810
+ parser.add_argument("--version", action="version", version=__version__)
1811
+ subparsers = parser.add_subparsers(dest="command", required=True)
1812
+
1813
+ ingest = subparsers.add_parser("ingest", help="ingest configured synthetic or public data")
1814
+ ingest.add_argument("--config", required=True, type=Path)
1815
+ ingest.add_argument("--output-root", type=Path)
1816
+ ingest.set_defaults(handler=_cmd_ingest)
1817
+
1818
+ acquire_m8 = subparsers.add_parser(
1819
+ "acquire-m8",
1820
+ help="acquire raw M8 evidence without opening any archive CSV member",
1821
+ )
1822
+ acquire_m8.add_argument("--config", required=True, type=Path)
1823
+ acquire_m8.add_argument("--output-root", required=True, type=Path)
1824
+ acquire_m8.set_defaults(handler=_cmd_acquire_m8)
1825
+
1826
+ validate = subparsers.add_parser("validate", help="run non-mutating data validation")
1827
+ validate.add_argument("--config", required=True, type=Path)
1828
+ validate.set_defaults(handler=_cmd_validate)
1829
+
1830
+ reproduce_parser = subparsers.add_parser(
1831
+ "reproduce", help="produce or verify an immutable end-to-end sample run"
1832
+ )
1833
+ reproduce_parser.add_argument("--config", required=True, type=Path)
1834
+ reproduce_parser.add_argument("--run-dir", required=True, type=Path)
1835
+ reproduce_parser.add_argument(
1836
+ "--ingestion-manifest",
1837
+ type=Path,
1838
+ help="explicit public ingestion manifest; required with its SHA-256 for public mode",
1839
+ )
1840
+ reproduce_parser.add_argument(
1841
+ "--ingestion-manifest-sha256",
1842
+ help="SHA-256 of --ingestion-manifest; required for public mode",
1843
+ )
1844
+ reproduce_parser.set_defaults(handler=_cmd_reproduce)
1845
+
1846
+ reproduce_m8_parser = subparsers.add_parser(
1847
+ "reproduce-m8",
1848
+ help="produce the frozen M8 study from one explicit raw acquisition authority",
1849
+ )
1850
+ reproduce_m8_parser.add_argument("--config", required=True, type=Path)
1851
+ reproduce_m8_parser.add_argument("--run-dir", required=True, type=Path)
1852
+ reproduce_m8_parser.add_argument("--raw-manifest", required=True, type=Path)
1853
+ reproduce_m8_parser.add_argument(
1854
+ "--raw-manifest-sha256",
1855
+ required=True,
1856
+ type=_lowercase_sha256,
1857
+ )
1858
+ reproduce_m8_parser.set_defaults(handler=_cmd_reproduce_m8)
1859
+
1860
+ verify_m8_parser = subparsers.add_parser(
1861
+ "verify-m8",
1862
+ help="verify a complete or INSUFFICIENT_DATA M8 result and its raw authority",
1863
+ )
1864
+ verify_m8_parser.add_argument("--config", required=True, type=Path)
1865
+ verify_m8_parser.add_argument("--run-dir", required=True, type=Path)
1866
+ verify_m8_parser.add_argument("--raw-manifest", required=True, type=Path)
1867
+ verify_m8_parser.add_argument(
1868
+ "--raw-manifest-sha256",
1869
+ required=True,
1870
+ type=_lowercase_sha256,
1871
+ )
1872
+ verify_m8_parser.set_defaults(handler=_cmd_verify_m8)
1873
+
1874
+ report_m8_parser = subparsers.add_parser(
1875
+ "report-m8",
1876
+ help="render a complete M8 result or expose its frozen failure report",
1877
+ )
1878
+ report_m8_parser.add_argument("--config", required=True, type=Path)
1879
+ report_m8_parser.add_argument("--run-dir", required=True, type=Path)
1880
+ report_m8_parser.add_argument("--raw-manifest", required=True, type=Path)
1881
+ report_m8_parser.add_argument(
1882
+ "--raw-manifest-sha256",
1883
+ required=True,
1884
+ type=_lowercase_sha256,
1885
+ )
1886
+ report_m8_parser.add_argument("--output-dir", type=Path)
1887
+ report_m8_parser.set_defaults(handler=_cmd_report_m8)
1888
+
1889
+ verify = subparsers.add_parser("verify", help="verify a frozen run and all checksums")
1890
+ verify.add_argument("--run-dir", required=True, type=Path)
1891
+ verify.set_defaults(handler=_cmd_verify)
1892
+
1893
+ report = subparsers.add_parser("report", help="render reports from a frozen run")
1894
+ report.add_argument("--run-dir", required=True, type=Path)
1895
+ report.add_argument("--output-dir", type=Path)
1896
+ report.set_defaults(handler=_cmd_report)
1897
+
1898
+ collect = subparsers.add_parser(
1899
+ "collect-l2", help="capture and reconstruct public live L2 data; never place orders"
1900
+ )
1901
+ collect.add_argument("--symbol", choices=("BTCUSDT", "ETHUSDT"), required=True)
1902
+ collect.add_argument("--max-messages", type=int, default=1_000)
1903
+ collect.add_argument(
1904
+ "--duration-seconds",
1905
+ type=float,
1906
+ help=(
1907
+ "gracefully complete after this wall duration; max-messages remains a safety "
1908
+ "ceiling and fails the capture if reached first"
1909
+ ),
1910
+ )
1911
+ collect.add_argument("--output-root", type=Path, default=Path("data"))
1912
+ collect.set_defaults(handler=_cmd_collect_l2)
1913
+
1914
+ capture_m8_l2 = subparsers.add_parser(
1915
+ "capture-m8-l2-session",
1916
+ help="capture one frozen concurrent BTCUSDT/ETHUSDT prospective L2 session",
1917
+ )
1918
+ capture_m8_l2.add_argument("--config", required=True, type=Path)
1919
+ capture_m8_l2.add_argument("--date", required=True)
1920
+ capture_m8_l2.add_argument("--output-root", required=True, type=Path)
1921
+ capture_m8_l2.set_defaults(handler=_cmd_capture_m8_l2_session)
1922
+
1923
+ verify_m8_l2 = subparsers.add_parser(
1924
+ "verify-m8-l2-session",
1925
+ help="verify a complete or INSUFFICIENT_DATA frozen L2 session bundle",
1926
+ )
1927
+ verify_m8_l2.add_argument("--config", required=True, type=Path)
1928
+ verify_m8_l2.add_argument("--bundle-dir", required=True, type=Path)
1929
+ verify_m8_l2.set_defaults(handler=_cmd_verify_m8_l2_session)
1930
+
1931
+ lock_m8_l2_development_parser = subparsers.add_parser(
1932
+ "lock-m8-l2-development",
1933
+ help="fit and freeze the Aug 8/9 L2 development state before held-out access",
1934
+ )
1935
+ _add_m8_l2_development_authority_args(lock_m8_l2_development_parser)
1936
+ lock_m8_l2_development_parser.set_defaults(handler=_cmd_lock_m8_l2_development)
1937
+
1938
+ verify_m8_l2_development_parser = subparsers.add_parser(
1939
+ "verify-m8-l2-development-lock",
1940
+ help="verify the frozen L2 development lock and its explicit session authorities",
1941
+ )
1942
+ _add_m8_l2_development_authority_args(verify_m8_l2_development_parser)
1943
+ verify_m8_l2_development_parser.add_argument(
1944
+ "--development-lock-sha256",
1945
+ required=True,
1946
+ type=_lowercase_sha256,
1947
+ )
1948
+ verify_m8_l2_development_parser.set_defaults(handler=_cmd_verify_m8_l2_development_lock)
1949
+
1950
+ reproduce_m8_l2_parser = subparsers.add_parser(
1951
+ "reproduce-m8-l2",
1952
+ help="produce the frozen four-session prospective live-L2 study",
1953
+ )
1954
+ _add_m8_l2_study_authority_args(
1955
+ reproduce_m8_l2_parser,
1956
+ require_run_authority=False,
1957
+ )
1958
+ reproduce_m8_l2_parser.set_defaults(handler=_cmd_reproduce_m8_l2)
1959
+
1960
+ verify_m8_l2_run_parser = subparsers.add_parser(
1961
+ "verify-m8-l2-run",
1962
+ help="verify a terminal live-L2 study and all external authorities",
1963
+ )
1964
+ _add_m8_l2_study_authority_args(
1965
+ verify_m8_l2_run_parser,
1966
+ require_run_authority=True,
1967
+ )
1968
+ verify_m8_l2_run_parser.set_defaults(handler=_cmd_verify_m8_l2_run)
1969
+
1970
+ report_m8_l2_parser = subparsers.add_parser(
1971
+ "report-m8-l2",
1972
+ help="render verified live-L2 report inputs outside the immutable run bundle",
1973
+ )
1974
+ _add_m8_l2_study_authority_args(
1975
+ report_m8_l2_parser,
1976
+ require_run_authority=True,
1977
+ )
1978
+ report_m8_l2_parser.add_argument("--output-dir", required=True, type=Path)
1979
+ report_m8_l2_parser.set_defaults(handler=_cmd_report_m8_l2)
1980
+ return parser
1981
+
1982
+
1983
+ def main(argv: Sequence[str] | None = None) -> int:
1984
+ parser = build_parser()
1985
+ args = parser.parse_args(argv)
1986
+ if getattr(args, "max_messages", 1) < 1:
1987
+ parser.error("--max-messages must be positive")
1988
+ duration_seconds = getattr(args, "duration_seconds", None)
1989
+ if duration_seconds is not None and duration_seconds <= 0:
1990
+ parser.error("--duration-seconds must be positive")
1991
+ handler = args.handler
1992
+ try:
1993
+ return int(handler(args))
1994
+ except (KeyboardInterrupt, asyncio.CancelledError):
1995
+ print("operation canceled", file=sys.stderr)
1996
+ return 130
1997
+ except Exception as error:
1998
+ print(f"error: {error}", file=sys.stderr)
1999
+ return 2
2000
+
2001
+
2002
+ if __name__ == "__main__": # pragma: no cover
2003
+ raise SystemExit(main())
Microstructure/src/microstructure/config.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed project configuration with deterministic hashing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import re
9
+ import tomllib
10
+ from collections.abc import Mapping
11
+ from dataclasses import asdict, dataclass
12
+ from datetime import UTC, datetime
13
+ from pathlib import Path
14
+ from typing import Any, Literal, cast
15
+
16
+ from microstructure.data.schemas import SCHEMA_VERSION
17
+
18
+
19
+ class ConfigError(ValueError):
20
+ """Raised when a project configuration is internally inconsistent."""
21
+
22
+
23
+ EvidenceTier = Literal["SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"]
24
+ # Adapter modes are intentionally open-ended: ingestion owns the fail-closed
25
+ # registry, while configuration validates a stable identifier that third-party
26
+ # adapters can use. Built-in modes retain their source-specific checks below.
27
+ DataMode = str
28
+ _DATA_MODE_PATTERN = re.compile(r"[a-z][a-z0-9_.-]{0,63}")
29
+
30
+
31
+ def _utc_datetime(value: str) -> datetime:
32
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
33
+ if parsed.tzinfo is None:
34
+ raise ConfigError(f"timestamp must include a UTC offset: {value!r}")
35
+ return parsed.astimezone(UTC)
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class RunConfig:
40
+ name: str
41
+ evidence_tier: EvidenceTier
42
+ seed: int
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class DataConfig:
47
+ mode: DataMode
48
+ source: str
49
+ symbols: tuple[str, ...]
50
+ start: datetime
51
+ end: datetime | None
52
+ events_per_symbol: int | None
53
+ max_events_per_symbol: int | None
54
+ raw_root: Path
55
+ partition_root: Path
56
+ schema_version: str
57
+ base_url: str
58
+ request_limit: int
59
+ timeout_seconds: float
60
+ max_retries: int
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class QualityConfig:
65
+ max_spread_bps: float
66
+ max_silence_ms: int
67
+ fail_on_error: bool
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class FeatureConfig:
72
+ trade_windows: tuple[int, ...]
73
+ volatility_window: int
74
+ intensity_window: int
75
+ label_horizon_events: int
76
+ large_trade_quantile: float
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class EvaluationConfig:
81
+ min_train_events: int
82
+ validation_events: int
83
+ test_events: int
84
+ step_events: int
85
+ embargo_events: int
86
+ bootstrap_samples: int
87
+ calibration_bins: int
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class ModelConfig:
92
+ selection_metric: str
93
+ logistic_c_values: tuple[float, ...]
94
+ tree_max_depth_values: tuple[int, ...]
95
+ tree_min_samples_leaf: int
96
+
97
+
98
+ @dataclass(frozen=True, slots=True)
99
+ class ExecutionConfig:
100
+ decision_latency_events: int
101
+ order_latency_events: int
102
+ maker_fee_bps: float
103
+ taker_fee_bps: float
104
+ half_spread_bps: float
105
+ slippage_bps_per_unit: float
106
+ signal_threshold: float
107
+ max_position_units: float
108
+ order_size_units: float
109
+ limit_fill_base_probability: float
110
+ queue_ahead_units: float
111
+ limit_max_age_events: int
112
+ cancel_latency_events: int
113
+ liquidate_at_end: bool
114
+ capacity_multipliers: tuple[float, ...]
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class ProjectConfig:
119
+ path: Path
120
+ project_root: Path
121
+ run: RunConfig
122
+ data: DataConfig
123
+ quality: QualityConfig
124
+ features: FeatureConfig
125
+ evaluation: EvaluationConfig
126
+ models: ModelConfig
127
+ execution: ExecutionConfig
128
+ canonical: Mapping[str, Any]
129
+
130
+ @property
131
+ def hash(self) -> str:
132
+ """Return a stable SHA-256 hash of the source configuration."""
133
+ payload = json.dumps(self.canonical, sort_keys=True, separators=(",", ":"))
134
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
135
+
136
+ def public_dict(self) -> dict[str, Any]:
137
+ """Return a JSON-safe representation with resolved paths and timestamps."""
138
+ result = asdict(self)
139
+ result.pop("canonical")
140
+ result["path"] = str(self.path)
141
+ result["project_root"] = str(self.project_root)
142
+ data = cast(dict[str, Any], result["data"])
143
+ data["start"] = self.data.start.isoformat().replace("+00:00", "Z")
144
+ data["end"] = self.data.end.isoformat().replace("+00:00", "Z") if self.data.end else None
145
+ data["raw_root"] = str(self.data.raw_root)
146
+ data["partition_root"] = str(self.data.partition_root)
147
+ return result
148
+
149
+
150
+ def _section(raw: Mapping[str, Any], name: str) -> Mapping[str, Any]:
151
+ value = raw.get(name)
152
+ if not isinstance(value, Mapping):
153
+ raise ConfigError(f"missing TOML section [{name}]")
154
+ return cast(Mapping[str, Any], value)
155
+
156
+
157
+ def _resolve(project_root: Path, value: str) -> Path:
158
+ candidate = Path(value)
159
+ return candidate if candidate.is_absolute() else (project_root / candidate).resolve()
160
+
161
+
162
+ def load_config(path: str | Path) -> ProjectConfig:
163
+ """Load and validate a project TOML configuration."""
164
+ config_path = Path(path).resolve()
165
+ with config_path.open("rb") as handle:
166
+ raw: dict[str, Any] = tomllib.load(handle)
167
+
168
+ project_root = config_path.parent.parent.resolve()
169
+ run_raw = _section(raw, "run")
170
+ data_raw = _section(raw, "data")
171
+ quality_raw = _section(raw, "quality")
172
+ feature_raw = _section(raw, "features")
173
+ evaluation_raw = _section(raw, "evaluation")
174
+ model_raw = _section(raw, "models")
175
+ execution_raw = _section(raw, "execution")
176
+
177
+ evidence_tier = str(run_raw["evidence_tier"])
178
+ if evidence_tier not in {"SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"}:
179
+ raise ConfigError(f"unsupported evidence tier: {evidence_tier}")
180
+ mode = str(data_raw["mode"])
181
+ if _DATA_MODE_PATTERN.fullmatch(mode) is None:
182
+ raise ConfigError(
183
+ "data.mode must be a lowercase adapter identifier containing only "
184
+ "letters, digits, underscores, dots, or hyphens"
185
+ )
186
+
187
+ start = _utc_datetime(str(data_raw["start"]))
188
+ end_value = data_raw.get("end")
189
+ end = _utc_datetime(str(end_value)) if end_value is not None else None
190
+ if end is not None and end <= start:
191
+ raise ConfigError("data.end must be after data.start")
192
+
193
+ run = RunConfig(
194
+ name=str(run_raw["name"]),
195
+ evidence_tier=cast(EvidenceTier, evidence_tier),
196
+ seed=int(run_raw["seed"]),
197
+ )
198
+ data = DataConfig(
199
+ mode=mode,
200
+ source=str(data_raw["source"]),
201
+ symbols=tuple(str(symbol).upper() for symbol in data_raw["symbols"]),
202
+ start=start,
203
+ end=end,
204
+ events_per_symbol=(
205
+ int(data_raw["events_per_symbol"])
206
+ if data_raw.get("events_per_symbol") is not None
207
+ else None
208
+ ),
209
+ max_events_per_symbol=(
210
+ int(data_raw["max_events_per_symbol"])
211
+ if data_raw.get("max_events_per_symbol") is not None
212
+ else None
213
+ ),
214
+ raw_root=_resolve(project_root, str(data_raw.get("raw_root", "data/raw"))),
215
+ partition_root=_resolve(project_root, str(data_raw["partition_root"])),
216
+ schema_version=str(data_raw["schema_version"]),
217
+ base_url=str(data_raw.get("base_url", "https://data-api.binance.vision")).rstrip("/"),
218
+ request_limit=int(data_raw.get("request_limit", 1000)),
219
+ timeout_seconds=float(data_raw.get("timeout_seconds", 30.0)),
220
+ max_retries=int(data_raw.get("max_retries", 5)),
221
+ )
222
+ quality = QualityConfig(
223
+ max_spread_bps=float(quality_raw["max_spread_bps"]),
224
+ max_silence_ms=int(quality_raw["max_silence_ms"]),
225
+ fail_on_error=bool(quality_raw["fail_on_error"]),
226
+ )
227
+ features = FeatureConfig(
228
+ trade_windows=tuple(int(window) for window in feature_raw["trade_windows"]),
229
+ volatility_window=int(feature_raw["volatility_window"]),
230
+ intensity_window=int(feature_raw["intensity_window"]),
231
+ label_horizon_events=int(feature_raw["label_horizon_events"]),
232
+ large_trade_quantile=float(feature_raw["large_trade_quantile"]),
233
+ )
234
+ evaluation = EvaluationConfig(
235
+ min_train_events=int(evaluation_raw["min_train_events"]),
236
+ validation_events=int(evaluation_raw["validation_events"]),
237
+ test_events=int(evaluation_raw["test_events"]),
238
+ step_events=int(evaluation_raw["step_events"]),
239
+ embargo_events=int(evaluation_raw["embargo_events"]),
240
+ bootstrap_samples=int(evaluation_raw["bootstrap_samples"]),
241
+ calibration_bins=int(evaluation_raw["calibration_bins"]),
242
+ )
243
+ models = ModelConfig(
244
+ selection_metric=str(model_raw["selection_metric"]),
245
+ logistic_c_values=tuple(float(value) for value in model_raw["logistic_c_values"]),
246
+ tree_max_depth_values=tuple(int(value) for value in model_raw["tree_max_depth_values"]),
247
+ tree_min_samples_leaf=int(model_raw["tree_min_samples_leaf"]),
248
+ )
249
+ execution = ExecutionConfig(
250
+ decision_latency_events=int(execution_raw["decision_latency_events"]),
251
+ order_latency_events=int(execution_raw["order_latency_events"]),
252
+ maker_fee_bps=float(execution_raw["maker_fee_bps"]),
253
+ taker_fee_bps=float(execution_raw["taker_fee_bps"]),
254
+ half_spread_bps=float(execution_raw["half_spread_bps"]),
255
+ slippage_bps_per_unit=float(execution_raw["slippage_bps_per_unit"]),
256
+ signal_threshold=float(execution_raw["signal_threshold"]),
257
+ max_position_units=float(execution_raw["max_position_units"]),
258
+ order_size_units=float(execution_raw["order_size_units"]),
259
+ limit_fill_base_probability=float(execution_raw["limit_fill_base_probability"]),
260
+ queue_ahead_units=float(execution_raw["queue_ahead_units"]),
261
+ limit_max_age_events=int(execution_raw["limit_max_age_events"]),
262
+ cancel_latency_events=int(execution_raw["cancel_latency_events"]),
263
+ liquidate_at_end=bool(execution_raw["liquidate_at_end"]),
264
+ capacity_multipliers=tuple(float(value) for value in execution_raw["capacity_multipliers"]),
265
+ )
266
+
267
+ if not data.symbols:
268
+ raise ConfigError("data.symbols must not be empty")
269
+ if data.mode == "synthetic" and (data.events_per_symbol is None or data.events_per_symbol < 1):
270
+ raise ConfigError("synthetic mode requires positive data.events_per_symbol")
271
+ if data.mode == "synthetic" and run.evidence_tier != "SYNTHETIC_SMOKE":
272
+ raise ConfigError("synthetic inputs must use the SYNTHETIC_SMOKE evidence tier")
273
+ if data.mode == "binance_rest" and run.evidence_tier == "SYNTHETIC_SMOKE":
274
+ raise ConfigError("public inputs cannot use the SYNTHETIC_SMOKE evidence tier")
275
+ if data.mode == "binance_rest" and data.end is None:
276
+ raise ConfigError("binance_rest mode requires a bounded data.end")
277
+ if data.mode == "binance_rest" and (
278
+ data.max_events_per_symbol is None or data.max_events_per_symbol < 1
279
+ ):
280
+ raise ConfigError("binance_rest mode requires positive data.max_events_per_symbol")
281
+ if data.schema_version != SCHEMA_VERSION:
282
+ raise ConfigError(
283
+ f"unsupported data.schema_version {data.schema_version!r}; expected {SCHEMA_VERSION!r}"
284
+ )
285
+ if not all(window > 1 for window in features.trade_windows):
286
+ raise ConfigError("all feature trade windows must exceed one event")
287
+ if features.label_horizon_events < 1:
288
+ raise ConfigError("label_horizon_events must be positive")
289
+ if evaluation.embargo_events < features.label_horizon_events:
290
+ raise ConfigError("embargo_events must cover label_horizon_events")
291
+ if not 0.5 < execution.signal_threshold < 1.0:
292
+ raise ConfigError("signal_threshold must be between 0.5 and 1.0")
293
+ if not 0.0 <= execution.limit_fill_base_probability <= 1.0:
294
+ raise ConfigError("limit_fill_base_probability must be in [0, 1]")
295
+ if execution.limit_max_age_events < 1 or execution.cancel_latency_events < 0:
296
+ raise ConfigError("limit order age must be positive and cancel latency nonnegative")
297
+ if execution.decision_latency_events < 0 or execution.order_latency_events < 0:
298
+ raise ConfigError("decision and order latency must be nonnegative")
299
+ if execution.max_position_units <= 0 or execution.order_size_units <= 0:
300
+ raise ConfigError("execution position and order sizes must be positive")
301
+ execution_floats = (
302
+ execution.maker_fee_bps,
303
+ execution.taker_fee_bps,
304
+ execution.half_spread_bps,
305
+ execution.slippage_bps_per_unit,
306
+ execution.max_position_units,
307
+ execution.order_size_units,
308
+ execution.queue_ahead_units,
309
+ )
310
+ if not all(math.isfinite(value) for value in execution_floats):
311
+ raise ConfigError("execution numeric assumptions must be finite")
312
+ if execution.queue_ahead_units < 0:
313
+ raise ConfigError("execution queue_ahead_units must be nonnegative")
314
+ if execution.half_spread_bps < 0 or execution.slippage_bps_per_unit < 0:
315
+ raise ConfigError("execution spread and slippage assumptions must be nonnegative")
316
+ if not execution.capacity_multipliers or not all(
317
+ math.isfinite(value) and value > 0 for value in execution.capacity_multipliers
318
+ ):
319
+ raise ConfigError("execution capacity_multipliers must be finite and positive")
320
+ if not 0.0 < features.large_trade_quantile < 1.0:
321
+ raise ConfigError("large_trade_quantile must lie strictly between zero and one")
322
+
323
+ return ProjectConfig(
324
+ path=config_path,
325
+ project_root=project_root,
326
+ run=run,
327
+ data=data,
328
+ quality=quality,
329
+ features=features,
330
+ evaluation=evaluation,
331
+ models=models,
332
+ execution=execution,
333
+ canonical=raw,
334
+ )
335
+
336
+
337
+ def datetime_to_ns(value: datetime) -> int:
338
+ """Convert an aware UTC datetime to integer epoch nanoseconds."""
339
+ if value.tzinfo is None:
340
+ raise ConfigError("datetime must be timezone aware")
341
+ return int(value.timestamp() * 1_000_000_000)
Microstructure/src/microstructure/data/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Market-data ingestion, normalization, storage, and validation primitives.
2
+
3
+ The package deliberately contains no authenticated or order-entry API. Binance
4
+ support is restricted to public market-data endpoints.
5
+ """
6
+
7
+ from microstructure.data.book import (
8
+ BookSnapshot,
9
+ DepthDelta,
10
+ ReconstructionResult,
11
+ reconstruct_snapshot_and_deltas,
12
+ )
13
+ from microstructure.data.quality import QualityFinding, ValidationReport, validate_table
14
+ from microstructure.data.schemas import SCHEMA_VERSION, get_schema, table_from_records
15
+ from microstructure.data.storage import DatasetWriteResult, write_partitioned_parquet
16
+ from microstructure.data.synthetic import SyntheticMarketData, generate_synthetic_market
17
+
18
+ __all__ = [
19
+ "SCHEMA_VERSION",
20
+ "BookSnapshot",
21
+ "DatasetWriteResult",
22
+ "DepthDelta",
23
+ "QualityFinding",
24
+ "ReconstructionResult",
25
+ "SyntheticMarketData",
26
+ "ValidationReport",
27
+ "generate_synthetic_market",
28
+ "get_schema",
29
+ "reconstruct_snapshot_and_deltas",
30
+ "table_from_records",
31
+ "validate_table",
32
+ "write_partitioned_parquet",
33
+ ]
Microstructure/src/microstructure/data/binance.py ADDED
@@ -0,0 +1,1330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public Binance Spot market-data adapters; no authenticated/trading endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import random
10
+ import tempfile
11
+ import time
12
+ from collections.abc import AsyncIterator, Callable, Iterator, Mapping
13
+ from contextlib import nullcontext
14
+ from dataclasses import dataclass
15
+ from decimal import Decimal, InvalidOperation
16
+ from enum import StrEnum
17
+ from pathlib import Path
18
+ from typing import Any, Literal, Protocol, cast
19
+
20
+ import pyarrow as pa # type: ignore[import-untyped]
21
+ import requests
22
+ import websockets
23
+ from websockets.exceptions import WebSocketException
24
+
25
+ from microstructure.data.book import BookSnapshot, DepthDelta
26
+ from microstructure.data.evidence_budget import RetainedEvidenceBudget
27
+ from microstructure.data.schemas import SCHEMA_VERSION, get_schema, table_from_records
28
+ from microstructure.data.storage import write_source_manifest
29
+ from microstructure.provenance import sha256_file
30
+
31
+ _NS_PER_MILLISECOND = 1_000_000
32
+ _NS_PER_MICROSECOND = 1_000
33
+
34
+
35
+ class BinanceError(RuntimeError):
36
+ """Base error for public Binance market-data collection."""
37
+
38
+
39
+ class BinanceHTTPError(BinanceError):
40
+ """Raised when a public market-data GET cannot be completed safely."""
41
+
42
+ def __init__(
43
+ self,
44
+ message: str,
45
+ *,
46
+ status_code: int | None = None,
47
+ retry_exhausted: bool = False,
48
+ ) -> None:
49
+ super().__init__(message)
50
+ self.status_code = status_code
51
+ self.retry_exhausted = retry_exhausted
52
+
53
+
54
+ class BinancePayloadError(BinanceError):
55
+ """Raised when Binance returns malformed or scale-incompatible data."""
56
+
57
+ def __init__(self, message: str, *, transient: bool = False) -> None:
58
+ super().__init__(message)
59
+ self.transient = transient
60
+
61
+
62
+ class BinanceMetadataContractError(BinancePayloadError):
63
+ """A bounded exchangeInfo response violates the declared metadata contract."""
64
+
65
+
66
+ class BinanceResponseSizeLimitError(BinancePayloadError):
67
+ """A public response violates its frozen body-size contract."""
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class RetryPolicy:
72
+ max_retries: int = 5
73
+ base_delay_seconds: float = 0.5
74
+ max_delay_seconds: float = 30.0
75
+
76
+ def __post_init__(self) -> None:
77
+ if self.max_retries < 0:
78
+ raise ValueError("max_retries must not be negative")
79
+ if self.base_delay_seconds < 0.0 or self.max_delay_seconds < 0.0:
80
+ raise ValueError("retry delays must not be negative")
81
+
82
+
83
+ @dataclass(frozen=True, slots=True)
84
+ class RawPage:
85
+ path: Path
86
+ manifest_path: Path
87
+ sha256: str
88
+ request_uri: str
89
+ row_count: int
90
+
91
+
92
+ @dataclass(frozen=True, slots=True)
93
+ class BinanceDownloadResult:
94
+ trades: pa.Table
95
+ raw_pages: tuple[RawPage, ...]
96
+ requested_start_ns: int
97
+ requested_end_ns: int
98
+ complete_range: bool
99
+
100
+
101
+ class BinanceTradeStreamStopReason(StrEnum):
102
+ """Why a normally exhausted historical-trade stream stopped."""
103
+
104
+ EMPTY_PAGE = "empty_page"
105
+ SHORT_PAGE = "short_page"
106
+ RANGE_END = "range_end"
107
+ EVENT_CAP = "event_cap"
108
+
109
+
110
+ @dataclass(frozen=True, slots=True)
111
+ class BinanceTradeStreamSummary:
112
+ """Constant-size terminal metadata for a historical-trade stream."""
113
+
114
+ requested_start_ns: int
115
+ requested_end_ns: int
116
+ rows_yielded: int
117
+ raw_page_count: int
118
+ stop_reason: BinanceTradeStreamStopReason
119
+ complete_range: bool
120
+ last_raw_page: RawPage | None
121
+
122
+
123
+ @dataclass(frozen=True, slots=True)
124
+ class CapturedDepth:
125
+ raw_payload: str
126
+ delta: DepthDelta
127
+
128
+
129
+ @dataclass(frozen=True, slots=True)
130
+ class RawDepthFrame:
131
+ """One exact websocket frame timestamped before UTF-8/JSON normalization."""
132
+
133
+ payload: bytes
134
+ was_text: bool
135
+ received_ts_ns: int
136
+ capture_seq: int
137
+ continuity_id: str
138
+
139
+
140
+ @dataclass(frozen=True, slots=True)
141
+ class SymbolMetadata:
142
+ """Public symbol filters captured before tick/lot normalization."""
143
+
144
+ venue: str
145
+ symbol: str
146
+ status: str
147
+ base_asset: str
148
+ quote_asset: str
149
+ tick_size: Decimal
150
+ lot_size: Decimal
151
+ min_price: Decimal
152
+ max_price: Decimal
153
+ min_quantity: Decimal
154
+ max_quantity: Decimal
155
+ observed_ts_ns: int
156
+ source_artifact_id: str
157
+ source_path: Path
158
+ source_manifest_path: Path
159
+
160
+
161
+ class _WebSocketConnection(Protocol):
162
+ def __aiter__(self) -> AsyncIterator[str | bytes]: ...
163
+
164
+
165
+ class _WebSocketContext(Protocol):
166
+ async def __aenter__(self) -> _WebSocketConnection: ...
167
+
168
+ async def __aexit__(
169
+ self,
170
+ exc_type: type[BaseException] | None,
171
+ exc_value: BaseException | None,
172
+ traceback: object | None,
173
+ ) -> bool | None: ...
174
+
175
+
176
+ ConnectFactory = Callable[[str], _WebSocketContext]
177
+ RawDepthFrameCallback = Callable[[RawDepthFrame], None]
178
+
179
+
180
+ def _scaled_integer(value: str | Decimal, quantum: Decimal, label: str) -> int:
181
+ try:
182
+ decimal_value = value if isinstance(value, Decimal) else Decimal(value)
183
+ scaled = decimal_value / quantum
184
+ except (InvalidOperation, ZeroDivisionError) as exc:
185
+ raise BinancePayloadError(f"invalid {label}: {value!r}") from exc
186
+ integral = scaled.to_integral_value()
187
+ if scaled != integral:
188
+ raise BinancePayloadError(
189
+ f"{label} {decimal_value} is not aligned to configured scale {quantum}"
190
+ )
191
+ return int(integral)
192
+
193
+
194
+ def _event_timestamp_ns(value: int, unit: Literal["ms", "us"]) -> int:
195
+ if value < 0:
196
+ raise BinancePayloadError("event timestamp must not be negative")
197
+ return value * (_NS_PER_MILLISECOND if unit == "ms" else _NS_PER_MICROSECOND)
198
+
199
+
200
+ def _safe_response_headers(headers: Mapping[str, str]) -> dict[str, str]:
201
+ allowed = {"content-length", "content-type", "etag", "last-modified", "retry-after"}
202
+ return {
203
+ str(key): str(value)
204
+ for key, value in headers.items()
205
+ if key.lower() in allowed or key.lower().startswith("x-mbx-used-weight")
206
+ }
207
+
208
+
209
+ def _close_response(response: object) -> None:
210
+ close = getattr(response, "close", None)
211
+ if callable(close):
212
+ cast(Callable[[], object], close)()
213
+
214
+
215
+ def _fsync_directory(path: Path) -> None:
216
+ descriptor = os.open(path, os.O_RDONLY)
217
+ try:
218
+ os.fsync(descriptor)
219
+ finally:
220
+ os.close(descriptor)
221
+
222
+
223
+ class BinancePublicClient:
224
+ """Retrying client for market-data-only GET endpoints."""
225
+
226
+ def __init__(
227
+ self,
228
+ *,
229
+ base_url: str = "https://data-api.binance.vision",
230
+ timeout_seconds: float = 30.0,
231
+ retry_policy: RetryPolicy | None = None,
232
+ session: requests.Session | None = None,
233
+ sleep: Callable[[float], None] = time.sleep,
234
+ random_value: Callable[[], float] = random.random,
235
+ max_response_bytes: int = 8 * 1024 * 1024,
236
+ retained_evidence_budget: RetainedEvidenceBudget | None = None,
237
+ ) -> None:
238
+ if max_response_bytes < 1:
239
+ raise ValueError("max_response_bytes must be positive")
240
+ self.base_url = base_url.rstrip("/")
241
+ self.timeout_seconds = timeout_seconds
242
+ self.retry_policy = retry_policy or RetryPolicy()
243
+ self.session = session or requests.Session()
244
+ self._sleep = sleep
245
+ self._random_value = random_value
246
+ self.max_response_bytes = max_response_bytes
247
+ self.retained_evidence_budget = retained_evidence_budget
248
+
249
+ def _session_get(
250
+ self,
251
+ url: str,
252
+ params: Mapping[str, str | int],
253
+ *,
254
+ stream_response: bool,
255
+ ) -> requests.Response:
256
+ if not stream_response:
257
+ return self.session.get(url, params=params, timeout=self.timeout_seconds)
258
+ try:
259
+ return self.session.get(
260
+ url,
261
+ params=params,
262
+ timeout=self.timeout_seconds,
263
+ stream=True,
264
+ )
265
+ except TypeError as exc:
266
+ # Older injected test sessions may implement only the original
267
+ # three-argument boundary. Production requests.Session accepts
268
+ # ``stream`` and therefore always takes the bounded transport path.
269
+ if "unexpected keyword argument 'stream'" not in str(exc):
270
+ raise
271
+ return self.session.get(url, params=params, timeout=self.timeout_seconds)
272
+
273
+ def _request(
274
+ self,
275
+ path: str,
276
+ params: Mapping[str, str | int],
277
+ *,
278
+ stream_response: bool = False,
279
+ ) -> requests.Response:
280
+ url = f"{self.base_url}{path}"
281
+ last_error: BaseException | None = None
282
+ for attempt in range(self.retry_policy.max_retries + 1):
283
+ response: requests.Response | None = None
284
+ try:
285
+ response = self._session_get(
286
+ url,
287
+ params,
288
+ stream_response=stream_response,
289
+ )
290
+ except requests.RequestException as exc:
291
+ last_error = exc
292
+ retryable = True
293
+ else:
294
+ if response.status_code == 200:
295
+ return response
296
+ retryable = response.status_code in {408, 418, 429} or response.status_code >= 500
297
+ response_detail = (
298
+ "response body intentionally not materialized"
299
+ if stream_response
300
+ else response.text[:200]
301
+ )
302
+ last_error = BinanceHTTPError(
303
+ f"GET {response.url} returned HTTP {response.status_code}: {response_detail}",
304
+ status_code=response.status_code,
305
+ )
306
+ if not retryable:
307
+ _close_response(response)
308
+ raise last_error
309
+
310
+ if not retryable or attempt >= self.retry_policy.max_retries:
311
+ if response is not None:
312
+ _close_response(response)
313
+ break
314
+ retry_after: float | None = None
315
+ if response is not None and response.status_code in {418, 429}:
316
+ raw_retry_after = response.headers.get("Retry-After")
317
+ if raw_retry_after is not None:
318
+ try:
319
+ retry_after = max(0.0, float(raw_retry_after))
320
+ except ValueError:
321
+ retry_after = None
322
+ exponential_cap = min(
323
+ self.retry_policy.max_delay_seconds,
324
+ self.retry_policy.base_delay_seconds * (2**attempt),
325
+ )
326
+ delay = (
327
+ retry_after if retry_after is not None else exponential_cap * self._random_value()
328
+ )
329
+ if response is not None:
330
+ _close_response(response)
331
+ self._sleep(delay)
332
+ status_code = last_error.status_code if isinstance(last_error, BinanceHTTPError) else None
333
+ raise BinanceHTTPError(
334
+ f"public Binance GET failed after {self.retry_policy.max_retries + 1} attempts",
335
+ status_code=status_code,
336
+ retry_exhausted=True,
337
+ ) from last_error
338
+
339
+ def _bounded_request_body(
340
+ self,
341
+ path: str,
342
+ params: Mapping[str, str | int],
343
+ *,
344
+ raw_root: Path,
345
+ rejected_dataset: str,
346
+ symbol: str,
347
+ requested_start_ns: int | None,
348
+ requested_end_ns: int | None,
349
+ max_response_bytes: int | None = None,
350
+ ) -> tuple[bytes, str, dict[str, str], int]:
351
+ """Read one bounded body, retrying recoverable transport interruptions.
352
+
353
+ Every interrupted attempt is persisted before retry. Payload/size
354
+ violations remain non-retryable because another identical response is
355
+ not evidence of a transient network failure.
356
+ """
357
+ byte_ceiling = max_response_bytes or self.max_response_bytes
358
+ for attempt in range(self.retry_policy.max_retries + 1):
359
+ response = self._request(path, params, stream_response=True)
360
+ observed_ts_ns = time.time_ns()
361
+ request_uri = str(response.url)
362
+ response_headers = _safe_response_headers(response.headers)
363
+ bounded_body = _read_bounded_response_body(
364
+ response,
365
+ max_response_bytes=byte_ceiling,
366
+ )
367
+ if bounded_body.error_message is None:
368
+ return (
369
+ bounded_body.content,
370
+ request_uri,
371
+ response_headers,
372
+ observed_ts_ns,
373
+ )
374
+
375
+ rejected_headers = _rejected_response_headers(response_headers, bounded_body)
376
+ rejected_headers["x-local-body-attempt"] = str(attempt + 1)
377
+ _write_raw_response(
378
+ bounded_body.content,
379
+ raw_root=raw_root,
380
+ dataset=rejected_dataset,
381
+ symbol=symbol,
382
+ request_uri=request_uri,
383
+ downloaded_at_utc=_iso_from_ns(observed_ts_ns),
384
+ requested_start_ns=requested_start_ns,
385
+ requested_end_ns=requested_end_ns,
386
+ response_headers=rejected_headers,
387
+ retained_evidence_budget=self.retained_evidence_budget,
388
+ )
389
+ if not bounded_body.retryable or attempt >= self.retry_policy.max_retries:
390
+ if bounded_body.retryable:
391
+ raise BinancePayloadError(bounded_body.error_message, transient=True)
392
+ raise BinanceResponseSizeLimitError(bounded_body.error_message)
393
+ exponential_cap = min(
394
+ self.retry_policy.max_delay_seconds,
395
+ self.retry_policy.base_delay_seconds * (2**attempt),
396
+ )
397
+ self._sleep(exponential_cap * self._random_value())
398
+ raise AssertionError("bounded response retry loop exhausted without a terminal result")
399
+
400
+ def fetch_exchange_info(self, *, symbol: str, raw_root: str | Path) -> SymbolMetadata:
401
+ """Fetch public symbol status and exact PRICE_FILTER/LOT_SIZE scales."""
402
+ symbol = symbol.upper()
403
+ content, request_uri, response_headers, observed_ts_ns = self._bounded_request_body(
404
+ "/api/v3/exchangeInfo",
405
+ {"symbol": symbol},
406
+ raw_root=Path(raw_root),
407
+ rejected_dataset="exchange_info_rejected",
408
+ symbol=symbol,
409
+ requested_start_ns=None,
410
+ requested_end_ns=None,
411
+ )
412
+ raw_page = _write_raw_response(
413
+ content,
414
+ raw_root=Path(raw_root),
415
+ dataset="exchange_info",
416
+ symbol=symbol,
417
+ request_uri=request_uri,
418
+ downloaded_at_utc=_iso_from_ns(observed_ts_ns),
419
+ requested_start_ns=None,
420
+ requested_end_ns=None,
421
+ response_headers=response_headers,
422
+ retained_evidence_budget=self.retained_evidence_budget,
423
+ )
424
+ try:
425
+ payload = cast(dict[str, Any], json.loads(content))
426
+ symbols = cast(list[dict[str, Any]], payload["symbols"])
427
+ if len(symbols) != 1 or str(symbols[0]["symbol"]).upper() != symbol:
428
+ raise BinanceMetadataContractError(
429
+ "exchangeInfo did not return exactly the requested symbol"
430
+ )
431
+ item = symbols[0]
432
+ filters = {
433
+ str(value["filterType"]): value
434
+ for value in cast(list[dict[str, Any]], item["filters"])
435
+ }
436
+ price_filter = filters["PRICE_FILTER"]
437
+ lot_filter = filters["LOT_SIZE"]
438
+ tick_size = Decimal(str(price_filter["tickSize"]))
439
+ lot_size = Decimal(str(lot_filter["stepSize"]))
440
+ if tick_size <= 0 or lot_size <= 0:
441
+ raise BinanceMetadataContractError(
442
+ "exchangeInfo returned a nonpositive tick or lot size"
443
+ )
444
+ return SymbolMetadata(
445
+ venue="binance_spot",
446
+ symbol=symbol,
447
+ status=str(item["status"]),
448
+ base_asset=str(item["baseAsset"]),
449
+ quote_asset=str(item["quoteAsset"]),
450
+ tick_size=tick_size,
451
+ lot_size=lot_size,
452
+ min_price=Decimal(str(price_filter["minPrice"])),
453
+ max_price=Decimal(str(price_filter["maxPrice"])),
454
+ min_quantity=Decimal(str(lot_filter["minQty"])),
455
+ max_quantity=Decimal(str(lot_filter["maxQty"])),
456
+ observed_ts_ns=observed_ts_ns,
457
+ source_artifact_id=raw_page.sha256,
458
+ source_path=raw_page.path,
459
+ source_manifest_path=raw_page.manifest_path,
460
+ )
461
+ except (BinanceMetadataContractError, BinanceResponseSizeLimitError):
462
+ raise
463
+ except BinancePayloadError as exc:
464
+ if exc.transient:
465
+ raise
466
+ raise BinanceMetadataContractError(str(exc)) from exc
467
+ except (InvalidOperation, KeyError, TypeError, ValueError) as exc:
468
+ raise BinanceMetadataContractError("malformed Binance exchangeInfo response") from exc
469
+
470
+ def fetch_depth_snapshot(
471
+ self,
472
+ *,
473
+ symbol: str,
474
+ raw_root: str | Path,
475
+ continuity_id: str,
476
+ tick_size: Decimal | None = None,
477
+ lot_size: Decimal | None = None,
478
+ limit: int = 5000,
479
+ ) -> BookSnapshot:
480
+ """Fetch a public REST anchor; it intentionally has no exchange event time."""
481
+ if limit not in {5, 10, 20, 50, 100, 500, 1000, 5000}:
482
+ raise ValueError("unsupported Binance depth snapshot limit")
483
+ symbol = symbol.upper()
484
+ if (tick_size is None) != (lot_size is None):
485
+ raise ValueError("tick_size and lot_size must be supplied together")
486
+ if tick_size is None or lot_size is None:
487
+ metadata = self.fetch_exchange_info(symbol=symbol, raw_root=raw_root)
488
+ tick_size = metadata.tick_size
489
+ lot_size = metadata.lot_size
490
+ request_ts_ns = time.time_ns()
491
+ content, request_uri, response_headers, received_ts_ns = self._bounded_request_body(
492
+ "/api/v3/depth",
493
+ {"symbol": symbol, "limit": limit},
494
+ raw_root=Path(raw_root),
495
+ rejected_dataset="depth_snapshots_rejected",
496
+ symbol=symbol,
497
+ requested_start_ns=None,
498
+ requested_end_ns=None,
499
+ )
500
+ raw_page = _write_raw_response(
501
+ content,
502
+ raw_root=Path(raw_root),
503
+ dataset="depth_snapshots",
504
+ symbol=symbol,
505
+ request_uri=request_uri,
506
+ downloaded_at_utc=_iso_from_ns(received_ts_ns),
507
+ requested_start_ns=None,
508
+ requested_end_ns=None,
509
+ response_headers=response_headers,
510
+ retained_evidence_budget=self.retained_evidence_budget,
511
+ )
512
+ try:
513
+ payload = cast(dict[str, Any], json.loads(content))
514
+ bids = tuple(
515
+ (
516
+ _scaled_integer(str(item[0]), tick_size, "bid price"),
517
+ _scaled_integer(str(item[1]), lot_size, "bid quantity"),
518
+ )
519
+ for item in payload["bids"]
520
+ )
521
+ asks = tuple(
522
+ (
523
+ _scaled_integer(str(item[0]), tick_size, "ask price"),
524
+ _scaled_integer(str(item[1]), lot_size, "ask quantity"),
525
+ )
526
+ for item in payload["asks"]
527
+ )
528
+ last_update_id = int(payload["lastUpdateId"])
529
+ except (KeyError, TypeError, ValueError) as exc:
530
+ raise BinancePayloadError("malformed Binance depth snapshot") from exc
531
+ return BookSnapshot(
532
+ venue="binance_spot",
533
+ symbol=symbol,
534
+ snapshot_id=raw_page.sha256,
535
+ request_ts_ns=request_ts_ns,
536
+ received_ts_ns=received_ts_ns,
537
+ available_ts_ns=received_ts_ns,
538
+ continuity_id=continuity_id,
539
+ last_update_id=last_update_id,
540
+ depth_limit=limit,
541
+ bids=bids,
542
+ asks=asks,
543
+ tick_size=float(tick_size),
544
+ lot_size=float(lot_size),
545
+ source_artifact_id=raw_page.sha256,
546
+ )
547
+
548
+
549
+ @dataclass(frozen=True, slots=True)
550
+ class _ParsedAggregateTrade:
551
+ aggregate_id: int
552
+ first_trade_id: int
553
+ last_trade_id: int
554
+ event_ts_ns: int
555
+ price: Decimal
556
+ quantity: Decimal
557
+ buyer_is_maker: bool
558
+
559
+
560
+ def _response_header(headers: Mapping[str, str], name: str) -> str | None:
561
+ normalized_name = name.lower()
562
+ for key, value in headers.items():
563
+ if str(key).lower() == normalized_name:
564
+ return str(value)
565
+ return None
566
+
567
+
568
+ @dataclass(frozen=True, slots=True)
569
+ class _BoundedResponseBody:
570
+ content: bytes
571
+ error_message: str | None
572
+ observed_bytes_lower_bound: int
573
+ retryable: bool = False
574
+
575
+
576
+ def _rejected_response_headers(
577
+ response_headers: Mapping[str, str],
578
+ body: _BoundedResponseBody,
579
+ ) -> dict[str, str]:
580
+ """Describe a bounded rejected response in its immutable raw sidecar."""
581
+ result = dict(response_headers)
582
+ result.update(
583
+ {
584
+ "x-local-capture-status": (
585
+ "rejected_partial_response" if body.content else "rejected_headers_only"
586
+ ),
587
+ "x-local-captured-bytes": str(len(body.content)),
588
+ "x-local-observed-bytes-lower-bound": str(body.observed_bytes_lower_bound),
589
+ "x-local-rejection-reason": body.error_message or "unknown",
590
+ }
591
+ )
592
+ return result
593
+
594
+
595
+ def _read_bounded_response_body(
596
+ response: requests.Response,
597
+ *,
598
+ max_response_bytes: int,
599
+ ) -> _BoundedResponseBody:
600
+ """Read one response with a hard prefix bound on the production transport.
601
+
602
+ A real ``requests.Response`` exposes ``iter_content`` and is consumed a
603
+ chunk at a time. Injected legacy test responses without that method fall
604
+ back to their already-materialized ``content`` attribute for compatibility.
605
+ """
606
+ headers = response.headers
607
+ declared = _response_header(headers, "content-length")
608
+ try:
609
+ if declared is not None:
610
+ try:
611
+ declared_size = int(declared)
612
+ except ValueError:
613
+ return _BoundedResponseBody(
614
+ content=b"",
615
+ error_message="aggregate-trade response has invalid Content-Length",
616
+ observed_bytes_lower_bound=0,
617
+ )
618
+ if declared_size < 0:
619
+ return _BoundedResponseBody(
620
+ content=b"",
621
+ error_message="aggregate-trade response has invalid Content-Length",
622
+ observed_bytes_lower_bound=0,
623
+ )
624
+ if declared_size > max_response_bytes:
625
+ return _BoundedResponseBody(
626
+ content=b"",
627
+ error_message=(
628
+ "aggregate-trade response Content-Length exceeded the response-byte ceiling"
629
+ ),
630
+ observed_bytes_lower_bound=0,
631
+ )
632
+
633
+ iter_content = getattr(response, "iter_content", None)
634
+ if callable(iter_content):
635
+ chunks: list[bytes] = []
636
+ captured_bytes = 0
637
+ chunk_size = min(64 * 1024, max_response_bytes + 1)
638
+ iterator = cast(
639
+ Callable[..., Iterator[object]],
640
+ iter_content,
641
+ )
642
+ try:
643
+ for raw_chunk in iterator(chunk_size=chunk_size):
644
+ if not raw_chunk:
645
+ continue
646
+ if not isinstance(raw_chunk, bytes):
647
+ return _BoundedResponseBody(
648
+ content=b"".join(chunks),
649
+ error_message=(
650
+ "aggregate-trade response yielded a non-bytes body chunk"
651
+ ),
652
+ observed_bytes_lower_bound=captured_bytes,
653
+ )
654
+ remaining = max_response_bytes - captured_bytes
655
+ if len(raw_chunk) > remaining:
656
+ if remaining:
657
+ chunks.append(raw_chunk[:remaining])
658
+ return _BoundedResponseBody(
659
+ content=b"".join(chunks),
660
+ error_message=(
661
+ "aggregate-trade response body exceeded the response-byte ceiling"
662
+ ),
663
+ observed_bytes_lower_bound=captured_bytes + len(raw_chunk),
664
+ )
665
+ chunks.append(raw_chunk)
666
+ captured_bytes += len(raw_chunk)
667
+ except requests.RequestException as exc:
668
+ return _BoundedResponseBody(
669
+ content=b"".join(chunks),
670
+ error_message=(
671
+ "aggregate-trade response body was interrupted after "
672
+ f"{captured_bytes} bytes: {type(exc).__name__}"
673
+ ),
674
+ observed_bytes_lower_bound=captured_bytes,
675
+ retryable=True,
676
+ )
677
+ return _BoundedResponseBody(
678
+ content=b"".join(chunks),
679
+ error_message=None,
680
+ observed_bytes_lower_bound=captured_bytes,
681
+ )
682
+
683
+ # Compatibility path for minimal injected responses. This is not used
684
+ # by requests.Response and therefore is not the production transport.
685
+ content = bytes(response.content)
686
+ if len(content) > max_response_bytes:
687
+ return _BoundedResponseBody(
688
+ content=content[:max_response_bytes],
689
+ error_message=("aggregate-trade response body exceeded the response-byte ceiling"),
690
+ observed_bytes_lower_bound=len(content),
691
+ )
692
+ return _BoundedResponseBody(
693
+ content=content,
694
+ error_message=None,
695
+ observed_bytes_lower_bound=len(content),
696
+ )
697
+ finally:
698
+ _close_response(response)
699
+
700
+
701
+ def _parse_aggregate_trade_page(
702
+ content: bytes,
703
+ *,
704
+ request_limit: int,
705
+ ) -> list[_ParsedAggregateTrade]:
706
+ try:
707
+ decoded = json.loads(content)
708
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
709
+ raise BinancePayloadError("malformed Binance aggregate-trade page") from exc
710
+ if not isinstance(decoded, list):
711
+ raise BinancePayloadError("malformed Binance aggregate-trade page")
712
+ if len(decoded) > request_limit:
713
+ raise BinancePayloadError("aggregate-trade response exceeded the requested page-size bound")
714
+
715
+ parsed: list[_ParsedAggregateTrade] = []
716
+ previous_id: int | None = None
717
+ previous_ts_ns: int | None = None
718
+ for raw_item in decoded:
719
+ if not isinstance(raw_item, dict):
720
+ raise BinancePayloadError("malformed aggregate-trade record")
721
+ item = cast(dict[str, Any], raw_item)
722
+ try:
723
+ aggregate_id = int(item["a"])
724
+ first_trade_id = int(item.get("f", aggregate_id))
725
+ last_trade_id = int(item.get("l", aggregate_id))
726
+ event_ts_ns = _event_timestamp_ns(int(item["T"]), "ms")
727
+ price = Decimal(str(item["p"]))
728
+ quantity = Decimal(str(item["q"]))
729
+ buyer_is_maker = item["m"]
730
+ except (KeyError, InvalidOperation, TypeError, ValueError) as exc:
731
+ raise BinancePayloadError("malformed aggregate-trade record") from exc
732
+ if not isinstance(buyer_is_maker, bool):
733
+ raise BinancePayloadError("malformed aggregate-trade record")
734
+ if aggregate_id < 0 or first_trade_id < 0 or last_trade_id < first_trade_id:
735
+ raise BinancePayloadError("invalid aggregate-trade identifiers")
736
+ if previous_id is not None and aggregate_id <= previous_id:
737
+ raise BinancePayloadError("aggregate-trade page IDs are not strictly increasing")
738
+ if previous_ts_ns is not None and event_ts_ns < previous_ts_ns:
739
+ raise BinancePayloadError("aggregate-trade page event times are not ordered")
740
+ parsed.append(
741
+ _ParsedAggregateTrade(
742
+ aggregate_id=aggregate_id,
743
+ first_trade_id=first_trade_id,
744
+ last_trade_id=last_trade_id,
745
+ event_ts_ns=event_ts_ns,
746
+ price=price,
747
+ quantity=quantity,
748
+ buyer_is_maker=buyer_is_maker,
749
+ )
750
+ )
751
+ previous_id = aggregate_id
752
+ previous_ts_ns = event_ts_ns
753
+ return parsed
754
+
755
+
756
+ class BinanceTradeBatchStream(Iterator[pa.RecordBatch]):
757
+ """Lazy, page-bounded iterator over normalized aggregate trades.
758
+
759
+ No HTTP request is made until the first call to :func:`next`. Each
760
+ nonempty batch comes from one retained raw response and has no more rows
761
+ than the downloader's request limit. The iterator retains only terminal
762
+ counters and the latest raw-page descriptor; callers that need every raw
763
+ descriptor can process them incrementally with ``on_raw_page``. Production
764
+ HTTP responses are consumed incrementally and stop after the first chunk
765
+ crossing ``max_response_bytes``. Minimal injected responses that do not
766
+ implement ``iter_content`` retain a compatibility-only ``content`` fallback.
767
+ """
768
+
769
+ def __init__(
770
+ self,
771
+ *,
772
+ client: BinancePublicClient,
773
+ raw_root: Path,
774
+ request_limit: int,
775
+ max_response_bytes: int,
776
+ tick_size: Decimal | None,
777
+ lot_size: Decimal | None,
778
+ symbol: str,
779
+ start_ts_ns: int,
780
+ end_ts_ns: int,
781
+ max_events: int,
782
+ on_raw_page: Callable[[RawPage], None] | None,
783
+ ) -> None:
784
+ if end_ts_ns <= start_ts_ns:
785
+ raise ValueError("end_ts_ns must be after start_ts_ns")
786
+ if max_events < 1:
787
+ raise ValueError("max_events must be positive")
788
+ self._client = client
789
+ self._raw_root = raw_root
790
+ self._request_limit = request_limit
791
+ self._max_response_bytes = max_response_bytes
792
+ self._tick_size = tick_size
793
+ self._lot_size = lot_size
794
+ self._symbol = symbol.upper()
795
+ self._start_ts_ns = start_ts_ns
796
+ self._end_ts_ns = end_ts_ns
797
+ self._max_events = max_events
798
+ self._on_raw_page = on_raw_page
799
+ self._params: dict[str, str | int] = {
800
+ "symbol": self._symbol,
801
+ "startTime": start_ts_ns // _NS_PER_MILLISECOND,
802
+ "endTime": (end_ts_ns - 1) // _NS_PER_MILLISECOND,
803
+ "limit": request_limit,
804
+ }
805
+ self._rows_yielded = 0
806
+ self._raw_page_count = 0
807
+ self._last_raw_page: RawPage | None = None
808
+ self._previous_last_id: int | None = None
809
+ self._previous_last_event_ts_ns: int | None = None
810
+ self._summary: BinanceTradeStreamSummary | None = None
811
+ self._failed = False
812
+
813
+ def __iter__(self) -> BinanceTradeBatchStream:
814
+ return self
815
+
816
+ @property
817
+ def rows_yielded(self) -> int:
818
+ return self._rows_yielded
819
+
820
+ @property
821
+ def raw_page_count(self) -> int:
822
+ return self._raw_page_count
823
+
824
+ @property
825
+ def last_raw_page(self) -> RawPage | None:
826
+ return self._last_raw_page
827
+
828
+ @property
829
+ def summary(self) -> BinanceTradeStreamSummary:
830
+ """Return terminal metadata, failing closed before normal exhaustion."""
831
+ if self._summary is None:
832
+ raise RuntimeError("trade stream summary is unavailable before normal exhaustion")
833
+ return self._summary
834
+
835
+ def __next__(self) -> pa.RecordBatch:
836
+ if self._summary is not None:
837
+ raise StopIteration
838
+ if self._failed:
839
+ raise RuntimeError("trade stream cannot resume after a previous failure")
840
+ try:
841
+ return self._next_batch()
842
+ except StopIteration:
843
+ raise
844
+ except Exception:
845
+ self._failed = True
846
+ raise
847
+
848
+ def _resolve_scales(self) -> tuple[Decimal, Decimal]:
849
+ if self._tick_size is None or self._lot_size is None:
850
+ metadata = self._client.fetch_exchange_info(
851
+ symbol=self._symbol,
852
+ raw_root=self._raw_root,
853
+ )
854
+ self._tick_size = metadata.tick_size
855
+ self._lot_size = metadata.lot_size
856
+ return self._tick_size, self._lot_size
857
+
858
+ def _record_page(self, raw_page: RawPage) -> None:
859
+ self._raw_page_count += 1
860
+ self._last_raw_page = raw_page
861
+ if self._on_raw_page is not None:
862
+ self._on_raw_page(raw_page)
863
+
864
+ def _finish(self, reason: BinanceTradeStreamStopReason) -> None:
865
+ self._summary = BinanceTradeStreamSummary(
866
+ requested_start_ns=self._start_ts_ns,
867
+ requested_end_ns=self._end_ts_ns,
868
+ rows_yielded=self._rows_yielded,
869
+ raw_page_count=self._raw_page_count,
870
+ stop_reason=reason,
871
+ complete_range=(
872
+ reason is not BinanceTradeStreamStopReason.EVENT_CAP and self._rows_yielded > 0
873
+ ),
874
+ last_raw_page=self._last_raw_page,
875
+ )
876
+
877
+ def _normalize_records(
878
+ self,
879
+ items: list[_ParsedAggregateTrade],
880
+ *,
881
+ source_artifact_id: str,
882
+ tick_size: Decimal,
883
+ lot_size: Decimal,
884
+ ) -> list[dict[str, object]]:
885
+ records: list[dict[str, object]] = []
886
+ for item in items:
887
+ price_ticks = _scaled_integer(item.price, tick_size, "trade price")
888
+ quantity_lots = _scaled_integer(item.quantity, lot_size, "trade quantity")
889
+ price = float(item.price)
890
+ quantity = float(item.quantity)
891
+ records.append(
892
+ {
893
+ "schema_version": SCHEMA_VERSION,
894
+ "venue": "binance_spot",
895
+ "symbol": self._symbol,
896
+ "event_ts_ns": item.event_ts_ns,
897
+ "received_ts_ns": None,
898
+ "available_ts_ns": item.event_ts_ns,
899
+ "availability_basis": "exchange_event_time_proxy",
900
+ "capture_seq": None,
901
+ "continuity_id": None,
902
+ "trade_id": item.aggregate_id,
903
+ "first_trade_id": item.first_trade_id,
904
+ "last_trade_id": item.last_trade_id,
905
+ "price_ticks": price_ticks,
906
+ "quantity_lots": quantity_lots,
907
+ "tick_size": float(tick_size),
908
+ "lot_size": float(lot_size),
909
+ "price": price,
910
+ "quantity": quantity,
911
+ "quote_quantity": price * quantity,
912
+ "aggressor_side": "sell" if item.buyer_is_maker else "buy",
913
+ "buyer_is_maker": item.buyer_is_maker,
914
+ "source_artifact_id": source_artifact_id,
915
+ }
916
+ )
917
+ return records
918
+
919
+ def _next_batch(self) -> pa.RecordBatch:
920
+ tick_size, lot_size = self._resolve_scales()
921
+ while True:
922
+ content, request_uri, response_headers, downloaded_ns = (
923
+ self._client._bounded_request_body(
924
+ "/api/v3/aggTrades",
925
+ self._params,
926
+ raw_root=self._raw_root,
927
+ rejected_dataset="agg_trades_rejected",
928
+ symbol=self._symbol,
929
+ requested_start_ns=self._start_ts_ns,
930
+ requested_end_ns=self._end_ts_ns,
931
+ max_response_bytes=self._max_response_bytes,
932
+ )
933
+ )
934
+ raw_page_base = _write_raw_response(
935
+ content,
936
+ raw_root=self._raw_root,
937
+ dataset="agg_trades",
938
+ symbol=self._symbol,
939
+ request_uri=request_uri,
940
+ downloaded_at_utc=_iso_from_ns(downloaded_ns),
941
+ requested_start_ns=self._start_ts_ns,
942
+ requested_end_ns=self._end_ts_ns,
943
+ response_headers=response_headers,
944
+ retained_evidence_budget=self._client.retained_evidence_budget,
945
+ )
946
+ parsed = _parse_aggregate_trade_page(content, request_limit=self._request_limit)
947
+ raw_page = RawPage(
948
+ path=raw_page_base.path,
949
+ manifest_path=raw_page_base.manifest_path,
950
+ sha256=raw_page_base.sha256,
951
+ request_uri=raw_page_base.request_uri,
952
+ row_count=len(parsed),
953
+ )
954
+ self._record_page(raw_page)
955
+ if not parsed:
956
+ self._finish(BinanceTradeStreamStopReason.EMPTY_PAGE)
957
+ raise StopIteration
958
+
959
+ first = parsed[0]
960
+ last = parsed[-1]
961
+ if self._previous_last_id is not None and first.aggregate_id <= self._previous_last_id:
962
+ raise BinancePayloadError("aggregate-trade pagination did not advance")
963
+ if (
964
+ self._previous_last_event_ts_ns is not None
965
+ and first.event_ts_ns < self._previous_last_event_ts_ns
966
+ ):
967
+ raise BinancePayloadError("aggregate-trade pages are not time ordered")
968
+ self._previous_last_id = last.aggregate_id
969
+ self._previous_last_event_ts_ns = last.event_ts_ns
970
+
971
+ in_range = [
972
+ item for item in parsed if self._start_ts_ns <= item.event_ts_ns < self._end_ts_ns
973
+ ]
974
+ remaining = self._max_events - self._rows_yielded
975
+ selected = in_range[:remaining]
976
+ records = self._normalize_records(
977
+ selected,
978
+ source_artifact_id=raw_page.sha256,
979
+ tick_size=tick_size,
980
+ lot_size=lot_size,
981
+ )
982
+ self._rows_yielded += len(records)
983
+
984
+ terminal_reason: BinanceTradeStreamStopReason | None = None
985
+ if len(in_range) >= remaining:
986
+ terminal_reason = BinanceTradeStreamStopReason.EVENT_CAP
987
+ elif last.event_ts_ns >= self._end_ts_ns:
988
+ terminal_reason = BinanceTradeStreamStopReason.RANGE_END
989
+ elif len(parsed) < self._request_limit:
990
+ terminal_reason = BinanceTradeStreamStopReason.SHORT_PAGE
991
+ else:
992
+ self._params = {
993
+ "symbol": self._symbol,
994
+ "fromId": last.aggregate_id + 1,
995
+ "limit": self._request_limit,
996
+ }
997
+
998
+ if terminal_reason is not None:
999
+ self._finish(terminal_reason)
1000
+ if records:
1001
+ table = table_from_records("trades", records)
1002
+ batches = table.to_batches(max_chunksize=self._request_limit)
1003
+ if len(batches) != 1:
1004
+ raise BinancePayloadError("failed to construct one bounded trade batch")
1005
+ return batches[0]
1006
+ if terminal_reason is not None:
1007
+ raise StopIteration
1008
+
1009
+
1010
+ class BinanceHistoricalTradeDownloader:
1011
+ """Historical aggregate-trade downloader with lazy and guarded materialized APIs."""
1012
+
1013
+ def __init__(
1014
+ self,
1015
+ *,
1016
+ client: BinancePublicClient,
1017
+ raw_root: str | Path,
1018
+ request_limit: int = 1000,
1019
+ max_response_bytes: int = 8 * 1024 * 1024,
1020
+ materialization_max_rows: int = 100_000,
1021
+ tick_size: Decimal | None = None,
1022
+ lot_size: Decimal | None = None,
1023
+ ) -> None:
1024
+ if not 1 <= request_limit <= 1000:
1025
+ raise ValueError("request_limit must be in [1, 1000]")
1026
+ if max_response_bytes < 1:
1027
+ raise ValueError("max_response_bytes must be positive")
1028
+ if materialization_max_rows < 1:
1029
+ raise ValueError("materialization_max_rows must be positive")
1030
+ self.client = client
1031
+ self.raw_root = Path(raw_root)
1032
+ self.request_limit = request_limit
1033
+ self.max_response_bytes = max_response_bytes
1034
+ self.materialization_max_rows = materialization_max_rows
1035
+ if (tick_size is None) != (lot_size is None):
1036
+ raise ValueError("tick_size and lot_size must be supplied together")
1037
+ self.tick_size = tick_size
1038
+ self.lot_size = lot_size
1039
+
1040
+ def stream(
1041
+ self,
1042
+ *,
1043
+ symbol: str,
1044
+ start_ts_ns: int,
1045
+ end_ts_ns: int,
1046
+ max_events: int,
1047
+ on_raw_page: Callable[[RawPage], None] | None = None,
1048
+ ) -> BinanceTradeBatchStream:
1049
+ """Create a lazy ``[start, end)`` page stream without making an HTTP call."""
1050
+ return BinanceTradeBatchStream(
1051
+ client=self.client,
1052
+ raw_root=self.raw_root,
1053
+ request_limit=self.request_limit,
1054
+ max_response_bytes=self.max_response_bytes,
1055
+ tick_size=self.tick_size,
1056
+ lot_size=self.lot_size,
1057
+ symbol=symbol,
1058
+ start_ts_ns=start_ts_ns,
1059
+ end_ts_ns=end_ts_ns,
1060
+ max_events=max_events,
1061
+ on_raw_page=on_raw_page,
1062
+ )
1063
+
1064
+ def download(
1065
+ self,
1066
+ *,
1067
+ symbol: str,
1068
+ start_ts_ns: int,
1069
+ end_ts_ns: int,
1070
+ max_events: int,
1071
+ ) -> BinanceDownloadResult:
1072
+ """Materialize the lazy stream for backwards-compatible small downloads."""
1073
+ if max_events > self.materialization_max_rows:
1074
+ raise ValueError(
1075
+ "max_events exceeds the guarded download() materialization limit; "
1076
+ "consume stream() incrementally for larger histories"
1077
+ )
1078
+ raw_pages: list[RawPage] = []
1079
+ stream = self.stream(
1080
+ symbol=symbol,
1081
+ start_ts_ns=start_ts_ns,
1082
+ end_ts_ns=end_ts_ns,
1083
+ max_events=max_events,
1084
+ on_raw_page=raw_pages.append,
1085
+ )
1086
+ batches = list(stream)
1087
+ trades = (
1088
+ pa.Table.from_batches(batches, schema=get_schema("trades"))
1089
+ if batches
1090
+ else table_from_records("trades", [])
1091
+ )
1092
+ return BinanceDownloadResult(
1093
+ trades=trades,
1094
+ raw_pages=tuple(raw_pages),
1095
+ requested_start_ns=start_ts_ns,
1096
+ requested_end_ns=end_ts_ns,
1097
+ complete_range=stream.summary.complete_range,
1098
+ )
1099
+
1100
+
1101
+ def _iso_from_ns(timestamp_ns: int) -> str:
1102
+ seconds, nanoseconds = divmod(timestamp_ns, 1_000_000_000)
1103
+ base = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(seconds))
1104
+ return f"{base}.{nanoseconds:09d}Z"
1105
+
1106
+
1107
+ def _write_raw_response(
1108
+ content: bytes,
1109
+ *,
1110
+ raw_root: Path,
1111
+ dataset: str,
1112
+ symbol: str,
1113
+ request_uri: str,
1114
+ downloaded_at_utc: str,
1115
+ requested_start_ns: int | None,
1116
+ requested_end_ns: int | None,
1117
+ response_headers: Mapping[str, str],
1118
+ retained_evidence_budget: RetainedEvidenceBudget | None = None,
1119
+ ) -> RawPage:
1120
+ checksum = hashlib.sha256(content).hexdigest()
1121
+ directory = raw_root / "binance_spot" / dataset / symbol.upper()
1122
+ destination = directory / f"{checksum}.json"
1123
+ if retained_evidence_budget is not None:
1124
+ retained_evidence_budget.assert_contains(destination)
1125
+ transaction = (
1126
+ retained_evidence_budget.write_transaction()
1127
+ if retained_evidence_budget is not None
1128
+ else nullcontext()
1129
+ )
1130
+ with transaction:
1131
+ directory.mkdir(parents=True, exist_ok=True)
1132
+ body_reservation = None
1133
+ created_body = False
1134
+ if destination.exists():
1135
+ if sha256_file(destination) != checksum:
1136
+ raise BinancePayloadError(f"raw content-address collision at {destination}")
1137
+ else:
1138
+ if retained_evidence_budget is not None:
1139
+ body_reservation = retained_evidence_budget.reserve(
1140
+ len(content),
1141
+ label=f"raw Binance response {destination.name}",
1142
+ )
1143
+ try:
1144
+ handle, temporary_name = tempfile.mkstemp(
1145
+ dir=directory,
1146
+ prefix=".raw-",
1147
+ suffix=".tmp",
1148
+ )
1149
+ except BaseException:
1150
+ if body_reservation is not None and body_reservation.active:
1151
+ body_reservation.release()
1152
+ raise
1153
+ try:
1154
+ with os.fdopen(handle, "wb") as stream:
1155
+ stream.write(content)
1156
+ stream.flush()
1157
+ os.fsync(stream.fileno())
1158
+ os.replace(temporary_name, destination)
1159
+ _fsync_directory(directory)
1160
+ created_body = True
1161
+ except BaseException:
1162
+ Path(temporary_name).unlink(missing_ok=True)
1163
+ if body_reservation is not None and body_reservation.active:
1164
+ body_reservation.release()
1165
+ raise
1166
+ try:
1167
+ manifest_path, _ = write_source_manifest(
1168
+ destination,
1169
+ source="binance_spot_public_api",
1170
+ source_uri=request_uri,
1171
+ downloaded_at_utc=downloaded_at_utc,
1172
+ requested_start_ns=requested_start_ns,
1173
+ requested_end_ns=requested_end_ns,
1174
+ response_headers=response_headers,
1175
+ retained_evidence_budget=retained_evidence_budget,
1176
+ )
1177
+ if body_reservation is not None:
1178
+ body_reservation.commit()
1179
+ except BaseException:
1180
+ if created_body:
1181
+ destination.unlink(missing_ok=True)
1182
+ if body_reservation is not None and body_reservation.active:
1183
+ body_reservation.release()
1184
+ raise
1185
+ return RawPage(
1186
+ path=destination,
1187
+ manifest_path=manifest_path,
1188
+ sha256=checksum,
1189
+ request_uri=request_uri,
1190
+ row_count=0,
1191
+ )
1192
+
1193
+
1194
+ def parse_depth_message(
1195
+ raw_message: str | bytes,
1196
+ *,
1197
+ received_ts_ns: int,
1198
+ capture_seq: int,
1199
+ continuity_id: str,
1200
+ tick_size: Decimal = Decimal("0.00000001"),
1201
+ lot_size: Decimal = Decimal("0.00000001"),
1202
+ timestamp_unit: Literal["ms", "us"] = "us",
1203
+ ) -> DepthDelta:
1204
+ """Normalize raw or combined-stream Spot ``U/u`` depth payloads."""
1205
+ raw_bytes = raw_message.encode() if isinstance(raw_message, str) else raw_message
1206
+ try:
1207
+ decoded = json.loads(raw_bytes)
1208
+ payload = decoded.get("data", decoded)
1209
+ if payload.get("e") != "depthUpdate":
1210
+ raise BinancePayloadError(f"unexpected websocket event: {payload.get('e')!r}")
1211
+ symbol = str(payload["s"]).upper()
1212
+ bids = tuple(
1213
+ (
1214
+ _scaled_integer(str(item[0]), tick_size, "bid price"),
1215
+ _scaled_integer(str(item[1]), lot_size, "bid quantity"),
1216
+ )
1217
+ for item in payload["b"]
1218
+ )
1219
+ asks = tuple(
1220
+ (
1221
+ _scaled_integer(str(item[0]), tick_size, "ask price"),
1222
+ _scaled_integer(str(item[1]), lot_size, "ask quantity"),
1223
+ )
1224
+ for item in payload["a"]
1225
+ )
1226
+ event_ts_ns = _event_timestamp_ns(int(payload["E"]), timestamp_unit)
1227
+ first_update_id = int(payload["U"])
1228
+ last_update_id = int(payload["u"])
1229
+ previous = payload.get("pu")
1230
+ except BinancePayloadError:
1231
+ raise
1232
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
1233
+ raise BinancePayloadError("malformed Binance depth websocket message") from exc
1234
+ return DepthDelta(
1235
+ venue="binance_spot",
1236
+ symbol=symbol,
1237
+ event_ts_ns=event_ts_ns,
1238
+ received_ts_ns=received_ts_ns,
1239
+ available_ts_ns=received_ts_ns,
1240
+ availability_basis="local_receive_time",
1241
+ capture_seq=capture_seq,
1242
+ continuity_id=continuity_id,
1243
+ first_update_id=first_update_id,
1244
+ last_update_id=last_update_id,
1245
+ previous_update_id=int(previous) if previous is not None else None,
1246
+ bids=bids,
1247
+ asks=asks,
1248
+ tick_size=float(tick_size),
1249
+ lot_size=float(lot_size),
1250
+ source_artifact_id=hashlib.sha256(raw_bytes).hexdigest(),
1251
+ )
1252
+
1253
+
1254
+ class BinanceLiveDepthCollector:
1255
+ """Optional reconnecting collector for public diff-depth streams."""
1256
+
1257
+ def __init__(
1258
+ self,
1259
+ *,
1260
+ symbols: tuple[str, ...],
1261
+ websocket_base_url: str = "wss://data-stream.binance.vision",
1262
+ tick_size: Decimal = Decimal("0.00000001"),
1263
+ lot_size: Decimal = Decimal("0.00000001"),
1264
+ max_reconnects: int = 5,
1265
+ connect_factory: ConnectFactory | None = None,
1266
+ on_raw_frame: RawDepthFrameCallback | None = None,
1267
+ ) -> None:
1268
+ if not symbols:
1269
+ raise ValueError("symbols must not be empty")
1270
+ self.symbols = tuple(symbol.upper() for symbol in symbols)
1271
+ streams = "/".join(f"{symbol.lower()}@depth@100ms" for symbol in self.symbols)
1272
+ self.url = f"{websocket_base_url.rstrip('/')}/stream?streams={streams}&timeUnit=MICROSECOND"
1273
+ self.tick_size = tick_size
1274
+ self.lot_size = lot_size
1275
+ self.max_reconnects = max_reconnects
1276
+ self._connect_factory = connect_factory or cast(ConnectFactory, websockets.connect)
1277
+ self._on_raw_frame = on_raw_frame
1278
+
1279
+ async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]:
1280
+ """Yield exact raw payloads plus normalized deltas across continuity epochs."""
1281
+ capture_seq = 0
1282
+ yielded = 0
1283
+ reconnect = 0
1284
+ while reconnect <= self.max_reconnects:
1285
+ continuity_id = f"binance-live-{time.time_ns()}-{reconnect}"
1286
+ try:
1287
+ async with self._connect_factory(self.url) as connection:
1288
+ async for raw in connection:
1289
+ received_ts_ns = time.time_ns()
1290
+ if isinstance(raw, bytes):
1291
+ raw_bytes = raw
1292
+ was_text = False
1293
+ else:
1294
+ raw_bytes = raw.encode("utf-8")
1295
+ was_text = True
1296
+ if self._on_raw_frame is not None:
1297
+ self._on_raw_frame(
1298
+ RawDepthFrame(
1299
+ payload=raw_bytes,
1300
+ was_text=was_text,
1301
+ received_ts_ns=received_ts_ns,
1302
+ capture_seq=capture_seq,
1303
+ continuity_id=continuity_id,
1304
+ )
1305
+ )
1306
+ raw_text = raw_bytes.decode("utf-8") if isinstance(raw, bytes) else raw
1307
+ delta = parse_depth_message(
1308
+ raw_text,
1309
+ received_ts_ns=received_ts_ns,
1310
+ capture_seq=capture_seq,
1311
+ continuity_id=continuity_id,
1312
+ tick_size=self.tick_size,
1313
+ lot_size=self.lot_size,
1314
+ timestamp_unit="us",
1315
+ )
1316
+ yield CapturedDepth(raw_payload=raw_text, delta=delta)
1317
+ capture_seq += 1
1318
+ yielded += 1
1319
+ if max_messages is not None and yielded >= max_messages:
1320
+ return
1321
+ reconnect += 1
1322
+ except (OSError, WebSocketException):
1323
+ reconnect += 1
1324
+ if reconnect > self.max_reconnects:
1325
+ raise
1326
+ await asyncio.sleep(min(30.0, 0.5 * (2 ** (reconnect - 1))))
1327
+
1328
+
1329
+ def depth_deltas_table(captured: tuple[CapturedDepth, ...] | list[CapturedDepth]) -> pa.Table:
1330
+ return table_from_records("depth_deltas", [item.delta.to_record() for item in captured])
Microstructure/src/microstructure/data/binance_archive.py ADDED
@@ -0,0 +1,1459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded acquisition and one-shot normalization of Binance daily trade archives.
2
+
3
+ The acquisition boundary deliberately stops after authenticating the exact ZIP
4
+ bytes and inspecting bounded ZIP metadata. CSV rows are not opened until a
5
+ caller explicitly requests a normalized stream. That separation lets a study
6
+ write an analysis lock before either held-out archive is exposed to research
7
+ code.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import math
14
+ import os
15
+ import random
16
+ import re
17
+ import stat
18
+ import struct
19
+ import tempfile
20
+ import time
21
+ import zipfile
22
+ from collections.abc import Callable, Generator, Iterator, Mapping
23
+ from contextlib import nullcontext
24
+ from dataclasses import dataclass
25
+ from datetime import UTC, date, datetime, timedelta
26
+ from decimal import Decimal, InvalidOperation
27
+ from pathlib import Path
28
+ from typing import Any, BinaryIO, Literal, Protocol, cast
29
+ from urllib.parse import urlsplit
30
+
31
+ import pyarrow as pa # type: ignore[import-untyped]
32
+ import requests
33
+
34
+ from microstructure.data.binance import RetryPolicy
35
+ from microstructure.data.evidence_budget import (
36
+ EvidenceBudgetError,
37
+ EvidenceReservation,
38
+ RetainedEvidenceBudget,
39
+ )
40
+ from microstructure.data.schemas import SCHEMA_VERSION, table_from_records
41
+ from microstructure.data.storage import write_source_manifest
42
+ from microstructure.provenance import sha256_file, utc_now_iso
43
+
44
+ _DEFAULT_BASE_URL = "https://data.binance.vision"
45
+ _SAFE_SYMBOL = re.compile(r"^[A-Z0-9]{2,20}$")
46
+ _SAFE_ARCHIVE_NAME = re.compile(r"^[A-Z0-9]{2,20}-aggTrades-\d{4}-\d{2}-\d{2}\.zip$")
47
+ _CHECKSUM_LINE = re.compile(rb"([0-9a-f]{64}) ([A-Za-z0-9_.-]+)(?:\r\n|\n)?")
48
+ _UNSIGNED_INTEGER = re.compile(rb"(?:0|[1-9][0-9]*)")
49
+ _EOCD_SIGNATURE = b"PK\x05\x06"
50
+ _EOCD_STRUCT = struct.Struct("<4s4H2LH")
51
+ _LOCAL_FILE_SIGNATURE = b"PK\x03\x04"
52
+ _LOCAL_FILE_STRUCT = struct.Struct("<4s5H3L2H")
53
+ _MAX_EOCD_BYTES = 22 + 65_535
54
+ _MAX_ZIP_ENTRY_METADATA_BYTES = 256 * 1_024
55
+ _MAX_DECIMAL_FIELD_BYTES = 64
56
+ _MAX_INT64 = (1 << 63) - 1
57
+ _MICROSECOND_ARCHIVE_START = date(2025, 1, 1)
58
+
59
+
60
+ class BinanceArchiveError(RuntimeError):
61
+ """Base failure for immutable Binance archive acquisition or parsing."""
62
+
63
+
64
+ class BinanceArchiveHTTPError(BinanceArchiveError):
65
+ """Raised when a bounded public archive response cannot be acquired."""
66
+
67
+ def __init__(
68
+ self,
69
+ message: str,
70
+ *,
71
+ status_code: int | None = None,
72
+ retry_exhausted: bool = False,
73
+ ) -> None:
74
+ super().__init__(message)
75
+ self.status_code = status_code
76
+ self.retry_exhausted = retry_exhausted
77
+
78
+
79
+ class BinanceArchivePayloadError(BinanceArchiveError):
80
+ """Raised when archive bytes or CSV rows violate their frozen contract."""
81
+
82
+
83
+ ArchiveAcquisitionReasonCode = Literal[
84
+ "CHECKSUM_CONTRACT",
85
+ "ZIP_CONTRACT",
86
+ "RESPONSE_SIZE_LIMIT",
87
+ ]
88
+
89
+
90
+ class BinanceArchiveContractError(BinanceArchivePayloadError):
91
+ """A deterministic raw archive/checksum contract failure before CSV open."""
92
+
93
+ def __init__(self, message: str, *, reason_code: ArchiveAcquisitionReasonCode) -> None:
94
+ super().__init__(message)
95
+ self.reason_code = reason_code
96
+
97
+
98
+ class _RetryableDownloadError(BinanceArchiveHTTPError):
99
+ """Internal marker for one recoverable, already-evidenced HTTP attempt."""
100
+
101
+ def __init__(self, message: str, *, retry_after_seconds: float | None = None) -> None:
102
+ super().__init__(message)
103
+ self.retry_after_seconds = retry_after_seconds
104
+
105
+
106
+ class _StreamingResponse(Protocol):
107
+ status_code: int
108
+ headers: Mapping[str, str]
109
+ url: str
110
+
111
+ def iter_content(self, *, chunk_size: int) -> Iterator[bytes]: ...
112
+
113
+ def close(self) -> object: ...
114
+
115
+
116
+ class _StreamingSession(Protocol):
117
+ def get(self, url: str, *, timeout: float, stream: bool) -> _StreamingResponse: ...
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class DailyArchiveRequest:
122
+ """One exact official UTC-day archive plus normalization scales."""
123
+
124
+ symbol: str
125
+ date: date
126
+ tick_size: Decimal
127
+ lot_size: Decimal
128
+
129
+ def __post_init__(self) -> None:
130
+ if not isinstance(self.symbol, str) or _SAFE_SYMBOL.fullmatch(self.symbol) is None:
131
+ raise ValueError("archive symbol must be uppercase ASCII letters/digits")
132
+ if type(self.date) is not date:
133
+ raise ValueError("archive date must be a datetime.date")
134
+ if not isinstance(self.tick_size, Decimal):
135
+ raise ValueError("tick_size must be a Decimal")
136
+ if (
137
+ not self.tick_size.is_finite()
138
+ or self.tick_size <= 0
139
+ or not math.isfinite(float(self.tick_size))
140
+ or float(self.tick_size) <= 0
141
+ ):
142
+ raise ValueError("tick_size must be a positive finite Decimal")
143
+ if not isinstance(self.lot_size, Decimal):
144
+ raise ValueError("lot_size must be a Decimal")
145
+ if (
146
+ not self.lot_size.is_finite()
147
+ or self.lot_size <= 0
148
+ or not math.isfinite(float(self.lot_size))
149
+ or float(self.lot_size) <= 0
150
+ ):
151
+ raise ValueError("lot_size must be a positive finite Decimal")
152
+
153
+ @property
154
+ def archive_name(self) -> str:
155
+ return f"{self.symbol}-aggTrades-{self.date.isoformat()}.zip"
156
+
157
+ @property
158
+ def member_name(self) -> str:
159
+ return self.archive_name.removesuffix(".zip") + ".csv"
160
+
161
+ @property
162
+ def continuity_id(self) -> str:
163
+ return f"binance_spot:{self.symbol}:{self.date.isoformat()}"
164
+
165
+
166
+ @dataclass(frozen=True, slots=True)
167
+ class ArchiveDownloadLimits:
168
+ """Hard transport, expansion, and record-boundary ceilings."""
169
+
170
+ max_compressed_bytes: int
171
+ max_uncompressed_bytes: int
172
+ max_checksum_bytes: int = 4_096
173
+ transfer_chunk_bytes: int = 64 * 1_024
174
+ max_csv_line_bytes: int = 16 * 1_024
175
+
176
+ def __post_init__(self) -> None:
177
+ values = (
178
+ self.max_compressed_bytes,
179
+ self.max_uncompressed_bytes,
180
+ self.max_checksum_bytes,
181
+ self.transfer_chunk_bytes,
182
+ self.max_csv_line_bytes,
183
+ )
184
+ if any(
185
+ isinstance(value, bool) or not isinstance(value, int) or value < 1 for value in values
186
+ ):
187
+ raise ValueError("all archive byte limits must be positive integers")
188
+
189
+
190
+ @dataclass(frozen=True, slots=True)
191
+ class RawArchiveArtifact:
192
+ """Immutable descriptor for an exact public response body."""
193
+
194
+ kind: Literal["archive_zip", "archive_checksum", "rejected_prefix"]
195
+ path: Path
196
+ manifest_path: Path
197
+ sha256: str
198
+ manifest_sha256: str
199
+ bytes: int
200
+ source_uri: str
201
+
202
+
203
+ @dataclass(frozen=True, slots=True)
204
+ class DailyArchiveSummary:
205
+ """Non-economic coverage facts available only after full stream exhaustion."""
206
+
207
+ symbol: str
208
+ date: str
209
+ rows: int
210
+ first_trade_id: int
211
+ last_trade_id: int
212
+ first_event_ts_ns: int
213
+ last_event_ts_ns: int
214
+ compressed_bytes: int
215
+ expanded_bytes: int
216
+ source_archive_sha256: str
217
+ member_name: str
218
+ continuity_id: str
219
+
220
+
221
+ @dataclass(frozen=True, slots=True)
222
+ class _ZipDescriptor:
223
+ member_name: str
224
+ declared_uncompressed_bytes: int
225
+
226
+
227
+ @dataclass(frozen=True, slots=True)
228
+ class _ZipDirectoryBounds:
229
+ offset: int
230
+ bytes: int
231
+
232
+
233
+ @dataclass(frozen=True, slots=True)
234
+ class _DownloadedBody:
235
+ temporary_path: Path
236
+ sha256: str
237
+ bytes: int
238
+ response_headers: Mapping[str, str]
239
+ downloaded_at_utc: str
240
+ evidence_reservations: tuple[EvidenceReservation, ...]
241
+
242
+
243
+ @dataclass(frozen=True, slots=True)
244
+ class AcquiredDailyArchive:
245
+ """Checksum-authenticated raw bytes whose CSV has not yet been opened."""
246
+
247
+ request: DailyArchiveRequest
248
+ archive_artifact: RawArchiveArtifact
249
+ checksum_artifact: RawArchiveArtifact
250
+ upstream_sha256: str
251
+ declared_uncompressed_bytes: int
252
+ limits: ArchiveDownloadLimits
253
+ requires_member_open_guard: bool = False
254
+
255
+ def iter_normalized_batches(
256
+ self,
257
+ *,
258
+ batch_rows: int = 65_536,
259
+ before_member_open: Callable[[], None] | None = None,
260
+ ) -> DailyArchiveTradeStream:
261
+ """Create a fresh one-shot normalized stream over the authenticated ZIP.
262
+
263
+ ``before_member_open`` is a fail-closed held-out-data guard. It runs
264
+ after bounded ZIP-directory validation and immediately before the CSV
265
+ member is opened. A raised exception therefore exposes zero member
266
+ bytes. Acquisition callers normally leave it unset; prospective
267
+ research pipelines use it to revalidate their durable analysis lock
268
+ at the actual economic-data boundary.
269
+
270
+ Handles reconstructed for a frozen held-out role set
271
+ ``requires_member_open_guard``. Such a stream refuses to advance at
272
+ all unless this callback is supplied; the generic archive adapter and
273
+ development-date handles retain their backward-compatible default.
274
+ """
275
+ if isinstance(batch_rows, bool) or not isinstance(batch_rows, int) or batch_rows < 1:
276
+ raise ValueError("batch_rows must be a positive integer")
277
+ return DailyArchiveTradeStream(
278
+ _stream_normalized_batches(
279
+ self,
280
+ batch_rows=batch_rows,
281
+ before_member_open=before_member_open,
282
+ )
283
+ )
284
+
285
+
286
+ class DailyArchiveTradeStream(Iterator[pa.RecordBatch]):
287
+ """One-shot RecordBatch iterator with a terminal-only coverage summary."""
288
+
289
+ def __init__(
290
+ self,
291
+ generator: Generator[pa.RecordBatch, None, DailyArchiveSummary],
292
+ ) -> None:
293
+ self._generator = generator
294
+ self._summary: DailyArchiveSummary | None = None
295
+ self._closed = False
296
+
297
+ def __iter__(self) -> DailyArchiveTradeStream:
298
+ return self
299
+
300
+ def __next__(self) -> pa.RecordBatch:
301
+ if self._closed:
302
+ raise StopIteration
303
+ try:
304
+ return next(self._generator)
305
+ except StopIteration as stop:
306
+ self._closed = True
307
+ self._summary = cast(DailyArchiveSummary, stop.value)
308
+ raise
309
+ except BaseException:
310
+ self._closed = True
311
+ raise
312
+
313
+ @property
314
+ def summary(self) -> DailyArchiveSummary:
315
+ if self._summary is None:
316
+ raise RuntimeError("archive summary is unavailable before full stream exhaustion")
317
+ return self._summary
318
+
319
+ def close(self) -> None:
320
+ if not self._closed:
321
+ self._generator.close()
322
+ self._closed = True
323
+
324
+
325
+ def _day_bounds_ns(value: date) -> tuple[int, int]:
326
+ start = datetime(value.year, value.month, value.day, tzinfo=UTC)
327
+ end = start + timedelta(days=1)
328
+ return int(start.timestamp()) * 1_000_000_000, int(end.timestamp()) * 1_000_000_000
329
+
330
+
331
+ def _safe_headers(headers: Mapping[str, str]) -> dict[str, str]:
332
+ allowed = {
333
+ "content-length",
334
+ "content-type",
335
+ "etag",
336
+ "last-modified",
337
+ "retry-after",
338
+ }
339
+ return {str(key): str(value) for key, value in headers.items() if str(key).lower() in allowed}
340
+
341
+
342
+ def _header(headers: Mapping[str, str], name: str) -> str | None:
343
+ lowered = name.lower()
344
+ for key, value in headers.items():
345
+ if str(key).lower() == lowered:
346
+ return str(value)
347
+ return None
348
+
349
+
350
+ def _content_length(headers: Mapping[str, str]) -> int | None:
351
+ raw = _header(headers, "content-length")
352
+ if raw is None:
353
+ return None
354
+ if not raw.isascii() or not raw.isdecimal():
355
+ raise BinanceArchivePayloadError("response Content-Length must be an unsigned integer")
356
+ return int(raw)
357
+
358
+
359
+ def _retry_after_seconds(headers: Mapping[str, str]) -> float | None:
360
+ raw = _header(headers, "retry-after")
361
+ if raw is None:
362
+ return None
363
+ try:
364
+ value = float(raw)
365
+ except ValueError:
366
+ return None
367
+ if not math.isfinite(value) or value < 0:
368
+ return None
369
+ return value
370
+
371
+
372
+ def _validate_base_url(value: str) -> str:
373
+ normalized = value.rstrip("/")
374
+ parsed = urlsplit(normalized)
375
+ if parsed.scheme != "https" or not parsed.netloc or parsed.path not in {"", "/"}:
376
+ raise ValueError("archive base_url must be an HTTPS origin without path/query")
377
+ if parsed.query or parsed.fragment or parsed.username or parsed.password:
378
+ raise ValueError("archive base_url must not contain credentials, query, or fragment")
379
+ return normalized
380
+
381
+
382
+ def _archive_urls(base_url: str, request: DailyArchiveRequest) -> tuple[str, str]:
383
+ archive = f"{base_url}/data/spot/daily/aggTrades/{request.symbol}/{request.archive_name}"
384
+ return archive, f"{archive}.CHECKSUM"
385
+
386
+
387
+ def _release_evidence_reservations(
388
+ reservations: tuple[EvidenceReservation, ...] | list[EvidenceReservation],
389
+ ) -> None:
390
+ for reservation in reservations:
391
+ if reservation.active:
392
+ reservation.release()
393
+
394
+
395
+ def _commit_evidence_reservations(
396
+ reservations: tuple[EvidenceReservation, ...] | list[EvidenceReservation],
397
+ ) -> None:
398
+ for reservation in reservations:
399
+ reservation.commit()
400
+
401
+
402
+ def _discard_download(body: _DownloadedBody) -> None:
403
+ body.temporary_path.unlink(missing_ok=True)
404
+ _release_evidence_reservations(body.evidence_reservations)
405
+
406
+
407
+ def _fsync_directory(path: Path) -> None:
408
+ descriptor = os.open(path, os.O_RDONLY)
409
+ try:
410
+ os.fsync(descriptor)
411
+ finally:
412
+ os.close(descriptor)
413
+
414
+
415
+ def _publish_temp(
416
+ temporary: Path,
417
+ *,
418
+ destination_directory: Path,
419
+ suffix: str,
420
+ destination_name: str | None = None,
421
+ kind: Literal["archive_zip", "archive_checksum", "rejected_prefix"],
422
+ source: str,
423
+ source_uri: str,
424
+ downloaded_at_utc: str,
425
+ request: DailyArchiveRequest,
426
+ sha256: str,
427
+ response_headers: Mapping[str, str],
428
+ upstream_checksum_sha256: str | None,
429
+ retained_evidence_budget: RetainedEvidenceBudget | None = None,
430
+ evidence_reservations: tuple[EvidenceReservation, ...] = (),
431
+ ) -> RawArchiveArtifact:
432
+ destination = destination_directory / (destination_name or f"{sha256}{suffix}")
433
+ if retained_evidence_budget is None and evidence_reservations:
434
+ raise BinanceArchiveError("download reservations require a retained-evidence budget")
435
+ if retained_evidence_budget is not None:
436
+ retained_evidence_budget.assert_contains(temporary)
437
+ retained_evidence_budget.assert_contains(destination)
438
+ transaction = (
439
+ retained_evidence_budget.write_transaction()
440
+ if retained_evidence_budget is not None
441
+ else nullcontext()
442
+ )
443
+ created_destination = False
444
+ try:
445
+ with transaction:
446
+ destination_directory.mkdir(parents=True, exist_ok=True)
447
+ if destination.exists():
448
+ if sha256_file(destination) != sha256:
449
+ raise BinanceArchivePayloadError(f"content-address collision at {destination}")
450
+ temporary.unlink(missing_ok=True)
451
+ _release_evidence_reservations(evidence_reservations)
452
+ else:
453
+ os.replace(temporary, destination)
454
+ _fsync_directory(destination_directory)
455
+ created_destination = True
456
+ start_ns, end_ns = _day_bounds_ns(request.date)
457
+ manifest_path, manifest_sha = write_source_manifest(
458
+ destination,
459
+ source=source,
460
+ source_uri=source_uri,
461
+ downloaded_at_utc=downloaded_at_utc,
462
+ requested_start_ns=start_ns,
463
+ requested_end_ns=end_ns,
464
+ upstream_checksum_sha256=upstream_checksum_sha256,
465
+ response_headers=response_headers,
466
+ retained_evidence_budget=retained_evidence_budget,
467
+ )
468
+ if created_destination:
469
+ _commit_evidence_reservations(evidence_reservations)
470
+ return RawArchiveArtifact(
471
+ kind=kind,
472
+ path=destination,
473
+ manifest_path=manifest_path,
474
+ sha256=sha256,
475
+ manifest_sha256=manifest_sha,
476
+ bytes=destination.stat().st_size,
477
+ source_uri=source_uri,
478
+ )
479
+ except BaseException:
480
+ temporary.unlink(missing_ok=True)
481
+ if created_destination:
482
+ destination.unlink(missing_ok=True)
483
+ _release_evidence_reservations(evidence_reservations)
484
+ raise
485
+
486
+
487
+ def _publish_rejected(
488
+ temporary: Path,
489
+ *,
490
+ raw_root: Path,
491
+ request: DailyArchiveRequest,
492
+ source_uri: str,
493
+ downloaded_at_utc: str,
494
+ response_headers: Mapping[str, str],
495
+ reason: str,
496
+ suffix: str,
497
+ attempt_number: int | None = None,
498
+ retained_evidence_budget: RetainedEvidenceBudget | None = None,
499
+ evidence_reservations: tuple[EvidenceReservation, ...] = (),
500
+ ) -> RawArchiveArtifact:
501
+ digest = sha256_file(temporary)
502
+ headers = dict(response_headers)
503
+ headers.update(
504
+ {
505
+ "x-local-capture-status": "rejected_bounded_prefix",
506
+ "x-local-rejection-reason": reason,
507
+ "x-local-captured-bytes": str(temporary.stat().st_size),
508
+ }
509
+ )
510
+ if attempt_number is not None:
511
+ headers["x-local-download-attempt"] = str(attempt_number)
512
+ return _publish_temp(
513
+ temporary,
514
+ destination_directory=(
515
+ raw_root
516
+ / "binance_spot"
517
+ / "daily_agg_trades_archive_rejected"
518
+ / request.symbol
519
+ / request.date.isoformat()
520
+ ),
521
+ suffix=suffix,
522
+ kind="rejected_prefix",
523
+ source="binance_spot_daily_aggtrades_archive_rejected",
524
+ source_uri=source_uri,
525
+ downloaded_at_utc=downloaded_at_utc,
526
+ request=request,
527
+ sha256=digest,
528
+ response_headers=headers,
529
+ upstream_checksum_sha256=None,
530
+ retained_evidence_budget=retained_evidence_budget,
531
+ evidence_reservations=evidence_reservations,
532
+ )
533
+
534
+
535
+ def _bounded_download_once(
536
+ session: _StreamingSession,
537
+ *,
538
+ url: str,
539
+ raw_root: Path,
540
+ request: DailyArchiveRequest,
541
+ byte_limit: int,
542
+ chunk_bytes: int,
543
+ timeout_seconds: float,
544
+ rejected_suffix: str,
545
+ attempt_number: int,
546
+ retained_evidence_budget: RetainedEvidenceBudget | None,
547
+ ) -> _DownloadedBody:
548
+ work = raw_root / "binance_spot" / ".archive_downloads"
549
+ if retained_evidence_budget is not None:
550
+ retained_evidence_budget.assert_contains(work)
551
+ work.mkdir(parents=True, exist_ok=True)
552
+ descriptor, temporary_name = tempfile.mkstemp(dir=work, prefix=".download-", suffix=".tmp")
553
+ temporary = Path(temporary_name)
554
+ response: _StreamingResponse | None = None
555
+ downloaded_at = utc_now_iso()
556
+ safe_headers: dict[str, str] = {}
557
+ digest = hashlib.sha256()
558
+ captured = 0
559
+ error: BaseException | None = None
560
+ evidence_reservations: list[EvidenceReservation] = []
561
+
562
+ def write_chunk(sink: Any, chunk: bytes) -> None:
563
+ reservation = (
564
+ retained_evidence_budget.reserve(
565
+ len(chunk),
566
+ label=f"raw Binance archive response from {url}",
567
+ )
568
+ if retained_evidence_budget is not None
569
+ else None
570
+ )
571
+ if reservation is not None:
572
+ evidence_reservations.append(reservation)
573
+ try:
574
+ sink.write(chunk)
575
+ except BaseException:
576
+ if reservation is not None:
577
+ evidence_reservations.pop()
578
+ reservation.release()
579
+ raise
580
+
581
+ try:
582
+ with os.fdopen(descriptor, "wb") as sink:
583
+ descriptor = -1
584
+ try:
585
+ response = session.get(url, timeout=timeout_seconds, stream=True)
586
+ except requests.RequestException as exc:
587
+ raise _RetryableDownloadError(f"GET {url} failed before a response") from exc
588
+ safe_headers = _safe_headers(response.headers)
589
+ if str(response.url) != url:
590
+ raise BinanceArchiveHTTPError("archive response redirected away from exact URL")
591
+ if response.status_code != 200:
592
+ status_code = response.status_code
593
+ message = f"GET {url} returned HTTP {status_code}"
594
+ if status_code in {408, 418, 429} or 500 <= status_code <= 599:
595
+ retry_after = (
596
+ _retry_after_seconds(response.headers)
597
+ if status_code in {418, 429}
598
+ else None
599
+ )
600
+ raise _RetryableDownloadError(
601
+ message,
602
+ retry_after_seconds=retry_after,
603
+ )
604
+ raise BinanceArchiveHTTPError(message, status_code=status_code)
605
+ declared = _content_length(response.headers)
606
+ if declared is not None and declared > byte_limit:
607
+ raise BinanceArchivePayloadError(
608
+ f"response Content-Length {declared} exceeds byte ceiling {byte_limit}"
609
+ )
610
+ try:
611
+ chunks = response.iter_content(chunk_size=chunk_bytes)
612
+ for chunk in chunks:
613
+ if not isinstance(chunk, bytes):
614
+ raise BinanceArchivePayloadError("streaming response emitted non-bytes")
615
+ if not chunk:
616
+ continue
617
+ remaining = byte_limit - captured
618
+ if len(chunk) > remaining:
619
+ prefix = chunk[:remaining]
620
+ if prefix:
621
+ write_chunk(sink, prefix)
622
+ digest.update(prefix)
623
+ captured += len(prefix)
624
+ raise BinanceArchivePayloadError(
625
+ f"response body exceeds byte ceiling {byte_limit}"
626
+ )
627
+ write_chunk(sink, chunk)
628
+ digest.update(chunk)
629
+ captured += len(chunk)
630
+ except requests.RequestException as exc:
631
+ raise _RetryableDownloadError(
632
+ f"GET {url} body interrupted after {captured} bytes"
633
+ ) from exc
634
+ if declared is not None and captured < declared:
635
+ raise _RetryableDownloadError(
636
+ f"GET {url} body truncated at {captured} of {declared} Content-Length bytes"
637
+ )
638
+ if declared is not None and captured > declared:
639
+ raise BinanceArchivePayloadError(
640
+ f"GET {url} body length {captured} exceeds Content-Length {declared}"
641
+ )
642
+ sink.flush()
643
+ os.fsync(sink.fileno())
644
+ except BaseException as exc:
645
+ error = exc
646
+ finally:
647
+ if descriptor >= 0:
648
+ os.close(descriptor)
649
+ if response is not None:
650
+ try:
651
+ response.close()
652
+ except BaseException as exc:
653
+ if error is None:
654
+ error = BinanceArchiveHTTPError(f"GET {url} response could not be closed")
655
+ error.__cause__ = exc
656
+
657
+ if error is not None:
658
+ try:
659
+ _publish_rejected(
660
+ temporary,
661
+ raw_root=raw_root,
662
+ request=request,
663
+ source_uri=url,
664
+ downloaded_at_utc=downloaded_at,
665
+ response_headers=safe_headers,
666
+ reason=str(error),
667
+ suffix=rejected_suffix,
668
+ attempt_number=attempt_number,
669
+ retained_evidence_budget=retained_evidence_budget,
670
+ evidence_reservations=tuple(evidence_reservations),
671
+ )
672
+ except BaseException as evidence_error:
673
+ temporary.unlink(missing_ok=True)
674
+ _release_evidence_reservations(evidence_reservations)
675
+ if isinstance(evidence_error, EvidenceBudgetError):
676
+ raise
677
+ if not isinstance(evidence_error, Exception):
678
+ raise
679
+ raise BinanceArchiveError(
680
+ f"could not retain rejected download attempt {attempt_number}"
681
+ ) from evidence_error
682
+ raise error
683
+ return _DownloadedBody(
684
+ temporary_path=temporary,
685
+ sha256=digest.hexdigest(),
686
+ bytes=captured,
687
+ response_headers=safe_headers,
688
+ downloaded_at_utc=downloaded_at,
689
+ evidence_reservations=tuple(evidence_reservations),
690
+ )
691
+
692
+
693
+ def _bounded_download(
694
+ session: _StreamingSession,
695
+ *,
696
+ url: str,
697
+ raw_root: Path,
698
+ request: DailyArchiveRequest,
699
+ byte_limit: int,
700
+ chunk_bytes: int,
701
+ timeout_seconds: float,
702
+ rejected_suffix: str,
703
+ retry_policy: RetryPolicy,
704
+ sleep: Callable[[float], None],
705
+ random_value: Callable[[], float],
706
+ retained_evidence_budget: RetainedEvidenceBudget | None,
707
+ ) -> _DownloadedBody:
708
+ attempts = retry_policy.max_retries + 1
709
+ for attempt_index in range(attempts):
710
+ try:
711
+ return _bounded_download_once(
712
+ session,
713
+ url=url,
714
+ raw_root=raw_root,
715
+ request=request,
716
+ byte_limit=byte_limit,
717
+ chunk_bytes=chunk_bytes,
718
+ timeout_seconds=timeout_seconds,
719
+ rejected_suffix=rejected_suffix,
720
+ attempt_number=attempt_index + 1,
721
+ retained_evidence_budget=retained_evidence_budget,
722
+ )
723
+ except _RetryableDownloadError as error:
724
+ if attempt_index >= retry_policy.max_retries:
725
+ error.add_note(f"exhausted {attempts} bounded download attempts")
726
+ error.retry_exhausted = True
727
+ raise
728
+ if error.retry_after_seconds is not None:
729
+ delay = error.retry_after_seconds
730
+ else:
731
+ exponential_cap = min(
732
+ retry_policy.max_delay_seconds,
733
+ retry_policy.base_delay_seconds * (2**attempt_index),
734
+ )
735
+ jitter = random_value()
736
+ if (
737
+ isinstance(jitter, bool)
738
+ or not isinstance(jitter, (int, float))
739
+ or not math.isfinite(jitter)
740
+ or not 0 <= jitter <= 1
741
+ ):
742
+ raise ValueError("random_value must return a finite number in [0, 1]") from None
743
+ delay = exponential_cap * jitter
744
+ sleep(delay)
745
+ raise AssertionError("archive retry loop exhausted without a terminal result")
746
+
747
+
748
+ def _read_bounded_file(path: Path, *, byte_limit: int) -> bytes:
749
+ with path.open("rb") as source:
750
+ content = source.read(byte_limit + 1)
751
+ if len(content) > byte_limit:
752
+ raise BinanceArchivePayloadError(f"artifact exceeds read ceiling {byte_limit}")
753
+ return content
754
+
755
+
756
+ def _parse_checksum(content: bytes, *, archive_name: str) -> str:
757
+ match = _CHECKSUM_LINE.fullmatch(content)
758
+ if match is None:
759
+ raise BinanceArchivePayloadError(
760
+ "archive CHECKSUM must be one lowercase SHA-256 and exact basename"
761
+ )
762
+ digest = match.group(1).decode("ascii")
763
+ filename = match.group(2).decode("ascii")
764
+ if filename != archive_name or _SAFE_ARCHIVE_NAME.fullmatch(filename) is None:
765
+ raise BinanceArchivePayloadError("archive CHECKSUM names an unexpected file")
766
+ return digest
767
+
768
+
769
+ def _preflight_eocd_handle(source: BinaryIO, size: int) -> _ZipDirectoryBounds:
770
+ if size < _EOCD_STRUCT.size:
771
+ raise BinanceArchivePayloadError("archive is too small to contain a ZIP directory")
772
+ tail_size = min(size, _MAX_EOCD_BYTES)
773
+ source.seek(size - tail_size)
774
+ tail = source.read(tail_size)
775
+ offset = tail.rfind(_EOCD_SIGNATURE)
776
+ if offset < 0 or len(tail) - offset < _EOCD_STRUCT.size:
777
+ raise BinanceArchivePayloadError("archive ZIP end-of-directory record is missing")
778
+ values = _EOCD_STRUCT.unpack_from(tail, offset)
779
+ _, disk, central_disk, entries_disk, entries_total, central_bytes, central_offset, comment = (
780
+ values
781
+ )
782
+ absolute_offset = size - tail_size + offset
783
+ if absolute_offset + _EOCD_STRUCT.size + comment != size:
784
+ raise BinanceArchivePayloadError("archive ZIP has trailing or malformed directory bytes")
785
+ if disk != 0 or central_disk != 0 or entries_disk != 1 or entries_total != 1:
786
+ raise BinanceArchivePayloadError("archive ZIP must contain exactly one single-disk member")
787
+ if central_bytes == 0 or central_bytes > _MAX_ZIP_ENTRY_METADATA_BYTES:
788
+ raise BinanceArchivePayloadError(
789
+ "archive ZIP central directory exceeds its metadata byte ceiling"
790
+ )
791
+ if central_offset + central_bytes != absolute_offset:
792
+ raise BinanceArchivePayloadError("archive ZIP central-directory bounds are invalid")
793
+ return _ZipDirectoryBounds(offset=central_offset, bytes=central_bytes)
794
+
795
+
796
+ def _validate_local_file_header_handle(
797
+ source: BinaryIO,
798
+ *,
799
+ info: zipfile.ZipInfo,
800
+ expected_member: str,
801
+ central_offset: int,
802
+ ) -> None:
803
+ header_offset = int(info.header_offset)
804
+ if header_offset < 0 or header_offset + _LOCAL_FILE_STRUCT.size > central_offset:
805
+ raise BinanceArchivePayloadError("archive ZIP local-header bounds are invalid")
806
+ source.seek(header_offset)
807
+ header = source.read(_LOCAL_FILE_STRUCT.size)
808
+ if len(header) != _LOCAL_FILE_STRUCT.size:
809
+ raise BinanceArchivePayloadError("archive ZIP local header is truncated")
810
+ (
811
+ signature,
812
+ _version,
813
+ flags,
814
+ compression,
815
+ _modified_time,
816
+ _modified_date,
817
+ _crc32,
818
+ _compressed_bytes,
819
+ _uncompressed_bytes,
820
+ filename_bytes,
821
+ extra_bytes,
822
+ ) = _LOCAL_FILE_STRUCT.unpack(header)
823
+ if signature != _LOCAL_FILE_SIGNATURE:
824
+ raise BinanceArchivePayloadError("archive ZIP local-header signature is invalid")
825
+ metadata_bytes = filename_bytes + extra_bytes
826
+ if metadata_bytes > _MAX_ZIP_ENTRY_METADATA_BYTES:
827
+ raise BinanceArchivePayloadError(
828
+ "archive ZIP local header exceeds its metadata byte ceiling"
829
+ )
830
+ if header_offset + _LOCAL_FILE_STRUCT.size + metadata_bytes > central_offset:
831
+ raise BinanceArchivePayloadError("archive ZIP local-header bounds are invalid")
832
+ local_name = source.read(filename_bytes)
833
+ if local_name != expected_member.encode("ascii"):
834
+ raise BinanceArchivePayloadError("archive ZIP local member path/name is invalid")
835
+ if flags != info.flag_bits or compression != info.compress_type:
836
+ raise BinanceArchivePayloadError("archive ZIP local and central metadata disagree")
837
+
838
+
839
+ def _validate_zip_structure_handle(
840
+ source: BinaryIO,
841
+ size: int,
842
+ *,
843
+ expected_member: str,
844
+ max_uncompressed_bytes: int,
845
+ ) -> _ZipDescriptor:
846
+ try:
847
+ directory = _preflight_eocd_handle(source, size)
848
+ source.seek(0)
849
+ with zipfile.ZipFile(source) as archive:
850
+ infos = archive.infolist()
851
+ if len(infos) != 1:
852
+ raise BinanceArchivePayloadError("archive ZIP must contain exactly one member")
853
+ info = infos[0]
854
+ mode = info.external_attr >> 16
855
+ if (
856
+ info.filename != expected_member
857
+ or Path(info.filename).name != info.filename
858
+ or "\\" in info.filename
859
+ or info.is_dir()
860
+ ):
861
+ raise BinanceArchivePayloadError("archive ZIP member path/name is invalid")
862
+ if stat.S_ISLNK(mode) or info.flag_bits & 0x1:
863
+ raise BinanceArchivePayloadError(
864
+ "archive ZIP member must be regular and unencrypted"
865
+ )
866
+ if info.compress_type not in {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED}:
867
+ raise BinanceArchivePayloadError("archive ZIP uses an unsupported compression type")
868
+ if info.file_size < 1 or info.file_size > max_uncompressed_bytes:
869
+ raise BinanceArchiveContractError(
870
+ "archive member declared uncompressed bytes outside configured ceiling",
871
+ reason_code="RESPONSE_SIZE_LIMIT",
872
+ )
873
+ _validate_local_file_header_handle(
874
+ source,
875
+ info=info,
876
+ expected_member=expected_member,
877
+ central_offset=directory.offset,
878
+ )
879
+ return _ZipDescriptor(
880
+ member_name=info.filename,
881
+ declared_uncompressed_bytes=int(info.file_size),
882
+ )
883
+ except BinanceArchivePayloadError:
884
+ raise
885
+ except (OSError, RuntimeError, zipfile.BadZipFile) as exc:
886
+ raise BinanceArchivePayloadError("cannot inspect archive ZIP structure") from exc
887
+
888
+
889
+ def _validate_zip_structure(
890
+ path: Path,
891
+ *,
892
+ expected_member: str,
893
+ max_uncompressed_bytes: int,
894
+ ) -> _ZipDescriptor:
895
+ with path.open("rb") as source:
896
+ return _validate_zip_structure_handle(
897
+ source,
898
+ os.fstat(source.fileno()).st_size,
899
+ expected_member=expected_member,
900
+ max_uncompressed_bytes=max_uncompressed_bytes,
901
+ )
902
+
903
+
904
+ class BinanceArchiveClient:
905
+ """HTTP boundary for official checksum-authenticated daily Spot archives."""
906
+
907
+ def __init__(
908
+ self,
909
+ *,
910
+ session: _StreamingSession | None = None,
911
+ base_url: str = _DEFAULT_BASE_URL,
912
+ timeout_seconds: float = 30.0,
913
+ retry_policy: RetryPolicy | None = None,
914
+ sleep: Callable[[float], None] = time.sleep,
915
+ random_value: Callable[[], float] = random.random,
916
+ retained_evidence_budget: RetainedEvidenceBudget | None = None,
917
+ ) -> None:
918
+ if (
919
+ isinstance(timeout_seconds, bool)
920
+ or not isinstance(timeout_seconds, (int, float))
921
+ or not math.isfinite(timeout_seconds)
922
+ or timeout_seconds <= 0
923
+ ):
924
+ raise ValueError("timeout_seconds must be positive")
925
+ self.session = (
926
+ session
927
+ if session is not None
928
+ else cast(_StreamingSession, cast(object, requests.Session()))
929
+ )
930
+ self.base_url = _validate_base_url(base_url)
931
+ self.timeout_seconds = timeout_seconds
932
+ self.retry_policy = retry_policy or RetryPolicy()
933
+ self._sleep = sleep
934
+ self._random_value = random_value
935
+ self.retained_evidence_budget = retained_evidence_budget
936
+
937
+ def acquire(
938
+ self,
939
+ request: DailyArchiveRequest,
940
+ *,
941
+ raw_root: str | Path,
942
+ limits: ArchiveDownloadLimits,
943
+ ) -> AcquiredDailyArchive:
944
+ """Acquire exact raw bytes without opening the archive CSV member."""
945
+ destination_root = Path(raw_root).resolve()
946
+ archive_url, checksum_url = _archive_urls(self.base_url, request)
947
+ try:
948
+ checksum_body = _bounded_download(
949
+ self.session,
950
+ url=checksum_url,
951
+ raw_root=destination_root,
952
+ request=request,
953
+ byte_limit=limits.max_checksum_bytes,
954
+ chunk_bytes=min(limits.transfer_chunk_bytes, limits.max_checksum_bytes),
955
+ timeout_seconds=self.timeout_seconds,
956
+ rejected_suffix=".CHECKSUM.rejected",
957
+ retry_policy=self.retry_policy,
958
+ sleep=self._sleep,
959
+ random_value=self._random_value,
960
+ retained_evidence_budget=self.retained_evidence_budget,
961
+ )
962
+ except BinanceArchiveContractError:
963
+ raise
964
+ except BinanceArchivePayloadError as exc:
965
+ raise BinanceArchiveContractError(
966
+ str(exc),
967
+ reason_code="RESPONSE_SIZE_LIMIT",
968
+ ) from exc
969
+ try:
970
+ checksum_directory = (
971
+ destination_root
972
+ / "binance_spot"
973
+ / "daily_agg_trades_archive_checksums"
974
+ / request.symbol
975
+ / request.date.isoformat()
976
+ )
977
+ checksum_destination = checksum_directory / f"{request.archive_name}.CHECKSUM"
978
+ if (
979
+ checksum_destination.exists()
980
+ and sha256_file(checksum_destination) != checksum_body.sha256
981
+ ):
982
+ _publish_rejected(
983
+ checksum_body.temporary_path,
984
+ raw_root=destination_root,
985
+ request=request,
986
+ source_uri=checksum_url,
987
+ downloaded_at_utc=checksum_body.downloaded_at_utc,
988
+ response_headers=checksum_body.response_headers,
989
+ reason="official CHECKSUM basename already contains different immutable bytes",
990
+ suffix=".CHECKSUM.rejected",
991
+ retained_evidence_budget=self.retained_evidence_budget,
992
+ evidence_reservations=checksum_body.evidence_reservations,
993
+ )
994
+ raise BinanceArchivePayloadError(
995
+ "official CHECKSUM basename collides with different immutable bytes"
996
+ )
997
+ checksum_artifact = _publish_temp(
998
+ checksum_body.temporary_path,
999
+ destination_directory=checksum_directory,
1000
+ suffix=".CHECKSUM",
1001
+ destination_name=f"{request.archive_name}.CHECKSUM",
1002
+ kind="archive_checksum",
1003
+ source="binance_spot_daily_aggtrades_archive_checksum",
1004
+ source_uri=checksum_url,
1005
+ downloaded_at_utc=checksum_body.downloaded_at_utc,
1006
+ request=request,
1007
+ sha256=checksum_body.sha256,
1008
+ response_headers=checksum_body.response_headers,
1009
+ upstream_checksum_sha256=None,
1010
+ retained_evidence_budget=self.retained_evidence_budget,
1011
+ evidence_reservations=checksum_body.evidence_reservations,
1012
+ )
1013
+ except BaseException:
1014
+ _discard_download(checksum_body)
1015
+ raise
1016
+ try:
1017
+ upstream_sha = _parse_checksum(
1018
+ _read_bounded_file(checksum_artifact.path, byte_limit=limits.max_checksum_bytes),
1019
+ archive_name=request.archive_name,
1020
+ )
1021
+ except BinanceArchivePayloadError as exc:
1022
+ raise BinanceArchiveContractError(
1023
+ str(exc),
1024
+ reason_code="CHECKSUM_CONTRACT",
1025
+ ) from exc
1026
+
1027
+ try:
1028
+ archive_body = _bounded_download(
1029
+ self.session,
1030
+ url=archive_url,
1031
+ raw_root=destination_root,
1032
+ request=request,
1033
+ byte_limit=limits.max_compressed_bytes,
1034
+ chunk_bytes=limits.transfer_chunk_bytes,
1035
+ timeout_seconds=self.timeout_seconds,
1036
+ rejected_suffix=".zip.rejected",
1037
+ retry_policy=self.retry_policy,
1038
+ sleep=self._sleep,
1039
+ random_value=self._random_value,
1040
+ retained_evidence_budget=self.retained_evidence_budget,
1041
+ )
1042
+ except BinanceArchivePayloadError as exc:
1043
+ raise BinanceArchiveContractError(
1044
+ str(exc),
1045
+ reason_code="RESPONSE_SIZE_LIMIT",
1046
+ ) from exc
1047
+ try:
1048
+ if archive_body.sha256 != upstream_sha:
1049
+ _publish_rejected(
1050
+ archive_body.temporary_path,
1051
+ raw_root=destination_root,
1052
+ request=request,
1053
+ source_uri=archive_url,
1054
+ downloaded_at_utc=archive_body.downloaded_at_utc,
1055
+ response_headers=archive_body.response_headers,
1056
+ reason=(
1057
+ f"archive SHA-256 {archive_body.sha256} disagrees with official {upstream_sha}"
1058
+ ),
1059
+ suffix=".zip.rejected",
1060
+ retained_evidence_budget=self.retained_evidence_budget,
1061
+ evidence_reservations=archive_body.evidence_reservations,
1062
+ )
1063
+ raise BinanceArchiveContractError(
1064
+ "archive SHA-256 disagrees with official CHECKSUM",
1065
+ reason_code="CHECKSUM_CONTRACT",
1066
+ )
1067
+
1068
+ archive_directory = (
1069
+ destination_root
1070
+ / "binance_spot"
1071
+ / "daily_agg_trades_archive"
1072
+ / request.symbol
1073
+ / request.date.isoformat()
1074
+ )
1075
+ official_destination = archive_directory / request.archive_name
1076
+ if (
1077
+ official_destination.exists()
1078
+ and sha256_file(official_destination) != archive_body.sha256
1079
+ ):
1080
+ _publish_rejected(
1081
+ archive_body.temporary_path,
1082
+ raw_root=destination_root,
1083
+ request=request,
1084
+ source_uri=archive_url,
1085
+ downloaded_at_utc=archive_body.downloaded_at_utc,
1086
+ response_headers=archive_body.response_headers,
1087
+ reason="official archive basename already contains different immutable bytes",
1088
+ suffix=".zip.rejected",
1089
+ retained_evidence_budget=self.retained_evidence_budget,
1090
+ evidence_reservations=archive_body.evidence_reservations,
1091
+ )
1092
+ raise BinanceArchivePayloadError(
1093
+ "official archive basename collides with different immutable bytes"
1094
+ )
1095
+ archive_artifact = _publish_temp(
1096
+ archive_body.temporary_path,
1097
+ destination_directory=archive_directory,
1098
+ suffix=".zip",
1099
+ destination_name=request.archive_name,
1100
+ kind="archive_zip",
1101
+ source="binance_spot_daily_aggtrades_archive",
1102
+ source_uri=archive_url,
1103
+ downloaded_at_utc=archive_body.downloaded_at_utc,
1104
+ request=request,
1105
+ sha256=archive_body.sha256,
1106
+ response_headers=archive_body.response_headers,
1107
+ upstream_checksum_sha256=upstream_sha,
1108
+ retained_evidence_budget=self.retained_evidence_budget,
1109
+ evidence_reservations=archive_body.evidence_reservations,
1110
+ )
1111
+ except BaseException:
1112
+ _discard_download(archive_body)
1113
+ raise
1114
+ try:
1115
+ zip_descriptor = _validate_zip_structure(
1116
+ archive_artifact.path,
1117
+ expected_member=request.member_name,
1118
+ max_uncompressed_bytes=limits.max_uncompressed_bytes,
1119
+ )
1120
+ except BinanceArchiveContractError:
1121
+ raise
1122
+ except BinanceArchivePayloadError as exc:
1123
+ if isinstance(exc.__cause__, OSError):
1124
+ raise
1125
+ raise BinanceArchiveContractError(
1126
+ str(exc),
1127
+ reason_code="ZIP_CONTRACT",
1128
+ ) from exc
1129
+ return AcquiredDailyArchive(
1130
+ request=request,
1131
+ archive_artifact=archive_artifact,
1132
+ checksum_artifact=checksum_artifact,
1133
+ upstream_sha256=upstream_sha,
1134
+ declared_uncompressed_bytes=zip_descriptor.declared_uncompressed_bytes,
1135
+ limits=limits,
1136
+ )
1137
+
1138
+
1139
+ def _parse_unsigned(value: bytes, *, label: str) -> int:
1140
+ if len(value) > 19:
1141
+ raise BinanceArchivePayloadError(f"{label} exceeds signed int64")
1142
+ if _UNSIGNED_INTEGER.fullmatch(value) is None:
1143
+ raise BinanceArchivePayloadError(f"{label} must be a canonical unsigned integer")
1144
+ parsed = int(value)
1145
+ if parsed > _MAX_INT64:
1146
+ raise BinanceArchivePayloadError(f"{label} exceeds signed int64")
1147
+ return parsed
1148
+
1149
+
1150
+ def _parse_boolean(value: bytes, *, label: str) -> bool:
1151
+ lowered = value.lower()
1152
+ if lowered == b"true":
1153
+ return True
1154
+ if lowered == b"false":
1155
+ return False
1156
+ raise BinanceArchivePayloadError(f"{label} must be true or false")
1157
+
1158
+
1159
+ def _scaled_decimal(value: bytes, *, quantum: Decimal, label: str) -> tuple[Decimal, int]:
1160
+ if len(value) > _MAX_DECIMAL_FIELD_BYTES:
1161
+ raise BinanceArchivePayloadError(f"{label} exceeds its field byte ceiling")
1162
+ try:
1163
+ text = value.decode("ascii")
1164
+ decimal = Decimal(text)
1165
+ if not decimal.is_finite() or decimal <= 0:
1166
+ raise BinanceArchivePayloadError(f"{label} must be positive and finite")
1167
+ scaled = decimal / quantum
1168
+ integral = scaled.to_integral_value()
1169
+ except (UnicodeDecodeError, InvalidOperation, ZeroDivisionError) as exc:
1170
+ raise BinanceArchivePayloadError(f"{label} is not a valid decimal") from exc
1171
+ if scaled != integral:
1172
+ raise BinanceArchivePayloadError(f"{label} is not aligned to declared scale")
1173
+ integer = int(integral)
1174
+ if integer < 1 or integer > _MAX_INT64:
1175
+ raise BinanceArchivePayloadError(f"{label} scaled value is outside signed int64")
1176
+ return decimal, integer
1177
+
1178
+
1179
+ def _line_chunks(
1180
+ source: Any,
1181
+ *,
1182
+ max_uncompressed_bytes: int,
1183
+ chunk_bytes: int,
1184
+ max_line_bytes: int,
1185
+ ) -> Generator[bytes, None, int]:
1186
+ pending = b""
1187
+ expanded = 0
1188
+ while True:
1189
+ chunk = source.read(chunk_bytes)
1190
+ if not isinstance(chunk, bytes):
1191
+ raise BinanceArchivePayloadError("archive member emitted non-bytes")
1192
+ if not chunk:
1193
+ break
1194
+ expanded += len(chunk)
1195
+ if expanded > max_uncompressed_bytes:
1196
+ raise BinanceArchivePayloadError("archive expansion exceeds configured byte ceiling")
1197
+ combined = pending + chunk
1198
+ pieces = combined.split(b"\n")
1199
+ pending = pieces.pop()
1200
+ if len(pending) > max_line_bytes:
1201
+ raise BinanceArchivePayloadError("archive CSV line exceeds configured byte ceiling")
1202
+ for line in pieces:
1203
+ if line.endswith(b"\r"):
1204
+ line = line[:-1]
1205
+ if len(line) > max_line_bytes:
1206
+ raise BinanceArchivePayloadError("archive CSV line exceeds configured byte ceiling")
1207
+ yield line
1208
+ if pending:
1209
+ if pending.endswith(b"\r"):
1210
+ pending = pending[:-1]
1211
+ if len(pending) > max_line_bytes:
1212
+ raise BinanceArchivePayloadError("archive CSV line exceeds configured byte ceiling")
1213
+ yield pending
1214
+ return expanded
1215
+
1216
+
1217
+ def _record_from_line(
1218
+ line: bytes,
1219
+ *,
1220
+ row_number: int,
1221
+ acquired: AcquiredDailyArchive,
1222
+ previous_trade_id: int | None,
1223
+ previous_event_ts_ns: int | None,
1224
+ start_ns: int,
1225
+ end_ns: int,
1226
+ ) -> tuple[dict[str, object], int, int]:
1227
+ fields = line.split(b",")
1228
+ if len(fields) != 8:
1229
+ raise BinanceArchivePayloadError(
1230
+ f"archive CSV row {row_number} must contain exactly 8 fields"
1231
+ )
1232
+ aggregate_id = _parse_unsigned(fields[0], label=f"row {row_number} aggregate trade ID")
1233
+ first_trade_id = _parse_unsigned(fields[3], label=f"row {row_number} first trade ID")
1234
+ last_trade_id = _parse_unsigned(fields[4], label=f"row {row_number} last trade ID")
1235
+ if first_trade_id > last_trade_id:
1236
+ raise BinanceArchivePayloadError(
1237
+ f"archive CSV row {row_number} first trade ID exceeds last trade ID"
1238
+ )
1239
+ if previous_trade_id is not None and aggregate_id != previous_trade_id + 1:
1240
+ raise BinanceArchivePayloadError(
1241
+ f"archive aggregate trade IDs are noncontiguous at row {row_number}"
1242
+ )
1243
+ raw_timestamp = _parse_unsigned(fields[5], label=f"row {row_number} timestamp")
1244
+ multiplier = 1_000 if acquired.request.date >= _MICROSECOND_ARCHIVE_START else 1_000_000
1245
+ if raw_timestamp > _MAX_INT64 // multiplier:
1246
+ raise BinanceArchivePayloadError(f"archive CSV row {row_number} timestamp overflows ns")
1247
+ event_ts_ns = raw_timestamp * multiplier
1248
+ if not start_ns <= event_ts_ns < end_ns:
1249
+ raise BinanceArchivePayloadError(
1250
+ f"archive CSV row {row_number} timestamp is outside declared UTC date"
1251
+ )
1252
+ if previous_event_ts_ns is not None and event_ts_ns < previous_event_ts_ns:
1253
+ raise BinanceArchivePayloadError(f"archive event time reverses at row {row_number}")
1254
+ price, price_ticks = _scaled_decimal(
1255
+ fields[1], quantum=acquired.request.tick_size, label=f"row {row_number} price"
1256
+ )
1257
+ quantity, quantity_lots = _scaled_decimal(
1258
+ fields[2], quantum=acquired.request.lot_size, label=f"row {row_number} quantity"
1259
+ )
1260
+ buyer_is_maker = _parse_boolean(fields[6], label=f"row {row_number} buyer-maker flag")
1261
+ _parse_boolean(fields[7], label=f"row {row_number} best-match flag")
1262
+ record: dict[str, object] = {
1263
+ "schema_version": SCHEMA_VERSION,
1264
+ "venue": "binance_spot",
1265
+ "symbol": acquired.request.symbol,
1266
+ "event_ts_ns": event_ts_ns,
1267
+ "received_ts_ns": None,
1268
+ "available_ts_ns": event_ts_ns,
1269
+ "availability_basis": "exchange_event_time_proxy",
1270
+ "capture_seq": None,
1271
+ "continuity_id": acquired.request.continuity_id,
1272
+ "trade_id": aggregate_id,
1273
+ "first_trade_id": first_trade_id,
1274
+ "last_trade_id": last_trade_id,
1275
+ "price_ticks": price_ticks,
1276
+ "quantity_lots": quantity_lots,
1277
+ "tick_size": float(acquired.request.tick_size),
1278
+ "lot_size": float(acquired.request.lot_size),
1279
+ "price": float(price),
1280
+ "quantity": float(quantity),
1281
+ "quote_quantity": float(price * quantity),
1282
+ "aggressor_side": "sell" if buyer_is_maker else "buy",
1283
+ "buyer_is_maker": buyer_is_maker,
1284
+ "source_artifact_id": acquired.archive_artifact.sha256,
1285
+ }
1286
+ return record, aggregate_id, event_ts_ns
1287
+
1288
+
1289
+ def _sha256_open_file(source: BinaryIO) -> str:
1290
+ digest = hashlib.sha256()
1291
+ source.seek(0)
1292
+ while chunk := source.read(1024 * 1024):
1293
+ digest.update(chunk)
1294
+ source.seek(0)
1295
+ return digest.hexdigest()
1296
+
1297
+
1298
+ def _stream_normalized_batches(
1299
+ acquired: AcquiredDailyArchive,
1300
+ *,
1301
+ batch_rows: int,
1302
+ before_member_open: Callable[[], None] | None,
1303
+ ) -> Generator[pa.RecordBatch, None, DailyArchiveSummary]:
1304
+ if acquired.requires_member_open_guard and before_member_open is None:
1305
+ raise BinanceArchivePayloadError("held-out archive requires a member-open authority guard")
1306
+ archive_path = acquired.archive_artifact.path
1307
+ nofollow = getattr(os, "O_NOFOLLOW", 0)
1308
+ try:
1309
+ raw_descriptor = os.open(archive_path, os.O_RDONLY | nofollow)
1310
+ except OSError as exc:
1311
+ raise BinanceArchivePayloadError("archive bytes are unavailable after acquisition") from exc
1312
+ try:
1313
+ archive_source = os.fdopen(raw_descriptor, "rb")
1314
+ except BaseException:
1315
+ os.close(raw_descriptor)
1316
+ raise
1317
+
1318
+ start_ns, end_ns = _day_bounds_ns(acquired.request.date)
1319
+ rows = 0
1320
+ first_trade_id: int | None = None
1321
+ last_trade_id: int | None = None
1322
+ first_event_ts_ns: int | None = None
1323
+ last_event_ts_ns: int | None = None
1324
+ records: list[dict[str, object]] = []
1325
+ expanded_bytes = 0
1326
+ with archive_source:
1327
+ try:
1328
+ observed = os.fstat(archive_source.fileno())
1329
+ if not stat.S_ISREG(observed.st_mode):
1330
+ raise BinanceArchivePayloadError("archive bytes are not a regular file")
1331
+ if observed.st_size != acquired.archive_artifact.bytes:
1332
+ raise BinanceArchivePayloadError("archive bytes changed after acquisition")
1333
+ if _sha256_open_file(archive_source) != acquired.archive_artifact.sha256:
1334
+ raise BinanceArchivePayloadError("archive checksum changed after acquisition")
1335
+ descriptor = _validate_zip_structure_handle(
1336
+ archive_source,
1337
+ observed.st_size,
1338
+ expected_member=acquired.request.member_name,
1339
+ max_uncompressed_bytes=acquired.limits.max_uncompressed_bytes,
1340
+ )
1341
+ if descriptor.declared_uncompressed_bytes != acquired.declared_uncompressed_bytes:
1342
+ raise BinanceArchivePayloadError(
1343
+ "archive uncompressed-size claim changed after acquisition"
1344
+ )
1345
+ archive_source.seek(0)
1346
+ archive_context = zipfile.ZipFile(archive_source)
1347
+ except BinanceArchivePayloadError:
1348
+ raise
1349
+ except (OSError, RuntimeError, ValueError, zipfile.BadZipFile) as exc:
1350
+ raise BinanceArchivePayloadError("cannot stream archive CSV safely") from exc
1351
+ with archive_context as archive:
1352
+ # The same already-hashed file descriptor backs both ZipFile and
1353
+ # member decompression. The path may change, but the guarded bytes
1354
+ # cannot switch inode between authority verification and open.
1355
+ if before_member_open is not None:
1356
+ before_member_open()
1357
+ try:
1358
+ with archive.open(descriptor.member_name, "r") as member:
1359
+ lines = _line_chunks(
1360
+ member,
1361
+ max_uncompressed_bytes=acquired.limits.max_uncompressed_bytes,
1362
+ chunk_bytes=acquired.limits.transfer_chunk_bytes,
1363
+ max_line_bytes=acquired.limits.max_csv_line_bytes,
1364
+ )
1365
+ while True:
1366
+ try:
1367
+ line = next(lines)
1368
+ except StopIteration as stop:
1369
+ expanded_bytes = int(stop.value)
1370
+ break
1371
+ row_number = rows + 1
1372
+ record, trade_id, event_ts_ns = _record_from_line(
1373
+ line,
1374
+ row_number=row_number,
1375
+ acquired=acquired,
1376
+ previous_trade_id=last_trade_id,
1377
+ previous_event_ts_ns=last_event_ts_ns,
1378
+ start_ns=start_ns,
1379
+ end_ns=end_ns,
1380
+ )
1381
+ if first_trade_id is None:
1382
+ first_trade_id = trade_id
1383
+ first_event_ts_ns = event_ts_ns
1384
+ last_trade_id = trade_id
1385
+ last_event_ts_ns = event_ts_ns
1386
+ records.append(record)
1387
+ rows += 1
1388
+ if len(records) == batch_rows:
1389
+ table = table_from_records("trades", records)
1390
+ batches = table.to_batches(max_chunksize=batch_rows)
1391
+ if len(batches) != 1 or batches[0].num_rows > batch_rows:
1392
+ raise BinanceArchivePayloadError(
1393
+ "archive normalizer violated its RecordBatch bound"
1394
+ )
1395
+ yield batches[0]
1396
+ records = []
1397
+ if records:
1398
+ table = table_from_records("trades", records)
1399
+ batches = table.to_batches(max_chunksize=batch_rows)
1400
+ if len(batches) != 1 or batches[0].num_rows > batch_rows:
1401
+ raise BinanceArchivePayloadError(
1402
+ "archive normalizer violated its RecordBatch bound"
1403
+ )
1404
+ yield batches[0]
1405
+ except BinanceArchivePayloadError:
1406
+ raise
1407
+ except (
1408
+ OSError,
1409
+ RuntimeError,
1410
+ UnicodeError,
1411
+ ValueError,
1412
+ OverflowError,
1413
+ zipfile.BadZipFile,
1414
+ ) as exc:
1415
+ raise BinanceArchivePayloadError("cannot stream archive CSV safely") from exc
1416
+
1417
+ if (
1418
+ rows < 1
1419
+ or first_trade_id is None
1420
+ or last_trade_id is None
1421
+ or first_event_ts_ns is None
1422
+ or last_event_ts_ns is None
1423
+ ):
1424
+ raise BinanceArchivePayloadError("archive CSV contains no trade rows")
1425
+ if expanded_bytes != acquired.declared_uncompressed_bytes:
1426
+ raise BinanceArchivePayloadError(
1427
+ "streamed archive bytes disagree with ZIP uncompressed-size claim"
1428
+ )
1429
+ return DailyArchiveSummary(
1430
+ symbol=acquired.request.symbol,
1431
+ date=acquired.request.date.isoformat(),
1432
+ rows=rows,
1433
+ first_trade_id=first_trade_id,
1434
+ last_trade_id=last_trade_id,
1435
+ first_event_ts_ns=first_event_ts_ns,
1436
+ last_event_ts_ns=last_event_ts_ns,
1437
+ compressed_bytes=acquired.archive_artifact.bytes,
1438
+ expanded_bytes=expanded_bytes,
1439
+ source_archive_sha256=acquired.archive_artifact.sha256,
1440
+ member_name=descriptor.member_name,
1441
+ continuity_id=acquired.request.continuity_id,
1442
+ )
1443
+
1444
+
1445
+ __all__ = [
1446
+ "AcquiredDailyArchive",
1447
+ "ArchiveAcquisitionReasonCode",
1448
+ "ArchiveDownloadLimits",
1449
+ "BinanceArchiveClient",
1450
+ "BinanceArchiveContractError",
1451
+ "BinanceArchiveError",
1452
+ "BinanceArchiveHTTPError",
1453
+ "BinanceArchivePayloadError",
1454
+ "DailyArchiveRequest",
1455
+ "DailyArchiveSummary",
1456
+ "DailyArchiveTradeStream",
1457
+ "RawArchiveArtifact",
1458
+ "RetryPolicy",
1459
+ ]
Microstructure/src/microstructure/data/book.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure snapshot-plus-delta order-book reconstruction.
2
+
3
+ Sequence order is authoritative. Exchange timestamps are never used to sort
4
+ updates, so a timestamp reversal is reportable without concealing or inventing
5
+ book continuity.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from collections.abc import Mapping
12
+ from dataclasses import dataclass
13
+ from typing import Literal
14
+
15
+ import pyarrow as pa # type: ignore[import-untyped]
16
+
17
+ from microstructure.data.schemas import SCHEMA_VERSION, table_from_records
18
+
19
+ BookLevel = tuple[int, int]
20
+ _MAX_BOOK_LEVELS_PER_SIDE = 10_000
21
+
22
+
23
+ class BookInvariantError(ValueError):
24
+ """Raised when a snapshot or delta contains an impossible book level."""
25
+
26
+
27
+ class _BookCapacityError(BookInvariantError):
28
+ """Raised before retained book state can exceed its hard memory bound."""
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class BookSnapshot:
33
+ venue: str
34
+ symbol: str
35
+ snapshot_id: str
36
+ request_ts_ns: int
37
+ received_ts_ns: int
38
+ available_ts_ns: int
39
+ continuity_id: str
40
+ last_update_id: int
41
+ depth_limit: int
42
+ bids: tuple[BookLevel, ...]
43
+ asks: tuple[BookLevel, ...]
44
+ tick_size: float
45
+ lot_size: float
46
+ source_artifact_id: str
47
+
48
+ def to_record(self) -> dict[str, object]:
49
+ return {
50
+ "schema_version": SCHEMA_VERSION,
51
+ "venue": self.venue,
52
+ "symbol": self.symbol,
53
+ "snapshot_id": self.snapshot_id,
54
+ "request_ts_ns": self.request_ts_ns,
55
+ "received_ts_ns": self.received_ts_ns,
56
+ "available_ts_ns": self.available_ts_ns,
57
+ "continuity_id": self.continuity_id,
58
+ "last_update_id": self.last_update_id,
59
+ "depth_limit": self.depth_limit,
60
+ "bids": [
61
+ {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.bids
62
+ ],
63
+ "asks": [
64
+ {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.asks
65
+ ],
66
+ "tick_size": self.tick_size,
67
+ "lot_size": self.lot_size,
68
+ "source_artifact_id": self.source_artifact_id,
69
+ }
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class DepthDelta:
74
+ venue: str
75
+ symbol: str
76
+ event_ts_ns: int
77
+ received_ts_ns: int | None
78
+ available_ts_ns: int
79
+ availability_basis: str
80
+ capture_seq: int | None
81
+ continuity_id: str
82
+ first_update_id: int
83
+ last_update_id: int
84
+ previous_update_id: int | None
85
+ bids: tuple[BookLevel, ...]
86
+ asks: tuple[BookLevel, ...]
87
+ tick_size: float
88
+ lot_size: float
89
+ source_artifact_id: str
90
+
91
+ def to_record(self) -> dict[str, object]:
92
+ return {
93
+ "schema_version": SCHEMA_VERSION,
94
+ "venue": self.venue,
95
+ "symbol": self.symbol,
96
+ "event_ts_ns": self.event_ts_ns,
97
+ "received_ts_ns": self.received_ts_ns,
98
+ "available_ts_ns": self.available_ts_ns,
99
+ "availability_basis": self.availability_basis,
100
+ "capture_seq": self.capture_seq,
101
+ "continuity_id": self.continuity_id,
102
+ "first_update_id": self.first_update_id,
103
+ "last_update_id": self.last_update_id,
104
+ "previous_update_id": self.previous_update_id,
105
+ "bids": [
106
+ {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.bids
107
+ ],
108
+ "asks": [
109
+ {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.asks
110
+ ],
111
+ "tick_size": self.tick_size,
112
+ "lot_size": self.lot_size,
113
+ "source_artifact_id": self.source_artifact_id,
114
+ }
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class SequenceGap:
119
+ venue: str
120
+ symbol: str
121
+ continuity_id: str
122
+ expected_sequence: int
123
+ observed_sequence_start: int
124
+ observed_sequence_end: int
125
+ missing_start: int
126
+ missing_end: int
127
+ detected_ts_ns: int
128
+ reason: str
129
+ source_artifact_id: str
130
+
131
+ def to_record(self) -> dict[str, object]:
132
+ return {
133
+ "schema_version": SCHEMA_VERSION,
134
+ "venue": self.venue,
135
+ "symbol": self.symbol,
136
+ "continuity_id": self.continuity_id,
137
+ "expected_sequence": self.expected_sequence,
138
+ "observed_sequence_start": self.observed_sequence_start,
139
+ "observed_sequence_end": self.observed_sequence_end,
140
+ "missing_start": self.missing_start,
141
+ "missing_end": self.missing_end,
142
+ "detected_ts_ns": self.detected_ts_ns,
143
+ "reason": self.reason,
144
+ "source_artifact_id": self.source_artifact_id,
145
+ }
146
+
147
+
148
+ @dataclass(frozen=True, slots=True)
149
+ class ReconstructionResult:
150
+ status: Literal["LIVE", "GAPPED", "INVALID"]
151
+ observations: pa.Table
152
+ gaps: pa.Table
153
+ stale_events: int
154
+ final_update_id: int
155
+
156
+
157
+ ReconstructionOutcome = Literal[
158
+ "OBSERVED",
159
+ "STALE",
160
+ "GAP",
161
+ "INVALID",
162
+ "EXCLUDED_AFTER_TERMINAL",
163
+ ]
164
+
165
+
166
+ @dataclass(frozen=True, slots=True)
167
+ class ReconstructionStep:
168
+ """Bounded result of applying one delta to one continuity epoch."""
169
+
170
+ outcome: ReconstructionOutcome
171
+ observation: Mapping[str, object] | None
172
+ gap: SequenceGap | None
173
+
174
+
175
+ def _levels_to_book(levels: tuple[BookLevel, ...], side: str) -> dict[int, int]:
176
+ if len(levels) > _MAX_BOOK_LEVELS_PER_SIDE:
177
+ raise _BookCapacityError(
178
+ f"{side} snapshot exceeds {_MAX_BOOK_LEVELS_PER_SIDE} retained levels"
179
+ )
180
+ result: dict[int, int] = {}
181
+ for price, quantity in levels:
182
+ if price <= 0:
183
+ raise BookInvariantError(f"{side} snapshot price must be positive: {price}")
184
+ if quantity <= 0:
185
+ raise BookInvariantError(f"{side} snapshot quantity must be positive: {quantity}")
186
+ if price in result:
187
+ raise BookInvariantError(f"duplicate {side} snapshot price: {price}")
188
+ result[price] = quantity
189
+ if not result:
190
+ raise BookInvariantError(f"{side} snapshot must not be empty")
191
+ return result
192
+
193
+
194
+ def _apply_side(book: dict[int, int], changes: tuple[BookLevel, ...], side: str) -> None:
195
+ for price, quantity in changes:
196
+ if price <= 0:
197
+ raise BookInvariantError(f"{side} delta price must be positive: {price}")
198
+ if quantity < 0:
199
+ raise BookInvariantError(f"{side} delta quantity must not be negative: {quantity}")
200
+ if quantity == 0:
201
+ book.pop(price, None)
202
+ else:
203
+ book[price] = quantity
204
+ if len(book) > _MAX_BOOK_LEVELS_PER_SIDE:
205
+ raise _BookCapacityError(f"{side} book exceeds {_MAX_BOOK_LEVELS_PER_SIDE} retained levels")
206
+
207
+
208
+ def _depth(book: dict[int, int], *, bids: bool, levels: int, lot_size: float) -> float:
209
+ ordered = sorted(book, reverse=bids)[:levels]
210
+ return sum(book[price] for price in ordered) * lot_size
211
+
212
+
213
+ def _queue_imbalance(bid_depth: float, ask_depth: float) -> float:
214
+ total = bid_depth + ask_depth
215
+ return (bid_depth - ask_depth) / total if total > 0.0 else 0.0
216
+
217
+
218
+ def _observation(
219
+ *,
220
+ snapshot: BookSnapshot,
221
+ delta: DepthDelta,
222
+ bids: dict[int, int],
223
+ asks: dict[int, int],
224
+ valid: bool,
225
+ ) -> dict[str, object]:
226
+ if not bids or not asks:
227
+ raise BookInvariantError("delta removed every price level from one side of the book")
228
+ best_bid_ticks = max(bids)
229
+ best_ask_ticks = min(asks)
230
+ bid_quantity_lots = bids[best_bid_ticks]
231
+ ask_quantity_lots = asks[best_ask_ticks]
232
+ best_bid = best_bid_ticks * snapshot.tick_size
233
+ best_ask = best_ask_ticks * snapshot.tick_size
234
+ bid_quantity = bid_quantity_lots * snapshot.lot_size
235
+ ask_quantity = ask_quantity_lots * snapshot.lot_size
236
+ mid_price = (best_bid + best_ask) / 2.0
237
+ microprice = (best_ask * bid_quantity + best_bid * ask_quantity) / (bid_quantity + ask_quantity)
238
+ depth_bid_1 = _depth(bids, bids=True, levels=1, lot_size=snapshot.lot_size)
239
+ depth_ask_1 = _depth(asks, bids=False, levels=1, lot_size=snapshot.lot_size)
240
+ depth_bid_5 = _depth(bids, bids=True, levels=5, lot_size=snapshot.lot_size)
241
+ depth_ask_5 = _depth(asks, bids=False, levels=5, lot_size=snapshot.lot_size)
242
+ depth_bid_10 = _depth(bids, bids=True, levels=10, lot_size=snapshot.lot_size)
243
+ depth_ask_10 = _depth(asks, bids=False, levels=10, lot_size=snapshot.lot_size)
244
+ return {
245
+ "schema_version": SCHEMA_VERSION,
246
+ "venue": snapshot.venue,
247
+ "symbol": snapshot.symbol,
248
+ "event_ts_ns": delta.event_ts_ns,
249
+ "received_ts_ns": delta.received_ts_ns,
250
+ "available_ts_ns": max(snapshot.available_ts_ns, delta.available_ts_ns),
251
+ "availability_basis": delta.availability_basis,
252
+ "capture_seq": delta.capture_seq,
253
+ "continuity_id": snapshot.continuity_id,
254
+ "sequence_start": delta.first_update_id,
255
+ "sequence_end": delta.last_update_id,
256
+ "is_valid": valid,
257
+ "best_bid_ticks": best_bid_ticks,
258
+ "best_ask_ticks": best_ask_ticks,
259
+ "bid_quantity_lots": bid_quantity_lots,
260
+ "ask_quantity_lots": ask_quantity_lots,
261
+ "tick_size": snapshot.tick_size,
262
+ "lot_size": snapshot.lot_size,
263
+ "best_bid": best_bid,
264
+ "best_ask": best_ask,
265
+ "bid_quantity": bid_quantity,
266
+ "ask_quantity": ask_quantity,
267
+ "spread": best_ask - best_bid,
268
+ "mid_price": mid_price,
269
+ "microprice": microprice,
270
+ "depth_bid_1": depth_bid_1,
271
+ "depth_ask_1": depth_ask_1,
272
+ "depth_bid_5": depth_bid_5,
273
+ "depth_ask_5": depth_ask_5,
274
+ "depth_bid_10": depth_bid_10,
275
+ "depth_ask_10": depth_ask_10,
276
+ "queue_imbalance_1": _queue_imbalance(depth_bid_1, depth_ask_1),
277
+ "queue_imbalance_5": _queue_imbalance(depth_bid_5, depth_ask_5),
278
+ "queue_imbalance_10": _queue_imbalance(depth_bid_10, depth_ask_10),
279
+ "source_artifact_id": delta.source_artifact_id,
280
+ }
281
+
282
+
283
+ def _gap(snapshot: BookSnapshot, delta: DepthDelta, expected: int, reason: str) -> SequenceGap:
284
+ missing_end = max(expected, delta.first_update_id - 1)
285
+ return SequenceGap(
286
+ venue=snapshot.venue,
287
+ symbol=snapshot.symbol,
288
+ continuity_id=snapshot.continuity_id,
289
+ expected_sequence=expected,
290
+ observed_sequence_start=delta.first_update_id,
291
+ observed_sequence_end=delta.last_update_id,
292
+ missing_start=expected,
293
+ missing_end=missing_end,
294
+ detected_ts_ns=delta.available_ts_ns,
295
+ reason=reason,
296
+ source_artifact_id=delta.source_artifact_id,
297
+ )
298
+
299
+
300
+ class IncrementalBookReconstructor:
301
+ """Stateful O(book-depth) snapshot-plus-delta reconstruction.
302
+
303
+ The class retains only the current epoch's book. Every input delta returns
304
+ an explicit outcome; after a gap or invalidation, later deltas receive an
305
+ ``EXCLUDED_AFTER_TERMINAL`` gap record rather than disappearing silently.
306
+ """
307
+
308
+ def __init__(self, snapshot: BookSnapshot) -> None:
309
+ if snapshot.available_ts_ns < snapshot.received_ts_ns:
310
+ raise BookInvariantError("snapshot cannot be available before it was received")
311
+ if (
312
+ not math.isfinite(snapshot.tick_size)
313
+ or not math.isfinite(snapshot.lot_size)
314
+ or snapshot.tick_size <= 0
315
+ or snapshot.lot_size <= 0
316
+ ):
317
+ raise BookInvariantError("snapshot tick and lot sizes must be finite and positive")
318
+ if snapshot.depth_limit < 1 or snapshot.depth_limit > _MAX_BOOK_LEVELS_PER_SIDE:
319
+ raise BookInvariantError(
320
+ f"snapshot depth_limit must be within 1..{_MAX_BOOK_LEVELS_PER_SIDE}"
321
+ )
322
+ bids = _levels_to_book(snapshot.bids, "bid")
323
+ asks = _levels_to_book(snapshot.asks, "ask")
324
+ if max(bids) >= min(asks):
325
+ raise BookInvariantError("snapshot is crossed or locked")
326
+ self.snapshot = snapshot
327
+ self._bids = bids
328
+ self._asks = asks
329
+ self._last_update_id = snapshot.last_update_id
330
+ self._stale_events = 0
331
+ self._status: Literal["LIVE", "GAPPED", "INVALID"] = "LIVE"
332
+
333
+ @property
334
+ def status(self) -> Literal["LIVE", "GAPPED", "INVALID"]:
335
+ return self._status
336
+
337
+ @property
338
+ def stale_events(self) -> int:
339
+ return self._stale_events
340
+
341
+ @property
342
+ def final_update_id(self) -> int:
343
+ return self._last_update_id
344
+
345
+ def _validate_identity(self, delta: DepthDelta) -> None:
346
+ if delta.venue != self.snapshot.venue or delta.symbol != self.snapshot.symbol:
347
+ raise BookInvariantError("delta venue/symbol does not match snapshot")
348
+ if delta.tick_size != self.snapshot.tick_size or delta.lot_size != self.snapshot.lot_size:
349
+ raise BookInvariantError("delta tick/lot scales do not match snapshot metadata")
350
+
351
+ def update(self, delta: DepthDelta) -> ReconstructionStep:
352
+ """Apply exactly one delta and return its explicit reconstruction disposition."""
353
+ self._validate_identity(delta)
354
+ expected = self._last_update_id + 1
355
+ if self._status != "LIVE":
356
+ return ReconstructionStep(
357
+ outcome="EXCLUDED_AFTER_TERMINAL",
358
+ observation=None,
359
+ gap=_gap(
360
+ self.snapshot,
361
+ delta,
362
+ expected,
363
+ f"epoch_already_{self._status.lower()}",
364
+ ),
365
+ )
366
+ if delta.continuity_id != self.snapshot.continuity_id:
367
+ self._status = "GAPPED"
368
+ return ReconstructionStep(
369
+ outcome="GAP",
370
+ observation=None,
371
+ gap=_gap(self.snapshot, delta, expected, "continuity_id_mismatch"),
372
+ )
373
+ if delta.last_update_id < delta.first_update_id:
374
+ self._status = "INVALID"
375
+ return ReconstructionStep(
376
+ outcome="INVALID",
377
+ observation=None,
378
+ gap=_gap(self.snapshot, delta, expected, "invalid_sequence_range"),
379
+ )
380
+ if delta.last_update_id <= self._last_update_id:
381
+ self._stale_events += 1
382
+ return ReconstructionStep(outcome="STALE", observation=None, gap=None)
383
+ if (
384
+ delta.previous_update_id is not None
385
+ and delta.previous_update_id != self._last_update_id
386
+ ):
387
+ self._status = "GAPPED"
388
+ return ReconstructionStep(
389
+ outcome="GAP",
390
+ observation=None,
391
+ gap=_gap(self.snapshot, delta, expected, "previous_update_id_mismatch"),
392
+ )
393
+ if delta.first_update_id > expected:
394
+ self._status = "GAPPED"
395
+ return ReconstructionStep(
396
+ outcome="GAP",
397
+ observation=None,
398
+ gap=_gap(self.snapshot, delta, expected, "forward_sequence_gap"),
399
+ )
400
+ if delta.last_update_id < expected:
401
+ self._stale_events += 1
402
+ return ReconstructionStep(outcome="STALE", observation=None, gap=None)
403
+
404
+ candidate_bids = self._bids.copy()
405
+ candidate_asks = self._asks.copy()
406
+ try:
407
+ _apply_side(candidate_bids, delta.bids, "bid")
408
+ _apply_side(candidate_asks, delta.asks, "ask")
409
+ if not candidate_bids or not candidate_asks:
410
+ raise BookInvariantError("delta emptied one side of the order book")
411
+ crossed = max(candidate_bids) >= min(candidate_asks)
412
+ observation = _observation(
413
+ snapshot=self.snapshot,
414
+ delta=delta,
415
+ bids=candidate_bids,
416
+ asks=candidate_asks,
417
+ valid=not crossed,
418
+ )
419
+ except _BookCapacityError:
420
+ self._status = "INVALID"
421
+ return ReconstructionStep(
422
+ outcome="INVALID",
423
+ observation=None,
424
+ gap=_gap(self.snapshot, delta, expected, "book_level_limit_exceeded"),
425
+ )
426
+ except BookInvariantError:
427
+ self._status = "INVALID"
428
+ return ReconstructionStep(
429
+ outcome="INVALID",
430
+ observation=None,
431
+ gap=_gap(self.snapshot, delta, expected, "invalid_book_level"),
432
+ )
433
+
434
+ self._bids = candidate_bids
435
+ self._asks = candidate_asks
436
+ self._last_update_id = delta.last_update_id
437
+ if crossed:
438
+ self._status = "INVALID"
439
+ return ReconstructionStep(
440
+ outcome="INVALID",
441
+ observation=observation,
442
+ gap=_gap(self.snapshot, delta, expected, "crossed_or_locked_book"),
443
+ )
444
+ return ReconstructionStep(outcome="OBSERVED", observation=observation, gap=None)
445
+
446
+
447
+ def reconstruct_snapshot_and_deltas(
448
+ snapshot: BookSnapshot, deltas: tuple[DepthDelta, ...] | list[DepthDelta]
449
+ ) -> ReconstructionResult:
450
+ """Apply buffered/live deltas until an explicit gap or invariant failure.
451
+
452
+ Stale events (``u <= last_update_id``) are counted and ignored. A usable
453
+ event must cover the next expected update ID, allowing safe overlap. A
454
+ forward gap invalidates the continuity epoch; later events are not emitted.
455
+ """
456
+ reconstructor = IncrementalBookReconstructor(snapshot)
457
+ observation_records: list[dict[str, object]] = []
458
+ gaps: list[SequenceGap] = []
459
+
460
+ for delta in deltas:
461
+ step = reconstructor.update(delta)
462
+ if step.observation is not None:
463
+ observation_records.append(dict(step.observation))
464
+ if step.gap is not None:
465
+ gaps.append(step.gap)
466
+ if step.outcome in {"GAP", "INVALID"}:
467
+ break
468
+
469
+ return ReconstructionResult(
470
+ status=reconstructor.status,
471
+ observations=table_from_records("book_observations", observation_records),
472
+ gaps=table_from_records("sequence_gaps", [item.to_record() for item in gaps]),
473
+ stale_events=reconstructor.stale_events,
474
+ final_update_id=reconstructor.final_update_id,
475
+ )
476
+
477
+
478
+ def snapshots_table(snapshots: list[BookSnapshot] | tuple[BookSnapshot, ...]) -> pa.Table:
479
+ return table_from_records("book_snapshots", [snapshot.to_record() for snapshot in snapshots])
480
+
481
+
482
+ def deltas_table(deltas: list[DepthDelta] | tuple[DepthDelta, ...]) -> pa.Table:
483
+ return table_from_records("depth_deltas", [delta.to_record() for delta in deltas])
Microstructure/src/microstructure/data/evidence_budget.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fail-closed accounting for retained raw-evidence bytes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import threading
7
+ from collections.abc import Iterator
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+
11
+
12
+ class EvidenceBudgetError(RuntimeError):
13
+ """Base error for retained-evidence budget failures."""
14
+
15
+
16
+ class EvidenceBudgetExceeded(EvidenceBudgetError):
17
+ """Raised before a retained artifact would exceed its byte budget."""
18
+
19
+
20
+ class EvidenceBudgetStateError(EvidenceBudgetError):
21
+ """Raised when a reservation is finalized more than once."""
22
+
23
+
24
+ def _scan_regular_file_bytes(root: Path) -> int:
25
+ """Return logical bytes below *root* without following symbolic links."""
26
+ if root.is_symlink():
27
+ raise EvidenceBudgetError(f"evidence-budget root must not be a symlink: {root}")
28
+ if not root.exists():
29
+ return 0
30
+ if not root.is_dir():
31
+ raise EvidenceBudgetError(f"evidence-budget root is not a directory: {root}")
32
+
33
+ total = 0
34
+ pending = [root]
35
+ try:
36
+ while pending:
37
+ directory = pending.pop()
38
+ with os.scandir(directory) as entries:
39
+ for entry in entries:
40
+ if entry.is_symlink():
41
+ continue
42
+ if entry.is_dir(follow_symlinks=False):
43
+ pending.append(Path(entry.path))
44
+ elif entry.is_file(follow_symlinks=False):
45
+ total += entry.stat(follow_symlinks=False).st_size
46
+ except OSError as exc:
47
+ raise EvidenceBudgetError(f"cannot scan retained evidence below {root}") from exc
48
+ return total
49
+
50
+
51
+ class EvidenceReservation:
52
+ """One exclusive byte reservation, committed only after durable retention."""
53
+
54
+ __slots__ = ("_budget", "_bytes_reserved", "_label", "_state")
55
+
56
+ def __init__(
57
+ self,
58
+ budget: RetainedEvidenceBudget,
59
+ bytes_reserved: int,
60
+ label: str,
61
+ ) -> None:
62
+ self._budget = budget
63
+ self._bytes_reserved = bytes_reserved
64
+ self._label = label
65
+ self._state = "active"
66
+
67
+ @property
68
+ def bytes_reserved(self) -> int:
69
+ return self._bytes_reserved
70
+
71
+ @property
72
+ def label(self) -> str:
73
+ return self._label
74
+
75
+ @property
76
+ def active(self) -> bool:
77
+ return self._state == "active"
78
+
79
+ def commit(self) -> None:
80
+ """Charge the reservation after its bytes have been retained."""
81
+ if self._state != "active":
82
+ raise EvidenceBudgetStateError(f"reservation is already {self._state}")
83
+ self._budget._commit(self._bytes_reserved)
84
+ self._state = "committed"
85
+
86
+ def release(self) -> None:
87
+ """Return an unused reservation to the available budget."""
88
+ if self._state != "active":
89
+ raise EvidenceBudgetStateError(f"reservation is already {self._state}")
90
+ self._budget._release(self._bytes_reserved)
91
+ self._state = "released"
92
+
93
+ def __enter__(self) -> EvidenceReservation:
94
+ return self
95
+
96
+ def __exit__(
97
+ self,
98
+ exc_type: type[BaseException] | None,
99
+ exc_value: BaseException | None,
100
+ traceback: object | None,
101
+ ) -> None:
102
+ if self.active:
103
+ self.release()
104
+
105
+
106
+ class RetainedEvidenceBudget:
107
+ """Thread-safe accounting for a bounded directory of immutable evidence.
108
+
109
+ Existing regular files are counted once at construction. Symbolic links
110
+ are neither counted nor traversed. Callers must share one instance across
111
+ writers targeting the same root so outstanding reservations cannot
112
+ oversubscribe the limit.
113
+ """
114
+
115
+ __slots__ = ("_limit_bytes", "_lock", "_reserved_bytes", "_root", "_used_bytes")
116
+
117
+ def __init__(self, root: str | Path, limit_bytes: int) -> None:
118
+ if isinstance(limit_bytes, bool) or limit_bytes < 0:
119
+ raise ValueError("limit_bytes must be a nonnegative integer")
120
+ self._root = Path(root).expanduser().absolute()
121
+ self._limit_bytes = limit_bytes
122
+ self._lock = threading.RLock()
123
+ self._reserved_bytes = 0
124
+ self._used_bytes = _scan_regular_file_bytes(self._root)
125
+ if self._used_bytes > self._limit_bytes:
126
+ raise EvidenceBudgetExceeded(
127
+ "preexisting retained evidence exceeds the configured byte budget: "
128
+ f"used={self._used_bytes}, limit={self._limit_bytes}, root={self._root}"
129
+ )
130
+
131
+ @property
132
+ def root(self) -> Path:
133
+ return self._root
134
+
135
+ @property
136
+ def limit_bytes(self) -> int:
137
+ return self._limit_bytes
138
+
139
+ @property
140
+ def used_bytes(self) -> int:
141
+ with self._lock:
142
+ return self._used_bytes
143
+
144
+ @property
145
+ def reserved_bytes(self) -> int:
146
+ with self._lock:
147
+ return self._reserved_bytes
148
+
149
+ @property
150
+ def remaining_bytes(self) -> int:
151
+ with self._lock:
152
+ return self._limit_bytes - self._used_bytes - self._reserved_bytes
153
+
154
+ def assert_contains(self, path: str | Path) -> None:
155
+ """Reject targets outside the budget root or below an in-root symlink."""
156
+ target = Path(os.path.abspath(Path(path).expanduser()))
157
+ if not target.is_relative_to(self._root):
158
+ raise EvidenceBudgetError(
159
+ f"retained-evidence target is outside budget root: target={target}, "
160
+ f"root={self._root}"
161
+ )
162
+ current = self._root
163
+ for component in target.relative_to(self._root).parts:
164
+ current /= component
165
+ if current.is_symlink():
166
+ raise EvidenceBudgetError(
167
+ f"retained-evidence target traverses a symlink: {current}"
168
+ )
169
+
170
+ @contextmanager
171
+ def write_transaction(self) -> Iterator[None]:
172
+ """Serialize deduplication checks, reservations, and artifact commits."""
173
+ with self._lock:
174
+ yield
175
+
176
+ def reserve(
177
+ self,
178
+ bytes_to_add: int,
179
+ *,
180
+ label: str = "retained evidence",
181
+ ) -> EvidenceReservation:
182
+ """Atomically reserve bytes or fail before the caller writes them."""
183
+ if isinstance(bytes_to_add, bool) or bytes_to_add < 0:
184
+ raise ValueError("bytes_to_add must be a nonnegative integer")
185
+ with self._lock:
186
+ projected = self._used_bytes + self._reserved_bytes + bytes_to_add
187
+ if projected > self._limit_bytes:
188
+ raise EvidenceBudgetExceeded(
189
+ f"{label} would exceed retained-evidence budget: "
190
+ f"requested={bytes_to_add}, used={self._used_bytes}, "
191
+ f"reserved={self._reserved_bytes}, limit={self._limit_bytes}, "
192
+ f"root={self._root}"
193
+ )
194
+ self._reserved_bytes += bytes_to_add
195
+ return EvidenceReservation(self, bytes_to_add, label)
196
+
197
+ def _commit(self, bytes_reserved: int) -> None:
198
+ with self._lock:
199
+ if bytes_reserved > self._reserved_bytes:
200
+ raise EvidenceBudgetStateError("reservation accounting underflow on commit")
201
+ self._reserved_bytes -= bytes_reserved
202
+ self._used_bytes += bytes_reserved
203
+
204
+ def _release(self, bytes_reserved: int) -> None:
205
+ with self._lock:
206
+ if bytes_reserved > self._reserved_bytes:
207
+ raise EvidenceBudgetStateError("reservation accounting underflow on release")
208
+ self._reserved_bytes -= bytes_reserved
Microstructure/src/microstructure/data/quality.py ADDED
@@ -0,0 +1,1103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Non-mutating data-quality rules with explicit, machine-readable findings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sqlite3
8
+ import tempfile
9
+ from collections.abc import Iterable, Mapping
10
+ from dataclasses import asdict, dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Literal, Protocol, TextIO
13
+
14
+ import pyarrow as pa # type: ignore[import-untyped]
15
+
16
+ from microstructure.data.schemas import ensure_schema, get_schema
17
+ from microstructure.provenance import utc_now_iso, write_json
18
+
19
+ Severity = Literal["ERROR", "WARNING"]
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class QualityFinding:
24
+ rule_id: str
25
+ severity: Severity
26
+ dataset: str
27
+ row_index: int | None
28
+ symbol: str | None
29
+ event_ts_ns: int | None
30
+ message: str
31
+ details: Mapping[str, Any]
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class ValidationReport:
36
+ dataset: str
37
+ rows_checked: int
38
+ findings: tuple[QualityFinding, ...]
39
+ total_errors: int | None = None
40
+ total_warnings: int | None = None
41
+ findings_jsonl_path: str | None = None
42
+
43
+ def __post_init__(self) -> None:
44
+ if self.rows_checked < 0:
45
+ raise ValueError("rows_checked must be non-negative")
46
+ if (self.total_errors is None) != (self.total_warnings is None):
47
+ raise ValueError("total_errors and total_warnings must be supplied together")
48
+ retained_errors = sum(item.severity == "ERROR" for item in self.findings)
49
+ retained_warnings = sum(item.severity == "WARNING" for item in self.findings)
50
+ if self.total_errors is not None and self.total_errors < retained_errors:
51
+ raise ValueError("total_errors cannot be smaller than retained error findings")
52
+ if self.total_warnings is not None and self.total_warnings < retained_warnings:
53
+ raise ValueError("total_warnings cannot be smaller than retained warning findings")
54
+
55
+ @property
56
+ def has_errors(self) -> bool:
57
+ return self.error_count > 0
58
+
59
+ @property
60
+ def error_count(self) -> int:
61
+ if self.total_errors is not None:
62
+ return self.total_errors
63
+ return sum(item.severity == "ERROR" for item in self.findings)
64
+
65
+ @property
66
+ def warning_count(self) -> int:
67
+ if self.total_warnings is not None:
68
+ return self.total_warnings
69
+ return sum(item.severity == "WARNING" for item in self.findings)
70
+
71
+ @property
72
+ def findings_truncated(self) -> bool:
73
+ """Whether ``findings`` is only an in-memory preview of the full result."""
74
+ return len(self.findings) < self.error_count + self.warning_count
75
+
76
+ def to_dict(self) -> dict[str, Any]:
77
+ payload: dict[str, Any] = {
78
+ "generated_at_utc": utc_now_iso(),
79
+ "dataset": self.dataset,
80
+ "rows_checked": self.rows_checked,
81
+ "summary": {"errors": self.error_count, "warnings": self.warning_count},
82
+ "findings": [asdict(item) for item in self.findings],
83
+ "mutation_policy": "observations were not changed or repaired",
84
+ }
85
+ if self.findings_truncated:
86
+ payload["findings_preview"] = {
87
+ "retained": len(self.findings),
88
+ "total": self.error_count + self.warning_count,
89
+ "truncated": True,
90
+ }
91
+ if self.findings_jsonl_path is not None:
92
+ payload["findings_jsonl_path"] = self.findings_jsonl_path
93
+ return payload
94
+
95
+ def write_json(self, path: str | Path) -> None:
96
+ write_json(path, self.to_dict())
97
+
98
+
99
+ class _FindingTarget(Protocol):
100
+ def append(self, finding: QualityFinding) -> None: ...
101
+
102
+
103
+ class _FindingAccumulator:
104
+ """Count every finding while retaining only a bounded in-memory preview."""
105
+
106
+ def __init__(
107
+ self,
108
+ *,
109
+ max_findings: int | None,
110
+ findings_jsonl_path: str | Path | None,
111
+ ) -> None:
112
+ if max_findings is not None and max_findings < 0:
113
+ raise ValueError("max_findings must be non-negative or None")
114
+ self._max_findings = max_findings
115
+ self._findings: list[QualityFinding] = []
116
+ self.error_count = 0
117
+ self.warning_count = 0
118
+ self.path = Path(findings_jsonl_path) if findings_jsonl_path is not None else None
119
+ self._temporary_path: Path | None = None
120
+ self._sink: TextIO | None = None
121
+ if self.path is not None:
122
+ self.path.parent.mkdir(parents=True, exist_ok=True)
123
+ descriptor, temporary_name = tempfile.mkstemp(
124
+ dir=self.path.parent,
125
+ prefix=f".{self.path.name}.",
126
+ suffix=".tmp",
127
+ text=True,
128
+ )
129
+ self._temporary_path = Path(temporary_name)
130
+ self._sink = os.fdopen(descriptor, "w", encoding="utf-8")
131
+
132
+ @property
133
+ def findings(self) -> tuple[QualityFinding, ...]:
134
+ return tuple(self._findings)
135
+
136
+ def append(self, finding: QualityFinding) -> None:
137
+ if finding.severity == "ERROR":
138
+ self.error_count += 1
139
+ else:
140
+ self.warning_count += 1
141
+ if self._max_findings is None or len(self._findings) < self._max_findings:
142
+ self._findings.append(finding)
143
+ if self._sink is not None:
144
+ self._sink.write(
145
+ json.dumps(
146
+ asdict(finding),
147
+ ensure_ascii=False,
148
+ separators=(",", ":"),
149
+ sort_keys=True,
150
+ )
151
+ )
152
+ self._sink.write("\n")
153
+
154
+ def flush(self) -> None:
155
+ if self._sink is not None:
156
+ self._sink.flush()
157
+
158
+ def publish(self) -> None:
159
+ if self._sink is not None:
160
+ self._sink.flush()
161
+ os.fsync(self._sink.fileno())
162
+ self._sink.close()
163
+ self._sink = None
164
+ if self.path is not None and self._temporary_path is not None:
165
+ os.replace(self._temporary_path, self.path)
166
+ self._temporary_path = None
167
+
168
+ def close(self) -> None:
169
+ if self._sink is not None:
170
+ self._sink.close()
171
+ self._sink = None
172
+ if self._temporary_path is not None:
173
+ self._temporary_path.unlink(missing_ok=True)
174
+ self._temporary_path = None
175
+
176
+
177
+ def _continuity_key(continuity_id: object) -> tuple[int, str]:
178
+ if continuity_id is None:
179
+ return (1, "")
180
+ return (0, str(continuity_id))
181
+
182
+
183
+ class _SpillState:
184
+ """Disk-backed exact state whose RAM use does not grow with row history."""
185
+
186
+ def __init__(self) -> None:
187
+ # An empty SQLite filename creates a private temporary on-disk database
188
+ # which is deleted when the connection closes.
189
+ self._connection = sqlite3.connect("")
190
+ self._connection.execute("PRAGMA cache_size = -2048")
191
+ self._connection.execute("PRAGMA temp_store = FILE")
192
+ self._connection.execute("PRAGMA journal_mode = OFF")
193
+ self._connection.execute("PRAGMA synchronous = OFF")
194
+ self._connection.executescript(
195
+ """
196
+ CREATE TABLE event_state (
197
+ venue TEXT NOT NULL,
198
+ symbol TEXT NOT NULL,
199
+ continuity_is_null INTEGER NOT NULL,
200
+ continuity_id TEXT NOT NULL,
201
+ event_ts_ns INTEGER NOT NULL,
202
+ received_ts_ns INTEGER,
203
+ row_index INTEGER NOT NULL,
204
+ PRIMARY KEY (venue, symbol, continuity_is_null, continuity_id)
205
+ ) WITHOUT ROWID;
206
+ CREATE TABLE sequence_state (
207
+ sequence_kind TEXT NOT NULL,
208
+ venue TEXT NOT NULL,
209
+ symbol TEXT NOT NULL,
210
+ continuity_is_null INTEGER NOT NULL,
211
+ continuity_id TEXT NOT NULL,
212
+ sequence_end INTEGER NOT NULL,
213
+ PRIMARY KEY (
214
+ sequence_kind,
215
+ venue,
216
+ symbol,
217
+ continuity_is_null,
218
+ continuity_id
219
+ )
220
+ ) WITHOUT ROWID;
221
+ CREATE TABLE trade_identity (
222
+ venue TEXT NOT NULL,
223
+ symbol TEXT NOT NULL,
224
+ trade_id INTEGER NOT NULL,
225
+ first_row INTEGER NOT NULL,
226
+ PRIMARY KEY (venue, symbol, trade_id)
227
+ ) WITHOUT ROWID;
228
+ """
229
+ )
230
+
231
+ def get_event(self, key: tuple[str, str, str | None]) -> tuple[int, int | None, int] | None:
232
+ continuity_is_null, continuity_id = _continuity_key(key[2])
233
+ result = self._connection.execute(
234
+ """
235
+ SELECT event_ts_ns, received_ts_ns, row_index
236
+ FROM event_state
237
+ WHERE venue = ? AND symbol = ?
238
+ AND continuity_is_null = ? AND continuity_id = ?
239
+ """,
240
+ (key[0], key[1], continuity_is_null, continuity_id),
241
+ ).fetchone()
242
+ if result is None:
243
+ return None
244
+ event_ts_ns, received_ts_ns, row_index = result
245
+ return (
246
+ int(event_ts_ns),
247
+ int(received_ts_ns) if received_ts_ns is not None else None,
248
+ int(row_index),
249
+ )
250
+
251
+ def set_event(
252
+ self,
253
+ key: tuple[str, str, str | None],
254
+ value: tuple[int, int | None, int],
255
+ ) -> None:
256
+ continuity_is_null, continuity_id = _continuity_key(key[2])
257
+ self._connection.execute(
258
+ """
259
+ INSERT INTO event_state (
260
+ venue, symbol, continuity_is_null, continuity_id,
261
+ event_ts_ns, received_ts_ns, row_index
262
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
263
+ ON CONFLICT (venue, symbol, continuity_is_null, continuity_id)
264
+ DO UPDATE SET
265
+ event_ts_ns = excluded.event_ts_ns,
266
+ received_ts_ns = excluded.received_ts_ns,
267
+ row_index = excluded.row_index
268
+ """,
269
+ (*key[:2], continuity_is_null, continuity_id, *value),
270
+ )
271
+
272
+ def get_sequence(self, kind: str, key: tuple[str, str, str | None]) -> int | None:
273
+ continuity_is_null, continuity_id = _continuity_key(key[2])
274
+ result = self._connection.execute(
275
+ """
276
+ SELECT sequence_end
277
+ FROM sequence_state
278
+ WHERE sequence_kind = ? AND venue = ? AND symbol = ?
279
+ AND continuity_is_null = ? AND continuity_id = ?
280
+ """,
281
+ (kind, key[0], key[1], continuity_is_null, continuity_id),
282
+ ).fetchone()
283
+ return int(result[0]) if result is not None else None
284
+
285
+ def set_sequence(
286
+ self,
287
+ kind: str,
288
+ key: tuple[str, str, str | None],
289
+ sequence_end: int,
290
+ ) -> None:
291
+ continuity_is_null, continuity_id = _continuity_key(key[2])
292
+ self._connection.execute(
293
+ """
294
+ INSERT INTO sequence_state (
295
+ sequence_kind, venue, symbol, continuity_is_null,
296
+ continuity_id, sequence_end
297
+ ) VALUES (?, ?, ?, ?, ?, ?)
298
+ ON CONFLICT (
299
+ sequence_kind, venue, symbol, continuity_is_null, continuity_id
300
+ ) DO UPDATE SET sequence_end = excluded.sequence_end
301
+ """,
302
+ (kind, key[0], key[1], continuity_is_null, continuity_id, sequence_end),
303
+ )
304
+
305
+ def first_trade_row_or_insert(
306
+ self, identity: tuple[str, str, int], row_index: int
307
+ ) -> int | None:
308
+ try:
309
+ self._connection.execute(
310
+ """
311
+ INSERT INTO trade_identity (venue, symbol, trade_id, first_row)
312
+ VALUES (?, ?, ?, ?)
313
+ """,
314
+ (*identity, row_index),
315
+ )
316
+ except sqlite3.IntegrityError:
317
+ result = self._connection.execute(
318
+ """
319
+ SELECT first_row FROM trade_identity
320
+ WHERE venue = ? AND symbol = ? AND trade_id = ?
321
+ """,
322
+ identity,
323
+ ).fetchone()
324
+ if result is None: # pragma: no cover - guarded by the primary key
325
+ raise RuntimeError("duplicate identity disappeared from quality state") from None
326
+ return int(result[0])
327
+ return None
328
+
329
+ def commit(self) -> None:
330
+ self._connection.commit()
331
+
332
+ def close(self) -> None:
333
+ self._connection.close()
334
+
335
+
336
+ class _ValidationState(Protocol):
337
+ def get_event(self, key: tuple[str, str, str | None]) -> tuple[int, int | None, int] | None: ...
338
+
339
+ def set_event(
340
+ self,
341
+ key: tuple[str, str, str | None],
342
+ value: tuple[int, int | None, int],
343
+ ) -> None: ...
344
+
345
+ def get_sequence(self, kind: str, key: tuple[str, str, str | None]) -> int | None: ...
346
+
347
+ def set_sequence(
348
+ self,
349
+ kind: str,
350
+ key: tuple[str, str, str | None],
351
+ sequence_end: int,
352
+ ) -> None: ...
353
+
354
+ def first_trade_row_or_insert(
355
+ self, identity: tuple[str, str, int], row_index: int
356
+ ) -> int | None: ...
357
+
358
+
359
+ class _MemoryState:
360
+ def __init__(self) -> None:
361
+ self._events: dict[tuple[str, str, str | None], tuple[int, int | None, int]] = {}
362
+ self._sequences: dict[tuple[str, str, str, str | None], int] = {}
363
+ self._trade_identities: dict[tuple[str, str, int], int] = {}
364
+
365
+ def get_event(self, key: tuple[str, str, str | None]) -> tuple[int, int | None, int] | None:
366
+ return self._events.get(key)
367
+
368
+ def set_event(
369
+ self,
370
+ key: tuple[str, str, str | None],
371
+ value: tuple[int, int | None, int],
372
+ ) -> None:
373
+ self._events[key] = value
374
+
375
+ def get_sequence(self, kind: str, key: tuple[str, str, str | None]) -> int | None:
376
+ return self._sequences.get((kind, *key))
377
+
378
+ def set_sequence(
379
+ self,
380
+ kind: str,
381
+ key: tuple[str, str, str | None],
382
+ sequence_end: int,
383
+ ) -> None:
384
+ self._sequences[(kind, *key)] = sequence_end
385
+
386
+ def first_trade_row_or_insert(
387
+ self, identity: tuple[str, str, int], row_index: int
388
+ ) -> int | None:
389
+ first_row = self._trade_identities.get(identity)
390
+ if first_row is None:
391
+ self._trade_identities[identity] = row_index
392
+ return first_row
393
+
394
+
395
+ def _finding(
396
+ findings: _FindingTarget,
397
+ *,
398
+ rule_id: str,
399
+ severity: Severity,
400
+ dataset: str,
401
+ row_index: int | None,
402
+ row: Mapping[str, Any] | None,
403
+ message: str,
404
+ details: Mapping[str, Any] | None = None,
405
+ ) -> None:
406
+ findings.append(
407
+ QualityFinding(
408
+ rule_id=rule_id,
409
+ severity=severity,
410
+ dataset=dataset,
411
+ row_index=row_index,
412
+ symbol=str(row["symbol"]) if row is not None and row.get("symbol") else None,
413
+ event_ts_ns=(
414
+ int(row["event_ts_ns"])
415
+ if row is not None and row.get("event_ts_ns") is not None
416
+ else None
417
+ ),
418
+ message=message,
419
+ details=details or {},
420
+ )
421
+ )
422
+
423
+
424
+ def _validate_event_clocks(
425
+ rows: list[dict[str, Any]],
426
+ *,
427
+ dataset: str,
428
+ findings: _FindingTarget,
429
+ max_silence_ns: int,
430
+ row_offset: int = 0,
431
+ state: _ValidationState | None = None,
432
+ ) -> None:
433
+ validation_state = state if state is not None else _MemoryState()
434
+ for local_index, row in enumerate(rows):
435
+ index = row_offset + local_index
436
+ event_ts = int(row["event_ts_ns"])
437
+ available_ts = int(row["available_ts_ns"])
438
+ received = row.get("received_ts_ns")
439
+ received_ts = int(received) if received is not None else None
440
+ if available_ts < event_ts:
441
+ _finding(
442
+ findings,
443
+ rule_id="temporal.available_before_event",
444
+ severity="ERROR",
445
+ dataset=dataset,
446
+ row_index=index,
447
+ row=row,
448
+ message="observation is marked available before its exchange event time",
449
+ details={"event_ts_ns": event_ts, "available_ts_ns": available_ts},
450
+ )
451
+ if received_ts is not None and available_ts < received_ts:
452
+ _finding(
453
+ findings,
454
+ rule_id="temporal.available_before_receipt",
455
+ severity="ERROR",
456
+ dataset=dataset,
457
+ row_index=index,
458
+ row=row,
459
+ message="live observation is marked available before local receipt",
460
+ details={"received_ts_ns": received_ts, "available_ts_ns": available_ts},
461
+ )
462
+
463
+ key = (str(row["venue"]), str(row["symbol"]), row.get("continuity_id"))
464
+ prior = validation_state.get_event(key)
465
+ if prior is not None:
466
+ previous_event, previous_received, previous_index = prior
467
+ if event_ts < previous_event:
468
+ _finding(
469
+ findings,
470
+ rule_id="temporal.out_of_order_event_time",
471
+ severity="WARNING",
472
+ dataset=dataset,
473
+ row_index=index,
474
+ row=row,
475
+ message="exchange timestamps reversed in source/capture order",
476
+ details={
477
+ "previous_row": previous_index,
478
+ "previous_event_ts_ns": previous_event,
479
+ },
480
+ )
481
+ if event_ts - previous_event > max_silence_ns:
482
+ _finding(
483
+ findings,
484
+ rule_id="temporal.long_silence",
485
+ severity="WARNING",
486
+ dataset=dataset,
487
+ row_index=index,
488
+ row=row,
489
+ message="time between events exceeded configured silence threshold",
490
+ details={"silence_ns": event_ts - previous_event},
491
+ )
492
+ if (
493
+ received_ts is not None
494
+ and previous_received is not None
495
+ and received_ts < previous_received
496
+ ):
497
+ _finding(
498
+ findings,
499
+ rule_id="temporal.receive_clock_reversal",
500
+ severity="WARNING",
501
+ dataset=dataset,
502
+ row_index=index,
503
+ row=row,
504
+ message="wall-clock receipt timestamp moved backwards",
505
+ details={
506
+ "previous_row": previous_index,
507
+ "previous_received_ts_ns": previous_received,
508
+ },
509
+ )
510
+ validation_state.set_event(key, (event_ts, received_ts, index))
511
+
512
+
513
+ def _validate_trades(
514
+ rows: list[dict[str, Any]],
515
+ dataset: str,
516
+ findings: _FindingTarget,
517
+ *,
518
+ row_offset: int = 0,
519
+ state: _ValidationState | None = None,
520
+ ) -> None:
521
+ validation_state = state if state is not None else _MemoryState()
522
+ for local_index, row in enumerate(rows):
523
+ index = row_offset + local_index
524
+ identity = (str(row["venue"]), str(row["symbol"]), int(row["trade_id"]))
525
+ first_row = validation_state.first_trade_row_or_insert(identity, index)
526
+ if first_row is not None:
527
+ _finding(
528
+ findings,
529
+ rule_id="trade.duplicate",
530
+ severity="ERROR",
531
+ dataset=dataset,
532
+ row_index=index,
533
+ row=row,
534
+ message="duplicate trade identity was preserved",
535
+ details={"first_row": first_row, "trade_id": identity[2]},
536
+ )
537
+ if int(row["price_ticks"]) <= 0 or float(row["price"]) <= 0.0:
538
+ _finding(
539
+ findings,
540
+ rule_id="trade.nonpositive_price",
541
+ severity="ERROR",
542
+ dataset=dataset,
543
+ row_index=index,
544
+ row=row,
545
+ message="trade price is zero or negative",
546
+ )
547
+ if int(row["quantity_lots"]) <= 0 or float(row["quantity"]) <= 0.0:
548
+ _finding(
549
+ findings,
550
+ rule_id="trade.nonpositive_quantity",
551
+ severity="ERROR",
552
+ dataset=dataset,
553
+ row_index=index,
554
+ row=row,
555
+ message="trade quantity is zero or negative",
556
+ )
557
+ expected_price = int(row["price_ticks"]) * float(row["tick_size"])
558
+ expected_quantity = int(row["quantity_lots"]) * float(row["lot_size"])
559
+ if abs(expected_price - float(row["price"])) > max(1e-12, abs(expected_price) * 1e-12):
560
+ _finding(
561
+ findings,
562
+ rule_id="trade.price_scale_mismatch",
563
+ severity="ERROR",
564
+ dataset=dataset,
565
+ row_index=index,
566
+ row=row,
567
+ message="floating price does not match exact ticks and tick size",
568
+ )
569
+ if abs(expected_quantity - float(row["quantity"])) > max(
570
+ 1e-12, abs(expected_quantity) * 1e-12
571
+ ):
572
+ _finding(
573
+ findings,
574
+ rule_id="trade.quantity_scale_mismatch",
575
+ severity="ERROR",
576
+ dataset=dataset,
577
+ row_index=index,
578
+ row=row,
579
+ message="floating quantity does not match exact lots and lot size",
580
+ )
581
+ if row["aggressor_side"] not in {"buy", "sell"}:
582
+ _finding(
583
+ findings,
584
+ rule_id="trade.invalid_aggressor_side",
585
+ severity="ERROR",
586
+ dataset=dataset,
587
+ row_index=index,
588
+ row=row,
589
+ message="aggressor side is outside the normalized enum",
590
+ )
591
+
592
+
593
+ def _validate_book_sequences(
594
+ rows: list[dict[str, Any]],
595
+ dataset: str,
596
+ findings: _FindingTarget,
597
+ *,
598
+ row_offset: int = 0,
599
+ state: _ValidationState | None = None,
600
+ ) -> None:
601
+ validation_state = state if state is not None else _MemoryState()
602
+ for local_index, row in enumerate(rows):
603
+ index = row_offset + local_index
604
+ start = int(row["sequence_start"])
605
+ end = int(row["sequence_end"])
606
+ if end < start:
607
+ _finding(
608
+ findings,
609
+ rule_id="sequence.invalid_range",
610
+ severity="ERROR",
611
+ dataset=dataset,
612
+ row_index=index,
613
+ row=row,
614
+ message="sequence range ends before it starts",
615
+ )
616
+ continue
617
+ key = (str(row["venue"]), str(row["symbol"]), row.get("continuity_id"))
618
+ prior = validation_state.get_sequence("book_observations", key)
619
+ if prior is not None:
620
+ expected = prior + 1
621
+ if start > expected:
622
+ _finding(
623
+ findings,
624
+ rule_id="sequence.missing_range",
625
+ severity="ERROR",
626
+ dataset=dataset,
627
+ row_index=index,
628
+ row=row,
629
+ message="book sequence has a forward gap",
630
+ details={
631
+ "expected_sequence": expected,
632
+ "observed_start": start,
633
+ "missing_start": expected,
634
+ "missing_end": start - 1,
635
+ },
636
+ )
637
+ elif end <= prior:
638
+ _finding(
639
+ findings,
640
+ rule_id="sequence.stale_or_duplicate",
641
+ severity="WARNING",
642
+ dataset=dataset,
643
+ row_index=index,
644
+ row=row,
645
+ message="sequence event is fully stale or duplicated",
646
+ details={"previous_end": prior},
647
+ )
648
+ validation_state.set_sequence(
649
+ "book_observations",
650
+ key,
651
+ max(prior if prior is not None else end, end),
652
+ )
653
+
654
+
655
+ def _validate_books(
656
+ rows: list[dict[str, Any]],
657
+ dataset: str,
658
+ findings: _FindingTarget,
659
+ max_spread_bps: float,
660
+ *,
661
+ row_offset: int = 0,
662
+ state: _ValidationState | None = None,
663
+ ) -> None:
664
+ _validate_book_sequences(
665
+ rows,
666
+ dataset,
667
+ findings,
668
+ row_offset=row_offset,
669
+ state=state,
670
+ )
671
+ for local_index, row in enumerate(rows):
672
+ index = row_offset + local_index
673
+ bid = float(row["best_bid"])
674
+ ask = float(row["best_ask"])
675
+ bid_quantity = float(row["bid_quantity"])
676
+ ask_quantity = float(row["ask_quantity"])
677
+ mid = float(row["mid_price"])
678
+ tick_size = float(row["tick_size"])
679
+ lot_size = float(row["lot_size"])
680
+ expected_bid = int(row["best_bid_ticks"]) * tick_size
681
+ expected_ask = int(row["best_ask_ticks"]) * tick_size
682
+ expected_bid_quantity = int(row["bid_quantity_lots"]) * lot_size
683
+ expected_ask_quantity = int(row["ask_quantity_lots"]) * lot_size
684
+ if abs(expected_bid - bid) > max(1e-12, abs(expected_bid) * 1e-12) or abs(
685
+ expected_ask - ask
686
+ ) > max(1e-12, abs(expected_ask) * 1e-12):
687
+ _finding(
688
+ findings,
689
+ rule_id="book.price_scale_mismatch",
690
+ severity="ERROR",
691
+ dataset=dataset,
692
+ row_index=index,
693
+ row=row,
694
+ message="floating best prices do not match exact ticks and tick size",
695
+ )
696
+ if abs(expected_bid_quantity - bid_quantity) > max(
697
+ 1e-12, abs(expected_bid_quantity) * 1e-12
698
+ ) or abs(expected_ask_quantity - ask_quantity) > max(
699
+ 1e-12, abs(expected_ask_quantity) * 1e-12
700
+ ):
701
+ _finding(
702
+ findings,
703
+ rule_id="book.quantity_scale_mismatch",
704
+ severity="ERROR",
705
+ dataset=dataset,
706
+ row_index=index,
707
+ row=row,
708
+ message="floating best quantities do not match exact lots and lot size",
709
+ )
710
+ if bid <= 0.0 or ask <= 0.0:
711
+ _finding(
712
+ findings,
713
+ rule_id="book.nonpositive_price",
714
+ severity="ERROR",
715
+ dataset=dataset,
716
+ row_index=index,
717
+ row=row,
718
+ message="best price is zero or negative",
719
+ )
720
+ if bid_quantity <= 0.0 or ask_quantity <= 0.0:
721
+ _finding(
722
+ findings,
723
+ rule_id="book.nonpositive_quantity",
724
+ severity="ERROR",
725
+ dataset=dataset,
726
+ row_index=index,
727
+ row=row,
728
+ message="best-level quantity is zero or negative",
729
+ )
730
+ if bid >= ask:
731
+ _finding(
732
+ findings,
733
+ rule_id="book.crossed_or_locked",
734
+ severity="ERROR",
735
+ dataset=dataset,
736
+ row_index=index,
737
+ row=row,
738
+ message="best bid is greater than or equal to best ask",
739
+ details={"best_bid": bid, "best_ask": ask},
740
+ )
741
+ if mid > 0.0:
742
+ relative_spread_bps = (ask - bid) / mid * 10_000.0
743
+ if relative_spread_bps > max_spread_bps:
744
+ _finding(
745
+ findings,
746
+ rule_id="book.abnormal_spread",
747
+ severity="WARNING",
748
+ dataset=dataset,
749
+ row_index=index,
750
+ row=row,
751
+ message="relative spread exceeded configured threshold",
752
+ details={
753
+ "spread_bps": relative_spread_bps,
754
+ "threshold_bps": max_spread_bps,
755
+ },
756
+ )
757
+ microprice = float(row["microprice"])
758
+ if not bid <= microprice <= ask:
759
+ _finding(
760
+ findings,
761
+ rule_id="book.microprice_outside_quotes",
762
+ severity="ERROR",
763
+ dataset=dataset,
764
+ row_index=index,
765
+ row=row,
766
+ message="microprice is outside the contemporaneous quotes",
767
+ )
768
+ for side in ("bid", "ask"):
769
+ depth_1 = float(row[f"depth_{side}_1"])
770
+ depth_5 = float(row[f"depth_{side}_5"])
771
+ depth_10 = float(row[f"depth_{side}_10"])
772
+ if not 0.0 < depth_1 <= depth_5 <= depth_10:
773
+ _finding(
774
+ findings,
775
+ rule_id="book.nonmonotone_depth",
776
+ severity="ERROR",
777
+ dataset=dataset,
778
+ row_index=index,
779
+ row=row,
780
+ message=f"cumulative {side} depth is not positive and monotone",
781
+ )
782
+ if not bool(row["is_valid"]):
783
+ _finding(
784
+ findings,
785
+ rule_id="book.invalid_state",
786
+ severity="ERROR",
787
+ dataset=dataset,
788
+ row_index=index,
789
+ row=row,
790
+ message="reconstructor marked this state invalid",
791
+ )
792
+
793
+
794
+ def _validate_depth_deltas(
795
+ rows: list[dict[str, Any]],
796
+ dataset: str,
797
+ findings: _FindingTarget,
798
+ *,
799
+ row_offset: int = 0,
800
+ state: _ValidationState | None = None,
801
+ ) -> None:
802
+ validation_state = state if state is not None else _MemoryState()
803
+ for local_index, row in enumerate(rows):
804
+ index = row_offset + local_index
805
+ start = int(row["first_update_id"])
806
+ end = int(row["last_update_id"])
807
+ if end < start:
808
+ _finding(
809
+ findings,
810
+ rule_id="sequence.invalid_range",
811
+ severity="ERROR",
812
+ dataset=dataset,
813
+ row_index=index,
814
+ row=row,
815
+ message="delta sequence range ends before it starts",
816
+ )
817
+ else:
818
+ key = (str(row["venue"]), str(row["symbol"]), row.get("continuity_id"))
819
+ prior = validation_state.get_sequence("depth_deltas", key)
820
+ if prior is not None:
821
+ expected = prior + 1
822
+ previous_hint = row.get("previous_update_id")
823
+ if previous_hint is not None and int(previous_hint) != prior:
824
+ _finding(
825
+ findings,
826
+ rule_id="sequence.previous_id_mismatch",
827
+ severity="ERROR",
828
+ dataset=dataset,
829
+ row_index=index,
830
+ row=row,
831
+ message="delta previous-update hint does not match the prior event",
832
+ details={"expected_previous": prior, "observed_previous": previous_hint},
833
+ )
834
+ if start > expected:
835
+ _finding(
836
+ findings,
837
+ rule_id="sequence.missing_range",
838
+ severity="ERROR",
839
+ dataset=dataset,
840
+ row_index=index,
841
+ row=row,
842
+ message="depth delta sequence has a forward gap",
843
+ details={
844
+ "expected_sequence": expected,
845
+ "observed_start": start,
846
+ "missing_start": expected,
847
+ "missing_end": start - 1,
848
+ },
849
+ )
850
+ elif end <= prior:
851
+ _finding(
852
+ findings,
853
+ rule_id="sequence.stale_or_duplicate",
854
+ severity="WARNING",
855
+ dataset=dataset,
856
+ row_index=index,
857
+ row=row,
858
+ message="depth delta is fully stale or duplicated",
859
+ details={"previous_end": prior},
860
+ )
861
+ validation_state.set_sequence(
862
+ "depth_deltas",
863
+ key,
864
+ max(prior if prior is not None else end, end),
865
+ )
866
+ for side in ("bids", "asks"):
867
+ seen_prices: set[int] = set()
868
+ for level in row[side]:
869
+ price_ticks = int(level["price_ticks"])
870
+ quantity_lots = int(level["quantity_lots"])
871
+ if price_ticks <= 0:
872
+ _finding(
873
+ findings,
874
+ rule_id="depth.nonpositive_price",
875
+ severity="ERROR",
876
+ dataset=dataset,
877
+ row_index=index,
878
+ row=row,
879
+ message="depth change contains a zero or negative price",
880
+ )
881
+ # Zero is a documented delete instruction, not bad quantity.
882
+ if quantity_lots < 0:
883
+ _finding(
884
+ findings,
885
+ rule_id="depth.negative_quantity",
886
+ severity="ERROR",
887
+ dataset=dataset,
888
+ row_index=index,
889
+ row=row,
890
+ message="depth change contains a negative quantity",
891
+ )
892
+ if price_ticks in seen_prices:
893
+ _finding(
894
+ findings,
895
+ rule_id="depth.duplicate_price_in_event",
896
+ severity="WARNING",
897
+ dataset=dataset,
898
+ row_index=index,
899
+ row=row,
900
+ message="one delta updates the same side/price more than once",
901
+ details={"side": side, "price_ticks": price_ticks},
902
+ )
903
+ seen_prices.add(price_ticks)
904
+
905
+
906
+ class IncrementalQualityValidator:
907
+ """Validate normalized Arrow batches without retaining the row history.
908
+
909
+ Clock, sequence, and exact trade-identity state spill to a private temporary
910
+ SQLite database. ``findings`` in the final report is a bounded preview, while
911
+ total severity counts remain exact. Supplying ``findings_jsonl_path`` streams
912
+ every finding to JSONL in detection order.
913
+ """
914
+
915
+ def __init__(
916
+ self,
917
+ schema_name: str,
918
+ *,
919
+ max_spread_bps: float = 100.0,
920
+ max_silence_ns: int = 5_000_000_000,
921
+ max_findings: int | None = 1_000,
922
+ findings_jsonl_path: str | Path | None = None,
923
+ row_chunk_size: int = 16_384,
924
+ ) -> None:
925
+ get_schema(schema_name)
926
+ if row_chunk_size <= 0:
927
+ raise ValueError("row_chunk_size must be positive")
928
+ self.schema_name = schema_name
929
+ self.max_spread_bps = max_spread_bps
930
+ self.max_silence_ns = max_silence_ns
931
+ self.row_chunk_size = row_chunk_size
932
+ self._state = _SpillState()
933
+ try:
934
+ self._findings = _FindingAccumulator(
935
+ max_findings=max_findings,
936
+ findings_jsonl_path=findings_jsonl_path,
937
+ )
938
+ except BaseException:
939
+ self._state.close()
940
+ raise
941
+ self._rows_checked = 0
942
+ self._closed = False
943
+ self._report: ValidationReport | None = None
944
+
945
+ def __enter__(self) -> IncrementalQualityValidator:
946
+ return self
947
+
948
+ def __exit__(
949
+ self,
950
+ exc_type: type[BaseException] | None,
951
+ exc_value: BaseException | None,
952
+ traceback: object,
953
+ ) -> None:
954
+ self.close()
955
+
956
+ @property
957
+ def rows_checked(self) -> int:
958
+ return self._rows_checked
959
+
960
+ def _require_open(self) -> None:
961
+ if self._closed:
962
+ raise RuntimeError("incremental quality validator is already closed")
963
+
964
+ def _validate_rows(self, rows: list[dict[str, Any]]) -> None:
965
+ row_offset = self._rows_checked
966
+ if self.schema_name in {"trades", "book_observations", "depth_deltas"}:
967
+ _validate_event_clocks(
968
+ rows,
969
+ dataset=self.schema_name,
970
+ findings=self._findings,
971
+ max_silence_ns=self.max_silence_ns,
972
+ row_offset=row_offset,
973
+ state=self._state,
974
+ )
975
+ if self.schema_name == "trades":
976
+ _validate_trades(
977
+ rows,
978
+ self.schema_name,
979
+ self._findings,
980
+ row_offset=row_offset,
981
+ state=self._state,
982
+ )
983
+ elif self.schema_name == "book_observations":
984
+ _validate_books(
985
+ rows,
986
+ self.schema_name,
987
+ self._findings,
988
+ self.max_spread_bps,
989
+ row_offset=row_offset,
990
+ state=self._state,
991
+ )
992
+ elif self.schema_name == "depth_deltas":
993
+ _validate_depth_deltas(
994
+ rows,
995
+ self.schema_name,
996
+ self._findings,
997
+ row_offset=row_offset,
998
+ state=self._state,
999
+ )
1000
+ self._rows_checked += len(rows)
1001
+
1002
+ def update(self, batch: pa.Table | pa.RecordBatch) -> None:
1003
+ """Consume one table or record batch without changing its observations."""
1004
+ self._require_open()
1005
+ if not isinstance(batch, (pa.Table, pa.RecordBatch)):
1006
+ raise TypeError("batch must be a pyarrow Table or RecordBatch")
1007
+ if batch.num_rows == 0:
1008
+ ensure_schema(batch, self.schema_name)
1009
+ return
1010
+ for start in range(0, batch.num_rows, self.row_chunk_size):
1011
+ chunk = batch.slice(start, self.row_chunk_size)
1012
+ ensure_schema(chunk, self.schema_name)
1013
+ self._validate_rows(chunk.to_pylist())
1014
+ self._state.commit()
1015
+ self._findings.flush()
1016
+
1017
+ def finish(self) -> ValidationReport:
1018
+ """Close spill resources and return the exact-count validation report."""
1019
+ if self._report is not None:
1020
+ return self._report
1021
+ self._require_open()
1022
+ self._state.commit()
1023
+ self._findings.flush()
1024
+ self._findings.publish()
1025
+ self._state.close()
1026
+ self._closed = True
1027
+ jsonl_path = self._findings.path
1028
+ self._report = ValidationReport(
1029
+ dataset=self.schema_name,
1030
+ rows_checked=self._rows_checked,
1031
+ findings=self._findings.findings,
1032
+ total_errors=self._findings.error_count,
1033
+ total_warnings=self._findings.warning_count,
1034
+ findings_jsonl_path=str(jsonl_path.resolve()) if jsonl_path is not None else None,
1035
+ )
1036
+ return self._report
1037
+
1038
+ def close(self) -> None:
1039
+ """Release resources without fabricating a report for unfinished input."""
1040
+ if self._closed:
1041
+ return
1042
+ self._findings.close()
1043
+ self._state.close()
1044
+ self._closed = True
1045
+
1046
+
1047
+ def validate_batches(
1048
+ batches: Iterable[pa.Table | pa.RecordBatch],
1049
+ schema_name: str,
1050
+ *,
1051
+ max_spread_bps: float = 100.0,
1052
+ max_silence_ns: int = 5_000_000_000,
1053
+ max_findings: int | None = 1_000,
1054
+ findings_jsonl_path: str | Path | None = None,
1055
+ row_chunk_size: int = 16_384,
1056
+ ) -> ValidationReport:
1057
+ """Consume an iterable once and validate it with bounded retained state."""
1058
+ validator = IncrementalQualityValidator(
1059
+ schema_name,
1060
+ max_spread_bps=max_spread_bps,
1061
+ max_silence_ns=max_silence_ns,
1062
+ max_findings=max_findings,
1063
+ findings_jsonl_path=findings_jsonl_path,
1064
+ row_chunk_size=row_chunk_size,
1065
+ )
1066
+ try:
1067
+ for batch in batches:
1068
+ validator.update(batch)
1069
+ return validator.finish()
1070
+ except BaseException:
1071
+ validator.close()
1072
+ raise
1073
+
1074
+
1075
+ def validate_table(
1076
+ table: pa.Table,
1077
+ schema_name: str,
1078
+ *,
1079
+ max_spread_bps: float = 100.0,
1080
+ max_silence_ns: int = 5_000_000_000,
1081
+ ) -> ValidationReport:
1082
+ """Validate without sorting, de-duplicating, clipping, or changing rows."""
1083
+ ensure_schema(table, schema_name)
1084
+ rows = table.to_pylist()
1085
+ findings: list[QualityFinding] = []
1086
+ if schema_name in {"trades", "book_observations", "depth_deltas"}:
1087
+ _validate_event_clocks(
1088
+ rows,
1089
+ dataset=schema_name,
1090
+ findings=findings,
1091
+ max_silence_ns=max_silence_ns,
1092
+ )
1093
+ if schema_name == "trades":
1094
+ _validate_trades(rows, schema_name, findings)
1095
+ elif schema_name == "book_observations":
1096
+ _validate_books(rows, schema_name, findings, max_spread_bps)
1097
+ elif schema_name == "depth_deltas":
1098
+ _validate_depth_deltas(rows, schema_name, findings)
1099
+ return ValidationReport(
1100
+ dataset=schema_name,
1101
+ rows_checked=table.num_rows,
1102
+ findings=tuple(findings),
1103
+ )
Microstructure/src/microstructure/data/schemas.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned normalized Arrow schemas and their temporal contract.
2
+
3
+ All timestamps are signed UTC epoch nanoseconds. ``available_ts_ns`` is the
4
+ earliest time at which a row may enter a research information set. Archive
5
+ rows explicitly identify exchange event time as a proxy; live rows use local
6
+ receipt time. Prices and quantities retain exact integer tick/lot columns and
7
+ also expose documented floating convenience columns for research consumers.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterable, Mapping
13
+ from typing import Any
14
+
15
+ import pyarrow as pa # type: ignore[import-untyped]
16
+
17
+ SCHEMA_VERSION = "1.0.0"
18
+
19
+
20
+ class SchemaError(ValueError):
21
+ """Raised when a normalized table violates its declared schema."""
22
+
23
+
24
+ def _metadata(name: str) -> dict[bytes, bytes]:
25
+ return {
26
+ b"schema_name": name.encode(),
27
+ b"schema_version": SCHEMA_VERSION.encode(),
28
+ b"timestamp_unit": b"UTC epoch nanoseconds",
29
+ b"temporal_contract": (
30
+ b"available_ts_ns is the information-set clock; event_ts_ns alone is not receipt proof"
31
+ ),
32
+ b"numeric_contract": (
33
+ b"price_ticks and quantity_lots are exact; float columns are convenience units"
34
+ ),
35
+ }
36
+
37
+
38
+ _COMMON_EVENT_FIELDS = [
39
+ pa.field("schema_version", pa.string(), nullable=False),
40
+ pa.field("venue", pa.string(), nullable=False),
41
+ pa.field("symbol", pa.string(), nullable=False),
42
+ pa.field("event_ts_ns", pa.int64(), nullable=False),
43
+ pa.field("received_ts_ns", pa.int64()),
44
+ pa.field("available_ts_ns", pa.int64(), nullable=False),
45
+ pa.field("availability_basis", pa.string(), nullable=False),
46
+ pa.field("capture_seq", pa.int64()),
47
+ pa.field("continuity_id", pa.string()),
48
+ ]
49
+
50
+
51
+ TRADE_SCHEMA = pa.schema(
52
+ [
53
+ *_COMMON_EVENT_FIELDS,
54
+ pa.field("trade_id", pa.int64(), nullable=False),
55
+ pa.field("first_trade_id", pa.int64()),
56
+ pa.field("last_trade_id", pa.int64()),
57
+ pa.field("price_ticks", pa.int64(), nullable=False),
58
+ pa.field("quantity_lots", pa.int64(), nullable=False),
59
+ pa.field("tick_size", pa.float64(), nullable=False),
60
+ pa.field("lot_size", pa.float64(), nullable=False),
61
+ pa.field("price", pa.float64(), nullable=False),
62
+ pa.field("quantity", pa.float64(), nullable=False),
63
+ pa.field("quote_quantity", pa.float64(), nullable=False),
64
+ pa.field("aggressor_side", pa.string(), nullable=False),
65
+ pa.field("buyer_is_maker", pa.bool_(), nullable=False),
66
+ pa.field("source_artifact_id", pa.string(), nullable=False),
67
+ ],
68
+ metadata=_metadata("trades"),
69
+ )
70
+
71
+
72
+ BOOK_OBSERVATION_SCHEMA = pa.schema(
73
+ [
74
+ *_COMMON_EVENT_FIELDS,
75
+ pa.field("sequence_start", pa.int64(), nullable=False),
76
+ pa.field("sequence_end", pa.int64(), nullable=False),
77
+ pa.field("is_valid", pa.bool_(), nullable=False),
78
+ pa.field("best_bid_ticks", pa.int64(), nullable=False),
79
+ pa.field("best_ask_ticks", pa.int64(), nullable=False),
80
+ pa.field("bid_quantity_lots", pa.int64(), nullable=False),
81
+ pa.field("ask_quantity_lots", pa.int64(), nullable=False),
82
+ pa.field("tick_size", pa.float64(), nullable=False),
83
+ pa.field("lot_size", pa.float64(), nullable=False),
84
+ pa.field("best_bid", pa.float64(), nullable=False),
85
+ pa.field("best_ask", pa.float64(), nullable=False),
86
+ pa.field("bid_quantity", pa.float64(), nullable=False),
87
+ pa.field("ask_quantity", pa.float64(), nullable=False),
88
+ pa.field("spread", pa.float64(), nullable=False),
89
+ pa.field("mid_price", pa.float64(), nullable=False),
90
+ pa.field("microprice", pa.float64(), nullable=False),
91
+ pa.field("depth_bid_1", pa.float64(), nullable=False),
92
+ pa.field("depth_ask_1", pa.float64(), nullable=False),
93
+ pa.field("depth_bid_5", pa.float64(), nullable=False),
94
+ pa.field("depth_ask_5", pa.float64(), nullable=False),
95
+ pa.field("depth_bid_10", pa.float64(), nullable=False),
96
+ pa.field("depth_ask_10", pa.float64(), nullable=False),
97
+ pa.field("queue_imbalance_1", pa.float64(), nullable=False),
98
+ pa.field("queue_imbalance_5", pa.float64(), nullable=False),
99
+ pa.field("queue_imbalance_10", pa.float64(), nullable=False),
100
+ pa.field("source_artifact_id", pa.string(), nullable=False),
101
+ ],
102
+ metadata=_metadata("book_observations"),
103
+ )
104
+
105
+
106
+ LEVEL_TYPE = pa.struct(
107
+ [
108
+ pa.field("price_ticks", pa.int64(), nullable=False),
109
+ pa.field("quantity_lots", pa.int64(), nullable=False),
110
+ ]
111
+ )
112
+
113
+
114
+ DEPTH_DELTA_SCHEMA = pa.schema(
115
+ [
116
+ *_COMMON_EVENT_FIELDS,
117
+ pa.field("first_update_id", pa.int64(), nullable=False),
118
+ pa.field("last_update_id", pa.int64(), nullable=False),
119
+ pa.field("previous_update_id", pa.int64()),
120
+ pa.field("bids", pa.list_(LEVEL_TYPE), nullable=False),
121
+ pa.field("asks", pa.list_(LEVEL_TYPE), nullable=False),
122
+ pa.field("tick_size", pa.float64(), nullable=False),
123
+ pa.field("lot_size", pa.float64(), nullable=False),
124
+ pa.field("source_artifact_id", pa.string(), nullable=False),
125
+ ],
126
+ metadata=_metadata("depth_deltas"),
127
+ )
128
+
129
+
130
+ BOOK_SNAPSHOT_SCHEMA = pa.schema(
131
+ [
132
+ pa.field("schema_version", pa.string(), nullable=False),
133
+ pa.field("venue", pa.string(), nullable=False),
134
+ pa.field("symbol", pa.string(), nullable=False),
135
+ pa.field("snapshot_id", pa.string(), nullable=False),
136
+ pa.field("request_ts_ns", pa.int64(), nullable=False),
137
+ pa.field("received_ts_ns", pa.int64(), nullable=False),
138
+ pa.field("available_ts_ns", pa.int64(), nullable=False),
139
+ pa.field("continuity_id", pa.string(), nullable=False),
140
+ pa.field("last_update_id", pa.int64(), nullable=False),
141
+ pa.field("depth_limit", pa.int32(), nullable=False),
142
+ pa.field("bids", pa.list_(LEVEL_TYPE), nullable=False),
143
+ pa.field("asks", pa.list_(LEVEL_TYPE), nullable=False),
144
+ pa.field("tick_size", pa.float64(), nullable=False),
145
+ pa.field("lot_size", pa.float64(), nullable=False),
146
+ pa.field("source_artifact_id", pa.string(), nullable=False),
147
+ ],
148
+ metadata=_metadata("book_snapshots"),
149
+ )
150
+
151
+
152
+ SEQUENCE_GAP_SCHEMA = pa.schema(
153
+ [
154
+ pa.field("schema_version", pa.string(), nullable=False),
155
+ pa.field("venue", pa.string(), nullable=False),
156
+ pa.field("symbol", pa.string(), nullable=False),
157
+ pa.field("continuity_id", pa.string(), nullable=False),
158
+ pa.field("expected_sequence", pa.int64(), nullable=False),
159
+ pa.field("observed_sequence_start", pa.int64(), nullable=False),
160
+ pa.field("observed_sequence_end", pa.int64(), nullable=False),
161
+ pa.field("missing_start", pa.int64(), nullable=False),
162
+ pa.field("missing_end", pa.int64(), nullable=False),
163
+ pa.field("detected_ts_ns", pa.int64(), nullable=False),
164
+ pa.field("reason", pa.string(), nullable=False),
165
+ pa.field("source_artifact_id", pa.string(), nullable=False),
166
+ ],
167
+ metadata=_metadata("sequence_gaps"),
168
+ )
169
+
170
+
171
+ SCHEMAS: Mapping[str, pa.Schema] = {
172
+ "trades": TRADE_SCHEMA,
173
+ "book_observations": BOOK_OBSERVATION_SCHEMA,
174
+ "depth_deltas": DEPTH_DELTA_SCHEMA,
175
+ "book_snapshots": BOOK_SNAPSHOT_SCHEMA,
176
+ "sequence_gaps": SEQUENCE_GAP_SCHEMA,
177
+ }
178
+
179
+
180
+ def get_schema(name: str, version: str = SCHEMA_VERSION) -> pa.Schema:
181
+ """Return a schema by stable name and fail closed on unknown versions."""
182
+ if version != SCHEMA_VERSION:
183
+ raise SchemaError(f"unsupported schema version {version!r}; expected {SCHEMA_VERSION!r}")
184
+ try:
185
+ return SCHEMAS[name]
186
+ except KeyError as exc:
187
+ raise SchemaError(f"unknown normalized schema: {name!r}") from exc
188
+
189
+
190
+ def table_from_records(name: str, records: Iterable[Mapping[str, Any]]) -> pa.Table:
191
+ """Construct a table using the registry rather than inferred Arrow types."""
192
+ schema = get_schema(name)
193
+ try:
194
+ return pa.Table.from_pylist(list(records), schema=schema)
195
+ except (pa.ArrowException, TypeError, ValueError) as exc:
196
+ raise SchemaError(f"records do not conform to {name} {SCHEMA_VERSION}: {exc}") from exc
197
+
198
+
199
+ def ensure_schema(table: pa.Table | pa.RecordBatch, name: str) -> None:
200
+ """Require exact field order/types/nullability; metadata may be absent on batches."""
201
+ expected = get_schema(name)
202
+ actual = table.schema
203
+ if not actual.equals(expected, check_metadata=False):
204
+ raise SchemaError(f"schema mismatch for {name}: expected {expected}, got {actual}")
205
+ metadata = actual.metadata or {}
206
+ declared_name = metadata.get(b"schema_name")
207
+ declared_version = metadata.get(b"schema_version")
208
+ if declared_name is not None and declared_name != name.encode():
209
+ raise SchemaError(
210
+ f"schema metadata name mismatch: expected {name!r}, got {declared_name.decode()}"
211
+ )
212
+ if declared_version is not None and declared_version != SCHEMA_VERSION.encode():
213
+ raise SchemaError(
214
+ "schema metadata version mismatch: "
215
+ f"expected {SCHEMA_VERSION!r}, got {declared_version.decode()}"
216
+ )
217
+ version_column = table.column(actual.get_field_index("schema_version"))
218
+ observed_versions = set(version_column.to_pylist())
219
+ if observed_versions.difference({SCHEMA_VERSION}):
220
+ raise SchemaError(
221
+ f"row schema_version mismatch: expected only {SCHEMA_VERSION!r}, "
222
+ f"got {sorted(observed_versions)!r}"
223
+ )
Microstructure/src/microstructure/data/storage.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streaming, content-addressed Parquet storage and immutable data manifests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import tempfile
10
+ from collections import defaultdict
11
+ from collections.abc import Iterable, Mapping, Sequence
12
+ from contextlib import nullcontext, suppress
13
+ from dataclasses import dataclass
14
+ from datetime import UTC, datetime
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import pyarrow as pa # type: ignore[import-untyped]
19
+ import pyarrow.compute as pc # type: ignore[import-untyped]
20
+ import pyarrow.parquet as pq # type: ignore[import-untyped]
21
+
22
+ from microstructure.data.evidence_budget import RetainedEvidenceBudget
23
+ from microstructure.data.schemas import SCHEMA_VERSION, ensure_schema, get_schema
24
+ from microstructure.provenance import read_json, sha256_file, utc_now_iso, write_json
25
+
26
+ MANIFEST_VERSION = "1.0.0"
27
+ _SAFE_COMPONENT = re.compile(r"^[A-Za-z0-9_.-]+$")
28
+ _NS_PER_SECOND = 1_000_000_000
29
+
30
+
31
+ class StorageError(RuntimeError):
32
+ """Raised for an unsafe path or inconsistent immutable artifact."""
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class PartitionArtifact:
37
+ dataset: str
38
+ venue: str
39
+ symbol: str
40
+ partition_date: str
41
+ rows: int
42
+ write_ordinal: int
43
+ observed_start_ns: int
44
+ observed_end_inclusive_ns: int
45
+ data_path: Path
46
+ manifest_path: Path
47
+ data_sha256: str
48
+ manifest_sha256: str
49
+
50
+
51
+ @dataclass(frozen=True, slots=True)
52
+ class DatasetWriteResult:
53
+ dataset: str
54
+ schema_version: str
55
+ rows: int
56
+ artifacts: tuple[PartitionArtifact, ...]
57
+ manifest_path: Path
58
+ manifest_sha256: str
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class CaptureDatasetWriteResult:
63
+ """Constant-descriptor result for one bounded-memory live capture."""
64
+
65
+ dataset: str
66
+ schema_version: str
67
+ rows: int
68
+ data_path: Path | None
69
+ data_sha256: str | None
70
+ manifest_path: Path
71
+ manifest_sha256: str
72
+
73
+
74
+ def _safe(value: str, label: str) -> str:
75
+ if not value or _SAFE_COMPONENT.fullmatch(value) is None:
76
+ raise StorageError(f"unsafe {label} path component: {value!r}")
77
+ return value
78
+
79
+
80
+ def _stable_sha(payload: Mapping[str, Any]) -> str:
81
+ encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False)
82
+ return hashlib.sha256(encoded.encode()).hexdigest()
83
+
84
+
85
+ def _partition_date(timestamp_ns: int) -> str:
86
+ seconds = timestamp_ns // _NS_PER_SECOND
87
+ return datetime.fromtimestamp(seconds, tz=UTC).date().isoformat()
88
+
89
+
90
+ def _immutable_json(
91
+ directory: Path,
92
+ stem: str,
93
+ payload: Mapping[str, Any],
94
+ *,
95
+ retained_evidence_budget: RetainedEvidenceBudget | None = None,
96
+ ) -> tuple[Path, str]:
97
+ identity = _stable_sha(payload)
98
+ destination = directory / f"{stem}-{identity[:20]}.json"
99
+ if retained_evidence_budget is not None:
100
+ retained_evidence_budget.assert_contains(destination)
101
+ transaction = (
102
+ retained_evidence_budget.write_transaction()
103
+ if retained_evidence_budget is not None
104
+ else nullcontext()
105
+ )
106
+ with transaction:
107
+ if destination.exists():
108
+ existing = read_json(destination)
109
+ if existing != dict(payload):
110
+ raise StorageError(f"immutable manifest collision at {destination}")
111
+ else:
112
+ encoded = (
113
+ json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + "\n"
114
+ ).encode()
115
+ reservation = (
116
+ retained_evidence_budget.reserve(
117
+ len(encoded),
118
+ label=f"raw source manifest {destination.name}",
119
+ )
120
+ if retained_evidence_budget is not None
121
+ else None
122
+ )
123
+ try:
124
+ write_json(destination, payload)
125
+ if destination.stat().st_size != len(encoded):
126
+ raise StorageError(
127
+ f"source manifest byte count changed while writing {destination}"
128
+ )
129
+ if reservation is not None:
130
+ reservation.commit()
131
+ except BaseException:
132
+ destination.unlink(missing_ok=True)
133
+ if reservation is not None and reservation.active:
134
+ reservation.release()
135
+ raise
136
+ return destination, sha256_file(destination)
137
+
138
+
139
+ def write_source_manifest(
140
+ raw_path: str | Path,
141
+ *,
142
+ source: str,
143
+ source_uri: str,
144
+ downloaded_at_utc: str,
145
+ requested_start_ns: int | None,
146
+ requested_end_ns: int | None,
147
+ upstream_checksum_sha256: str | None = None,
148
+ response_headers: Mapping[str, str] | None = None,
149
+ retained_evidence_budget: RetainedEvidenceBudget | None = None,
150
+ ) -> tuple[Path, str]:
151
+ """Write an immutable sidecar for an untouched raw response or archive."""
152
+ path = Path(raw_path)
153
+ if not path.is_file():
154
+ raise StorageError(f"raw artifact does not exist: {path}")
155
+ checksum = sha256_file(path)
156
+ payload: dict[str, Any] = {
157
+ "manifest_version": MANIFEST_VERSION,
158
+ "artifact_kind": "raw_source",
159
+ "source": source,
160
+ "source_uri": source_uri,
161
+ "downloaded_at_utc": downloaded_at_utc,
162
+ "requested_range_ns": {"start": requested_start_ns, "end_exclusive": requested_end_ns},
163
+ "checksum": {"algorithm": "sha256", "value": checksum},
164
+ "upstream_checksum_sha256": upstream_checksum_sha256,
165
+ "bytes": path.stat().st_size,
166
+ "path": path.name,
167
+ "response_headers": dict(sorted((response_headers or {}).items())),
168
+ }
169
+ manifest_path, manifest_sha = _immutable_json(
170
+ path.parent,
171
+ f"{path.name}.manifest",
172
+ payload,
173
+ retained_evidence_budget=retained_evidence_budget,
174
+ )
175
+ return manifest_path, manifest_sha
176
+
177
+
178
+ def _write_parquet_part(
179
+ *,
180
+ table: pa.Table,
181
+ root: Path,
182
+ dataset: str,
183
+ schema_name: str,
184
+ venue: str,
185
+ symbol: str,
186
+ date: str,
187
+ source: str,
188
+ source_uri: str,
189
+ downloaded_at_utc: str,
190
+ source_checksum_sha256: str | None,
191
+ requested_start_ns: int | None,
192
+ requested_end_ns: int | None,
193
+ time_column: str,
194
+ compression: str,
195
+ write_ordinal: int,
196
+ ) -> PartitionArtifact:
197
+ partition = (
198
+ root
199
+ / _safe(dataset, "dataset")
200
+ / f"schema-{_safe(SCHEMA_VERSION, 'schema version')}"
201
+ / f"venue-{_safe(venue, 'venue')}"
202
+ / f"symbol-{_safe(symbol, 'symbol')}"
203
+ / f"date-{_safe(date, 'date')}"
204
+ )
205
+ partition.mkdir(parents=True, exist_ok=True)
206
+ handle, temporary_name = tempfile.mkstemp(dir=partition, prefix=".part-", suffix=".parquet.tmp")
207
+ os.close(handle)
208
+ temporary = Path(temporary_name)
209
+ try:
210
+ table = table.replace_schema_metadata(get_schema(schema_name).metadata)
211
+ pq.write_table(
212
+ table,
213
+ temporary,
214
+ compression=compression,
215
+ use_dictionary=True,
216
+ write_statistics=True,
217
+ )
218
+ checksum = sha256_file(temporary)
219
+ destination = partition / f"part-{checksum[:20]}.parquet"
220
+ if destination.exists():
221
+ if sha256_file(destination) != checksum:
222
+ raise StorageError(f"content-address collision at {destination}")
223
+ temporary.unlink()
224
+ else:
225
+ os.replace(temporary, destination)
226
+ except BaseException:
227
+ temporary.unlink(missing_ok=True)
228
+ raise
229
+
230
+ time_bounds = pc.min_max(table.column(time_column)).as_py()
231
+ if time_bounds is None or time_bounds["min"] is None or time_bounds["max"] is None:
232
+ raise StorageError("cannot manifest a Parquet part without a timestamp range")
233
+ manifest_payload: dict[str, Any] = {
234
+ "manifest_version": MANIFEST_VERSION,
235
+ "artifact_kind": "normalized_parquet",
236
+ "dataset": dataset,
237
+ "schema_name": schema_name,
238
+ "schema_version": SCHEMA_VERSION,
239
+ "venue": venue,
240
+ "symbol": symbol,
241
+ "partition_date": date,
242
+ "write_ordinal": write_ordinal,
243
+ "source": source,
244
+ "source_uri": source_uri,
245
+ "downloaded_at_utc": downloaded_at_utc,
246
+ "requested_range_ns": {"start": requested_start_ns, "end_exclusive": requested_end_ns},
247
+ "observed_range_ns": {
248
+ "start": int(time_bounds["min"]),
249
+ "end_inclusive": int(time_bounds["max"]),
250
+ },
251
+ "source_checksum_sha256": source_checksum_sha256,
252
+ "checksum": {"algorithm": "sha256", "value": checksum},
253
+ "rows": table.num_rows,
254
+ "bytes": destination.stat().st_size,
255
+ "path": str(destination.relative_to(root)),
256
+ "transformations": [
257
+ "normalized field names and types",
258
+ "UTC epoch-nanosecond timestamp conversion",
259
+ "exact integer tick/lot conversion where scale supplied",
260
+ ],
261
+ }
262
+ manifest_path, manifest_sha = _immutable_json(
263
+ partition, f"part-{checksum[:20]}.manifest", manifest_payload
264
+ )
265
+ return PartitionArtifact(
266
+ dataset=dataset,
267
+ venue=venue,
268
+ symbol=symbol,
269
+ partition_date=date,
270
+ rows=table.num_rows,
271
+ write_ordinal=write_ordinal,
272
+ observed_start_ns=int(time_bounds["min"]),
273
+ observed_end_inclusive_ns=int(time_bounds["max"]),
274
+ data_path=destination,
275
+ manifest_path=manifest_path,
276
+ data_sha256=checksum,
277
+ manifest_sha256=manifest_sha,
278
+ )
279
+
280
+
281
+ def _as_table(batch: pa.RecordBatch | pa.Table) -> pa.Table:
282
+ return batch if isinstance(batch, pa.Table) else pa.Table.from_batches([batch])
283
+
284
+
285
+ def write_partitioned_parquet(
286
+ batches: Iterable[pa.RecordBatch | pa.Table],
287
+ *,
288
+ root: str | Path,
289
+ dataset: str,
290
+ schema_name: str,
291
+ source: str,
292
+ source_uri: str = "synthetic://local",
293
+ downloaded_at_utc: str | None = None,
294
+ source_checksum_sha256: str | None = None,
295
+ requested_start_ns: int | None = None,
296
+ requested_end_ns: int | None = None,
297
+ time_column: str = "event_ts_ns",
298
+ max_rows_per_file: int = 250_000,
299
+ max_input_batch_rows: int = 250_000,
300
+ compression: str = "zstd",
301
+ ) -> DatasetWriteResult:
302
+ """Stream batches into immutable Parquet parts partitioned by venue/symbol/day.
303
+
304
+ Each input batch is split only within that bounded batch, so this function
305
+ never requires the complete data set in memory. Existing content-addressed
306
+ parts are reused rather than overwritten.
307
+ """
308
+ if max_rows_per_file < 1:
309
+ raise ValueError("max_rows_per_file must be positive")
310
+ if max_input_batch_rows < 1:
311
+ raise ValueError("max_input_batch_rows must be positive")
312
+ destination_root = Path(root)
313
+ destination_root.mkdir(parents=True, exist_ok=True)
314
+ download_time = downloaded_at_utc or utc_now_iso()
315
+ artifacts: list[PartitionArtifact] = []
316
+
317
+ for raw_batch in batches:
318
+ table = _as_table(raw_batch)
319
+ if table.num_rows > max_input_batch_rows:
320
+ raise StorageError(
321
+ f"input batch has {table.num_rows} rows, above the bounded-memory limit "
322
+ f"{max_input_batch_rows}"
323
+ )
324
+ ensure_schema(table, schema_name)
325
+ if time_column not in table.column_names:
326
+ raise StorageError(f"partition time column is missing: {time_column}")
327
+ groups: dict[tuple[str, str, str], list[int]] = defaultdict(list)
328
+ venues = table.column("venue").to_pylist()
329
+ symbols = table.column("symbol").to_pylist()
330
+ timestamps = table.column(time_column).to_pylist()
331
+ for row_index, (venue, symbol, timestamp_ns) in enumerate(
332
+ zip(venues, symbols, timestamps, strict=True)
333
+ ):
334
+ groups[(str(venue), str(symbol), _partition_date(int(timestamp_ns)))].append(row_index)
335
+
336
+ for (venue, symbol, date), indices in groups.items():
337
+ for offset in range(0, len(indices), max_rows_per_file):
338
+ selected = indices[offset : offset + max_rows_per_file]
339
+ part = table.take(pa.array(selected, type=pa.int64()))
340
+ artifacts.append(
341
+ _write_parquet_part(
342
+ table=part,
343
+ root=destination_root,
344
+ dataset=dataset,
345
+ schema_name=schema_name,
346
+ venue=venue,
347
+ symbol=symbol,
348
+ date=date,
349
+ source=source,
350
+ source_uri=source_uri,
351
+ downloaded_at_utc=download_time,
352
+ source_checksum_sha256=source_checksum_sha256,
353
+ requested_start_ns=requested_start_ns,
354
+ requested_end_ns=requested_end_ns,
355
+ time_column=time_column,
356
+ compression=compression,
357
+ write_ordinal=len(artifacts),
358
+ )
359
+ )
360
+
361
+ artifact_entries = [
362
+ {
363
+ "data_path": str(item.data_path.relative_to(destination_root)),
364
+ "manifest_path": str(item.manifest_path.relative_to(destination_root)),
365
+ "data_sha256": item.data_sha256,
366
+ "manifest_sha256": item.manifest_sha256,
367
+ "rows": item.rows,
368
+ "write_ordinal": item.write_ordinal,
369
+ "observed_range_ns": {
370
+ "start": item.observed_start_ns,
371
+ "end_inclusive": item.observed_end_inclusive_ns,
372
+ },
373
+ }
374
+ for item in artifacts
375
+ ]
376
+ stable_identity: dict[str, Any] = {
377
+ "manifest_version": MANIFEST_VERSION,
378
+ "dataset": dataset,
379
+ "schema_version": SCHEMA_VERSION,
380
+ "source": source,
381
+ "source_uri": source_uri,
382
+ "downloaded_at_utc": download_time,
383
+ "requested_range_ns": {"start": requested_start_ns, "end_exclusive": requested_end_ns},
384
+ "artifacts": artifact_entries,
385
+ "rows": sum(item.rows for item in artifacts),
386
+ }
387
+ manifest_directory = destination_root / "_manifests"
388
+ manifest_directory.mkdir(parents=True, exist_ok=True)
389
+ manifest_path, manifest_sha = _immutable_json(
390
+ manifest_directory, f"{_safe(dataset, 'dataset')}.manifest", stable_identity
391
+ )
392
+ return DatasetWriteResult(
393
+ dataset=dataset,
394
+ schema_version=SCHEMA_VERSION,
395
+ rows=sum(item.rows for item in artifacts),
396
+ artifacts=tuple(artifacts),
397
+ manifest_path=manifest_path,
398
+ manifest_sha256=manifest_sha,
399
+ )
400
+
401
+
402
+ def write_capture_parquet(
403
+ batches: Iterable[pa.RecordBatch | pa.Table],
404
+ *,
405
+ root: str | Path,
406
+ dataset: str,
407
+ schema_name: str,
408
+ venue: str,
409
+ symbol: str,
410
+ capture_id: str,
411
+ source: str,
412
+ source_uri: str,
413
+ downloaded_at_utc: str | None = None,
414
+ source_checksum_sha256: str | None = None,
415
+ requested_start_ns: int | None = None,
416
+ requested_end_ns: int | None = None,
417
+ time_column: str = "event_ts_ns",
418
+ max_input_batch_rows: int = 16_384,
419
+ compression: str = "zstd",
420
+ ) -> CaptureDatasetWriteResult:
421
+ """Write one live-capture Parquet artifact from a bounded batch iterator.
422
+
423
+ The Parquet writer emits one bounded row group per input batch and retains
424
+ exactly one output descriptor, independent of capture length. Live capture
425
+ data is partitioned by immutable ``capture_id`` rather than UTC day because
426
+ capture-order quality evidence must not be reordered to satisfy a partition.
427
+ """
428
+ if max_input_batch_rows < 1:
429
+ raise ValueError("max_input_batch_rows must be positive")
430
+ safe_dataset = _safe(dataset, "dataset")
431
+ safe_schema = _safe(SCHEMA_VERSION, "schema version")
432
+ safe_venue = _safe(venue, "venue")
433
+ safe_symbol = _safe(symbol, "symbol")
434
+ safe_capture_id = _safe(capture_id, "capture ID")
435
+ schema = get_schema(schema_name)
436
+ if time_column not in schema.names:
437
+ raise StorageError(f"partition time column is missing: {time_column}")
438
+
439
+ destination_root = Path(root)
440
+ partition = (
441
+ destination_root
442
+ / safe_dataset
443
+ / f"schema-{safe_schema}"
444
+ / f"venue-{safe_venue}"
445
+ / f"symbol-{safe_symbol}"
446
+ / f"capture-{safe_capture_id}"
447
+ )
448
+ partition.mkdir(parents=True, exist_ok=True)
449
+ descriptor, temporary_name = tempfile.mkstemp(
450
+ dir=partition,
451
+ prefix=".capture-",
452
+ suffix=".parquet.tmp",
453
+ )
454
+ os.close(descriptor)
455
+ temporary = Path(temporary_name)
456
+ writer: pq.ParquetWriter | None = None
457
+ rows = 0
458
+ observed_start_ns: int | None = None
459
+ observed_end_ns: int | None = None
460
+ destination: Path | None = None
461
+ checksum: str | None = None
462
+ try:
463
+ writer = pq.ParquetWriter(
464
+ temporary,
465
+ schema,
466
+ compression=compression,
467
+ use_dictionary=True,
468
+ write_statistics=True,
469
+ )
470
+ for raw_batch in batches:
471
+ table = _as_table(raw_batch)
472
+ if table.num_rows > max_input_batch_rows:
473
+ raise StorageError(
474
+ f"input batch has {table.num_rows} rows, above the bounded-memory "
475
+ f"limit {max_input_batch_rows}"
476
+ )
477
+ ensure_schema(table, schema_name)
478
+ if table.num_rows == 0:
479
+ continue
480
+ if set(table.column("venue").to_pylist()) != {venue}:
481
+ raise StorageError("live capture batch contains an unexpected venue")
482
+ if set(table.column("symbol").to_pylist()) != {symbol}:
483
+ raise StorageError("live capture batch contains an unexpected symbol")
484
+ bounds = pc.min_max(table.column(time_column)).as_py()
485
+ if bounds is None or bounds["min"] is None or bounds["max"] is None:
486
+ raise StorageError("cannot write a live capture batch without timestamps")
487
+ batch_start = int(bounds["min"])
488
+ batch_end = int(bounds["max"])
489
+ observed_start_ns = (
490
+ batch_start if observed_start_ns is None else min(observed_start_ns, batch_start)
491
+ )
492
+ observed_end_ns = (
493
+ batch_end if observed_end_ns is None else max(observed_end_ns, batch_end)
494
+ )
495
+ writer.write_table(table, row_group_size=max_input_batch_rows)
496
+ rows += table.num_rows
497
+ writer.close()
498
+ writer = None
499
+ if rows == 0:
500
+ temporary.unlink()
501
+ else:
502
+ with temporary.open("rb") as handle:
503
+ os.fsync(handle.fileno())
504
+ checksum = sha256_file(temporary)
505
+ destination = partition / f"capture-{checksum[:20]}.parquet"
506
+ if destination.exists():
507
+ if sha256_file(destination) != checksum:
508
+ raise StorageError(f"content-address collision at {destination}")
509
+ temporary.unlink()
510
+ else:
511
+ os.replace(temporary, destination)
512
+ except BaseException:
513
+ if writer is not None:
514
+ with suppress(BaseException):
515
+ writer.close()
516
+ temporary.unlink(missing_ok=True)
517
+ raise
518
+
519
+ download_time = downloaded_at_utc or utc_now_iso()
520
+ data_path = destination
521
+ data_sha256 = checksum
522
+ artifact_entry: dict[str, Any] | None = None
523
+ if data_path is not None and data_sha256 is not None:
524
+ artifact_payload: dict[str, Any] = {
525
+ "manifest_version": MANIFEST_VERSION,
526
+ "artifact_kind": "normalized_live_capture_parquet",
527
+ "dataset": dataset,
528
+ "schema_name": schema_name,
529
+ "schema_version": SCHEMA_VERSION,
530
+ "venue": venue,
531
+ "symbol": symbol,
532
+ "capture_id": capture_id,
533
+ "source": source,
534
+ "source_uri": source_uri,
535
+ "downloaded_at_utc": download_time,
536
+ "requested_range_ns": {
537
+ "start": requested_start_ns,
538
+ "end_exclusive": requested_end_ns,
539
+ },
540
+ "observed_range_ns": {
541
+ "start": observed_start_ns,
542
+ "end_inclusive": observed_end_ns,
543
+ },
544
+ "source_checksum_sha256": source_checksum_sha256,
545
+ "checksum": {"algorithm": "sha256", "value": data_sha256},
546
+ "rows": rows,
547
+ "bytes": data_path.stat().st_size,
548
+ "path": str(data_path.relative_to(destination_root)),
549
+ "transformations": [
550
+ "normalized field names and types",
551
+ "UTC epoch-nanosecond timestamp conversion",
552
+ "exact integer tick/lot conversion where scale supplied",
553
+ ],
554
+ }
555
+ artifact_manifest_path, artifact_manifest_sha = _immutable_json(
556
+ partition,
557
+ f"capture-{data_sha256[:20]}.manifest",
558
+ artifact_payload,
559
+ )
560
+ artifact_entry = {
561
+ "data_path": str(data_path.relative_to(destination_root)),
562
+ "manifest_path": str(artifact_manifest_path.relative_to(destination_root)),
563
+ "data_sha256": data_sha256,
564
+ "manifest_sha256": artifact_manifest_sha,
565
+ "rows": rows,
566
+ "write_ordinal": 0,
567
+ "observed_range_ns": artifact_payload["observed_range_ns"],
568
+ }
569
+
570
+ dataset_payload: dict[str, Any] = {
571
+ "manifest_version": MANIFEST_VERSION,
572
+ "dataset": dataset,
573
+ "schema_version": SCHEMA_VERSION,
574
+ "source": source,
575
+ "source_uri": source_uri,
576
+ "downloaded_at_utc": download_time,
577
+ "requested_range_ns": {
578
+ "start": requested_start_ns,
579
+ "end_exclusive": requested_end_ns,
580
+ },
581
+ "partitioning": {"kind": "capture_id", "value": capture_id},
582
+ "artifacts": [artifact_entry] if artifact_entry is not None else [],
583
+ "rows": rows,
584
+ }
585
+ manifest_directory = destination_root / "_manifests"
586
+ manifest_directory.mkdir(parents=True, exist_ok=True)
587
+ manifest_path, manifest_sha = _immutable_json(
588
+ manifest_directory,
589
+ f"{safe_dataset}.capture-{safe_capture_id}.manifest",
590
+ dataset_payload,
591
+ )
592
+ return CaptureDatasetWriteResult(
593
+ dataset=dataset,
594
+ schema_version=SCHEMA_VERSION,
595
+ rows=rows,
596
+ data_path=data_path,
597
+ data_sha256=data_sha256,
598
+ manifest_path=manifest_path,
599
+ manifest_sha256=manifest_sha,
600
+ )
601
+
602
+
603
+ def parquet_paths(result: DatasetWriteResult) -> Sequence[Path]:
604
+ """Return concrete parts in manifest order for Polars/DuckDB consumers."""
605
+ return tuple(item.data_path for item in result.artifacts)