dccd 3.6.2__tar.gz → 3.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. {dccd-3.6.2 → dccd-3.7.0}/CHANGELOG.md +54 -0
  2. {dccd-3.6.2 → dccd-3.7.0}/CLAUDE.md +25 -54
  3. {dccd-3.6.2 → dccd-3.7.0}/PKG-INFO +1 -1
  4. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/config.py +6 -4
  5. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/operations.py +134 -6
  6. {dccd-3.6.2 → dccd-3.7.0}/dccd/domain/capability.py +13 -0
  7. {dccd-3.6.2 → dccd-3.7.0}/dccd/domain/dataset.py +10 -2
  8. {dccd-3.6.2 → dccd-3.7.0}/dccd/domain/records.py +60 -1
  9. dccd-3.7.0/dccd/domain/symbol.py +101 -0
  10. {dccd-3.6.2 → dccd-3.7.0}/dccd/domain/timeutils.py +27 -0
  11. dccd-3.7.0/dccd/domain/types.py +36 -0
  12. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/api/app.py +12 -4
  13. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/data.html +18 -7
  14. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/historical.html +56 -20
  15. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/base.py +68 -1
  16. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/binance.py +223 -4
  17. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/bybit.py +145 -6
  18. {dccd-3.6.2 → dccd-3.7.0}/dccd/storage/parquet.py +53 -10
  19. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_api.py +72 -0
  20. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_application.py +348 -0
  21. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_domain.py +132 -1
  22. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_domain_extended.py +10 -0
  23. dccd-3.7.0/dccd/tests/v3/test_sources.py +1161 -0
  24. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_storage.py +160 -2
  25. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_transport.py +44 -0
  26. {dccd-3.6.2 → dccd-3.7.0}/dccd/transport/http.py +12 -4
  27. {dccd-3.6.2 → dccd-3.7.0}/dccd/transport/paginate.py +15 -11
  28. {dccd-3.6.2 → dccd-3.7.0}/dccd.egg-info/PKG-INFO +1 -1
  29. {dccd-3.6.2 → dccd-3.7.0}/pyproject.toml +1 -1
  30. dccd-3.6.2/dccd/domain/symbol.py +0 -63
  31. dccd-3.6.2/dccd/domain/types.py +0 -27
  32. dccd-3.6.2/dccd/tests/v3/test_sources.py +0 -479
  33. {dccd-3.6.2 → dccd-3.7.0}/CONTRIBUTING.md +0 -0
  34. {dccd-3.6.2 → dccd-3.7.0}/LICENSE.txt +0 -0
  35. {dccd-3.6.2 → dccd-3.7.0}/MANIFEST.in +0 -0
  36. {dccd-3.6.2 → dccd-3.7.0}/README.md +0 -0
  37. {dccd-3.6.2 → dccd-3.7.0}/dccd/__init__.py +0 -0
  38. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/__init__.py +0 -0
  39. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/events.py +0 -0
  40. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/jobs.py +0 -0
  41. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/monitor.py +0 -0
  42. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/registry.py +0 -0
  43. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/scheduler.py +0 -0
  44. {dccd-3.6.2 → dccd-3.7.0}/dccd/application/service_factory.py +0 -0
  45. {dccd-3.6.2 → dccd-3.7.0}/dccd/domain/__init__.py +0 -0
  46. {dccd-3.6.2 → dccd-3.7.0}/dccd/domain/errors.py +0 -0
  47. {dccd-3.6.2 → dccd-3.7.0}/dccd/domain/transforms.py +0 -0
  48. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/__init__.py +0 -0
  49. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/api/__init__.py +0 -0
  50. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/cli/__init__.py +0 -0
  51. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/cli/main.py +0 -0
  52. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/__init__.py +0 -0
  53. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/favicon.svg +0 -0
  54. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/fonts/martian-mono-600.woff2 +0 -0
  55. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/fonts/martian-mono-700.woff2 +0 -0
  56. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/fonts/spline-sans-400.woff2 +0 -0
  57. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/fonts/spline-sans-500.woff2 +0 -0
  58. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/fonts/spline-sans-600.woff2 +0 -0
  59. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/fonts/spline-sans-700.woff2 +0 -0
  60. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/static/logo.svg +0 -0
  61. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/base.html +0 -0
  62. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/config.html +0 -0
  63. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/dashboard.html +0 -0
  64. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/live.html +0 -0
  65. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/login.html +0 -0
  66. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/logs.html +0 -0
  67. {dccd-3.6.2 → dccd-3.7.0}/dccd/interfaces/ui/templates/storage.html +0 -0
  68. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/__init__.py +0 -0
  69. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/bitfinex.py +0 -0
  70. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/bitmex.py +0 -0
  71. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/coinbase.py +0 -0
  72. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/kraken.py +0 -0
  73. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/okx.py +0 -0
  74. {dccd-3.6.2 → dccd-3.7.0}/dccd/sources/registry.py +0 -0
  75. {dccd-3.6.2 → dccd-3.7.0}/dccd/storage/__init__.py +0 -0
  76. {dccd-3.6.2 → dccd-3.7.0}/dccd/storage/coverage_sqlite.py +0 -0
  77. {dccd-3.6.2 → dccd-3.7.0}/dccd/storage/purge.py +0 -0
  78. {dccd-3.6.2 → dccd-3.7.0}/dccd/storage/remote.py +0 -0
  79. {dccd-3.6.2 → dccd-3.7.0}/dccd/storage/runs_sqlite.py +0 -0
  80. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/__init__.py +0 -0
  81. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/__init__.py +0 -0
  82. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_adapter_parsing.py +0 -0
  83. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_backfill_lookback.py +0 -0
  84. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_cli.py +0 -0
  85. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_client.py +0 -0
  86. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_coverage.py +0 -0
  87. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_monitor_webhook.py +0 -0
  88. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_network.py +0 -0
  89. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_orderbook_throttle.py +0 -0
  90. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_purge.py +0 -0
  91. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_ratelimit.py +0 -0
  92. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_remote_sync.py +0 -0
  93. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_restart.py +0 -0
  94. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_restore.py +0 -0
  95. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_scheduler_hygiene.py +0 -0
  96. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_storage_extended.py +0 -0
  97. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_stream_end_state.py +0 -0
  98. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_stream_flush.py +0 -0
  99. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_stream_nocapability.py +0 -0
  100. {dccd-3.6.2 → dccd-3.7.0}/dccd/tests/v3/test_ws_subscription_honesty.py +0 -0
  101. {dccd-3.6.2 → dccd-3.7.0}/dccd/transport/__init__.py +0 -0
  102. {dccd-3.6.2 → dccd-3.7.0}/dccd/transport/ratelimit.py +0 -0
  103. {dccd-3.6.2 → dccd-3.7.0}/dccd/transport/ws.py +0 -0
  104. {dccd-3.6.2 → dccd-3.7.0}/dccd.egg-info/SOURCES.txt +0 -0
  105. {dccd-3.6.2 → dccd-3.7.0}/dccd.egg-info/dependency_links.txt +0 -0
  106. {dccd-3.6.2 → dccd-3.7.0}/dccd.egg-info/entry_points.txt +0 -0
  107. {dccd-3.6.2 → dccd-3.7.0}/dccd.egg-info/requires.txt +0 -0
  108. {dccd-3.6.2 → dccd-3.7.0}/dccd.egg-info/top_level.txt +0 -0
  109. {dccd-3.6.2 → dccd-3.7.0}/setup.cfg +0 -0
@@ -16,6 +16,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
16
16
 
17
17
  ### Removed
18
18
 
19
+ ## [3.7.0] - 2026-07-05
20
+
21
+ ### Added
22
+
23
+ - `Symbol.market` (`spot`/`perp`/`quarter`/`next_quarter`) with `:market` pair
24
+ syntax (`BTC/USDT:perp`), market-suffixed storage slugs (`BTC-USDT_PERP`), and
25
+ per-market capability declarations (`Capability.markets`, `recent_window_s`)
26
+ enforced by `backfill()` — the plumbing for the derivative-markets epic. (#183)
27
+ - Binance USDS-M continuous-contract klines: `BTC/USDT:perp` / `:quarter` /
28
+ `:next_quarter` OHLC backfills route to `fapi/v1/continuousKlines` (auto-rolled
29
+ quarterly series — the futures leg of the basis signal), reusing the OHLC
30
+ machinery and storage layout verbatim (`ohlc/BTC-USDT_QUARTER/…`). (#184)
31
+ - `DataType.FUNDING` — perp funding-rate history end to end: `FundingRate`
32
+ record, annual Parquet store (`funding/{pair}/YYYY.parquet`, dedup on `TS`),
33
+ `FundingHistory` cursor protocol, bounded 365-day default lookback, and
34
+ Binance USDS-M as first source (full history; verified 2019-09→today on real
35
+ data, values byte-identical to the exchange). (#185)
36
+ - Bybit perp funding-rate history (paired `startTime`/`endTime` params,
37
+ newest-first backward pagination; depth probed to contract launch 2020-03 →
38
+ `history="full"` declared honestly) — cross-exchange funding spread now
39
+ computable. (#187)
40
+ - `DataType.OPEN_INTEREST` — span-typed OI history end to end:
41
+ `OpenInterest` record, `open_interest/{pair}/{span}/YYYY.parquet` layout with
42
+ the same gap detection as OHLC, `OpenInterestHistory` cursor protocol,
43
+ span-required validation (config + API), and a `recent_window_s` clamp for
44
+ time-bound recent windows; Bybit first with full history to symbol launch
45
+ (verified: 39.5k hourly rows since 2022-01-01, 0 % gap). (#188)
46
+ - Binance USDS-M open-interest statistics — forward collector with the 30-day
47
+ window declared honestly (`history="recent"` + `recent_window_s` → clamp +
48
+ warn at exactly the boundary), handling two verified endpoint quirks: a hard
49
+ HTTP 400 below the 30-day floor (floored with a safety margin) and
50
+ `endTime`-anchored over-full windows that would otherwise silently drop all
51
+ but the newest 500 rows (per-request `endTime` bounding + window-left
52
+ continuation). (#190)
53
+ - Funding and open-interest surfaced in the web UI: Data + Historical tabs
54
+ (span/coverage columns for OI, `:perp` pair hints, OI span select), plus a
55
+ `how-to/derivatives` guide (funding, OI forward collection, quarterly klines
56
+ → basis recipe) and the per-exchange capability matrix updated. (#191)
57
+
58
+ ## [3.6.3] - 2026-06-20
59
+
60
+ ### Fixed
61
+
62
+ - `POST /login` no longer returns a 500 on a non-ASCII submitted token:
63
+ `secrets.compare_digest` raises `TypeError` on a `str` with non-ASCII
64
+ characters, so the handler now compares UTF-8 bytes — a junk token (scanners POST
65
+ arbitrary bytes) is rejected cleanly with the usual invalid-login response. (#174)
66
+ - `AsyncHTTPClient.__aexit__` now nulls the shared client reference **before**
67
+ awaiting `aclose()`, closing a reference-count race: `aclose()` yields, and a
68
+ concurrent `__aenter__` during that await previously reused the closing client,
69
+ so a scheduled backfill could fail with `Cannot send a request, as the client
70
+ has been closed` (observed ~1×/day across exchanges). The re-entrant user now
71
+ builds a fresh client instead. (#173)
72
+
19
73
  ## [3.6.2] - 2026-06-20
20
74
 
21
75
  ### Fixed
@@ -9,6 +9,23 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
9
9
  > [`doc/dev/README.md`](doc/dev/README.md) for a fuller picture than this file
10
10
  > gives. `CLAUDE.md` remains authoritative for commands and invariants.
11
11
 
12
+ ## Common conventions
13
+
14
+ Shared across my repos, mirrored from `~/.claude/CLAUDE.md` (the single source of
15
+ truth — if they ever disagree, the global file wins). Restated here so the repo
16
+ stays self-contained:
17
+
18
+ - **Git Flow** — `master` (tagged releases) ← `develop` (integration) ←
19
+ `feat|fix|chore|docs/<topic>`. **Never commit directly to `develop` or `master`**
20
+ — always a feature branch + PR into `develop`; `develop` → `master` only at release.
21
+ - **Conventional Commits** — `feat:` `fix:` `chore:` `docs:`. **Never add
22
+ `Co-Authored-By` trailers** (personal repo).
23
+ - **One PR = one concern**, small and disposable — a big plan ships as several small
24
+ atomic PRs, never one catch-all branch.
25
+ - **Model: `opus`, always** — interactive sessions and every spawned subagent; a plan
26
+ leaf's `complexity` is effort/ordering only and never downgrades the model.
27
+ - **Before every commit** — `pytest` and `ruff check dccd/` must pass.
28
+
12
29
  ## Commands
13
30
 
14
31
  ```bash
@@ -42,42 +59,7 @@ python doc/dev/ui_smoke.py http://127.0.0.1:8137
42
59
  > env ships Sphinx whose source uses 3.12 `type` statements, which made mypy
43
60
  > abort under 3.11. dccd supports 3.11–3.13, so 3.12 semantics are safe.
44
61
 
45
- ## Git Flow
46
-
47
- **Branch model:**
48
- ```
49
- master ← stable releases only (tagged vX.Y.Z)
50
- └── develop ← integration branch
51
- ├── feat/<topic> new feature or modernization axis
52
- ├── fix/<topic> bug fix
53
- ├── chore/<topic> tooling, CI, deps
54
- └── docs/<topic> documentation only
55
- ```
56
-
57
- **Rules — always follow these before committing or pushing:**
58
- 1. **Never commit directly to `master`.**
59
- 2. **Never commit directly to `develop`** — always use a feature branch + PR.
60
- 3. Branch off `develop`: `git checkout develop && git checkout -b feat/my-topic`
61
- 4. Open a PR into `develop` when done. `develop` → `master` only at release time.
62
-
63
- **Commit style (Conventional Commits):**
64
- ```
65
- feat: add Bybit futures OHLC capability
66
- fix: correct paginator window for Coinbase
67
- chore: upgrade httpx to 0.28
68
- docs: update README for v3 install
69
- ```
70
-
71
- Do not add `Co-Authored-By` trailers to commits — this is a personal repo.
72
-
73
- **Before every commit:** run `pytest`. It must pass.
74
-
75
- **One PR = one concern, small and disposable.** Even a large plan ships as
76
- *several* small atomic PRs — never one fourre-tout branch. A PR you couldn't throw
77
- away without losing unrelated good work is too big: split it. This is what makes
78
- `/abandon-task` (kill a bad PR, keep the lesson) viable.
79
-
80
- ### Dev loop & docs of record
62
+ ## Dev loop & docs of record
81
63
 
82
64
  The iterative loop is tooled by skills, with four tracked docs as the sources of
83
65
  truth:
@@ -107,17 +89,6 @@ checklist) → … per leaf … → last leaf removes the roadmap line → `/rel
107
89
  backward-compatible: a repo whose `.claude/workflow.json` has **no `plans_dir`**
108
90
  falls back to the older `/pick-task → plan mode → /finish-task` loop.
109
91
 
110
- **Model per task** (advisory — you set it via `/model`, a skill spawns a subagent
111
- with an explicit `model`, or a plan **leaf's `complexity` derives it**:
112
- `low→haiku`, `medium→sonnet`, `high→opus`; subagents otherwise *inherit* the
113
- parent):
114
-
115
- | Model | For |
116
- |-------|-----|
117
- | `opus` | judgement, design, decisions, planning, review |
118
- | `sonnet` | implementation — code, tests, docstrings |
119
- | `haiku` | mechanical fan-out (doc scans, checklists) — spawn it explicitly as a subagent |
120
-
121
92
  ## Architecture (v3 — hexagonal)
122
93
 
123
94
  ### Three usage modes
@@ -148,9 +119,9 @@ Pure, synchronous, no I/O. Never import from transport/sources/storage.
148
119
 
149
120
  | Module | Contents |
150
121
  |--------|----------|
151
- | `symbol.py` | `Symbol(base, quote)` — normalises XBT→BTC |
152
- | `types.py` | `DataType` enum: `ohlc`, `trades`, `orderbook` |
153
- | `records.py` | `OHLCBar`, `Trade`, `OrderBookSnapshot` (ns timestamps) |
122
+ | `symbol.py` | `Symbol(base, quote, market)` — normalises XBT→BTC; `market` = `spot`/`perp`/`quarter`/`next_quarter` (`BTC/USDT:perp` syntax, `_PERP` slugs on disk) |
123
+ | `types.py` | `DataType` enum: `ohlc`, `trades`, `orderbook`, `funding`, `open_interest` |
124
+ | `records.py` | `OHLCBar`, `Trade`, `OrderBookSnapshot`, `FundingRate`, `OpenInterest` (ns timestamps) |
154
125
  | `dataset.py` | `DatasetId`, `Provenance` |
155
126
  | `capability.py` | `Capability` — declared per adapter per (data_type × transport × mode) |
156
127
  | `timeutils.py` | Helpers: `s_to_ns`, `align_ns`, `span_label`, `binance_interval`, … |
@@ -190,10 +161,10 @@ Adapters declare their capabilities via `capabilities() -> list[Capability]`.
190
161
 
191
162
  | Exchange | Notes |
192
163
  |----------|-------|
193
- | `binance.py` | Full history OHLC+trades, depth 5000 |
164
+ | `binance.py` | Full history OHLC+trades, depth 5000; perp/quarterly continuous futures klines, funding (full), open interest (30-day window only) |
194
165
  | `coinbase.py` | 300 candles/req (Paginator handles automatically) |
195
166
  | `kraken.py` | OHLC: 720 recent only (`history="recent"`); trades: full via `since` cursor |
196
- | `bybit.py` | No spot trades history (capability not declared → `NoCapability` early) |
167
+ | `bybit.py` | No spot trades history (capability not declared → `NoCapability` early); funding + open interest full history (perp) |
197
168
  | `okx.py` | `history-candles` + `history-trades` for deep history |
198
169
  | `bitfinex.py` | Up to 10 000 items per request |
199
170
  | `bitmex.py` | Bucketed OHLC (1m/5m/1h/1d only), full trades |
@@ -230,8 +201,8 @@ Adapters declare their capabilities via `capabilities() -> list[Capability]`.
230
201
  - `api/app.py` — FastAPI `create_app()`, lifespan context manager, module-level Pydantic request models. Job CRUD lives here: `POST /api/jobs/{create,delete,update}` (body-based to allow `/`/`:` in ids), all routed through the async `_persist_and_refresh` helper (writes YAML, updates `app.state`, calls `scheduler.sync_streams` **and** `scheduler.sync_intervals` to reconcile recurring backfills live). `POST /api/jobs/update` edits `start` and/or the recurring `every` (schedule). `GET /api/jobs` exposes `start`/`every`/`trigger`/`snapshot_interval`/`depth` so the UI can render and preserve them. `POST /api/jobs/run` + `/api/jobs/run-all` trigger configured backfills on demand. SSE at `GET /api/events` uses `add_queue`/`remove_queue` for multi-consumer fan-out.
231
202
  - `cli/main.py` — Typer commands, all import from `service_factory`
232
203
  - `ui/` — Jinja2 templates + static files. Nav: `Dashboard` · `Data` flat, plus `Collect ▾` (Historical/Live) and `System ▾` (Logs/Config/Storage) dropdowns. Pages are **split by concern**:
233
- - **Data** (`data.html`, route `/data`; `/inventory` 307-redirects here) — read-only view of what's on disk: DataType tabs → per-exchange accordions with totals, freshness dot, OHLC gap %, on-disk size, file count. No action buttons.
234
- - **Historical** (`historical.html`) — backfill jobs (**OHLC + Trades only**; order books have no REST history): DataType tabs → exchange accordions → one row per dataset with editable `first_date` (defaults to the dataset's earliest stored bar), a **Schedule** select (Off/hourly/daily/custom → `every`; `manual` trigger when off), real coverage bar, inline Run/Delete. **Run all** (header) + per-exchange **Run all**. New jobs default to `manual`.
204
+ - **Data** (`data.html`, route `/data`; `/inventory` 307-redirects here) — read-only view of what's on disk: DataType tabs (incl. Funding + Open Interest) → per-exchange accordions with totals, freshness dot, OHLC/OI gap %, on-disk size, file count. No action buttons.
205
+ - **Historical** (`historical.html`) — backfill jobs (**OHLC, Trades, Funding + Open Interest**; order books have no REST history): DataType tabs → exchange accordions → one row per dataset with editable `first_date` (defaults to the dataset's earliest stored bar), a **Schedule** select (Off/hourly/daily/custom → `every`; `manual` trigger when off), real coverage bar, inline Run/Delete. Span column/select is gated by `hasSpan(dt)` (OHLC + open interest); funding has no span. Pair fields accept the `:perp` market suffix (placeholder hints it on the derivative tabs). **Run all** (header) + per-exchange **Run all**. New jobs default to `manual`.
235
206
  - **Live** (`live.html`) — stream jobs (**Trades + Order Book only**; OHLC is collected via the Historical schedule, not streamed): same tab/accordion shape, with a liveness indicator fed by `StreamSampleEvent` over SSE (numeric `value`/`bid`/`ask`, formatted client-side via `fmtNum`). Liveness is **seeded from the last on-disk point** (inventory `max_ts`) so a refresh shows freshness without waiting for a live sample. The dot's "fresh" window is span-aware (order-book `snapshot_interval` / short for trades); the freshness label is a relative "N ago" under 24h (`fmtFreshness`) and an absolute date beyond, or the last-run date-time when stopped. Cadence column + `snapshot_interval` field for order book. Inline Start/Stop/Delete.
236
207
  - Single top bar carries the brand (logo · `dccd` · version) left and the nav right. Dates render in `settings.timezone` (`local`/`UTC`/zoneinfo) via `DCCD_TZ` in `fmtNs`/`fmtDate`; relative ages are tz-independent.
237
208
  - `dashboard.html` (KPIs + Active now / Recent runs / Data), `logs.html` (recent runs first, live console secondary, human run labels), `config.html` (Settings incl. `timezone`/Alerts/Storage + Raw JSON — **no jobs form**; jobs are managed on Historical/Live), `storage.html` (sizes via `fmtBytes`; no migrate tool).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dccd
3
- Version: 3.6.2
3
+ Version: 3.7.0
4
4
  Summary: Download Crypto Currency Data — hexagonal architecture, async-first.
5
5
  Author-email: Arthur Bernard <arthur.bernard.92@gmail.com>
6
6
  License: MIT
@@ -119,7 +119,7 @@ class JobConfig(BaseModel):
119
119
 
120
120
  Validation enforces:
121
121
  - ``exchange`` must be a known exchange name.
122
- - ``data_type='ohlc'`` requires ``span`` to be set.
122
+ - ``data_type='ohlc'`` or ``'open_interest'`` requires ``span`` to be set.
123
123
  - ``pairs`` must be non-empty and use ``BASE/QUOTE`` format.
124
124
  """
125
125
 
@@ -157,9 +157,11 @@ class JobConfig(BaseModel):
157
157
  return v
158
158
 
159
159
  @model_validator(mode="after")
160
- def _validate_span_for_ohlc(self) -> "JobConfig":
161
- if self.data_type == "ohlc" and self.span is None:
162
- raise ValueError("'span' is required when data_type='ohlc'")
160
+ def _validate_span_required(self) -> "JobConfig":
161
+ if self.data_type in ("ohlc", "open_interest") and self.span is None:
162
+ raise ValueError(
163
+ "'span' is required when data_type='ohlc' or 'open_interest'"
164
+ )
163
165
  return self
164
166
 
165
167
  def to_job_specs(self) -> list[JobSpec]:
@@ -22,10 +22,16 @@ from dccd.application.events import RunEvents
22
22
  from dccd.application.jobs import JobSpec, JobTarget
23
23
  from dccd.domain.dataset import DatasetId, Provenance
24
24
  from dccd.domain.errors import NoCapability
25
- from dccd.domain.records import OHLCBar, Trade
25
+ from dccd.domain.records import FundingRate, OHLCBar, OpenInterest, Trade
26
26
  from dccd.domain.timeutils import NS, ns_now, ns_to_dt
27
27
  from dccd.domain.types import DataType
28
- from dccd.sources.base import OHLCHistory, OrderBookSnapshotREST, TradesHistory
28
+ from dccd.sources.base import (
29
+ FundingHistory,
30
+ OHLCHistory,
31
+ OpenInterestHistory,
32
+ OrderBookSnapshotREST,
33
+ TradesHistory,
34
+ )
29
35
  from dccd.sources.registry import SourceRegistry
30
36
  from dccd.storage.coverage_sqlite import CoverageStore
31
37
  from dccd.storage.parquet import ParquetStore
@@ -62,12 +68,29 @@ _STREAM_FLUSH_INTERVAL_S = 60.0
62
68
  # Bounds the very first backfill so it can't silently run for millions of rows
63
69
  # (trades) or from epoch 0. Deep history is opt-in via an explicit start date.
64
70
  _DEFAULT_LOOKBACK_NS = {
65
- DataType.OHLC: 30 * 86400 * NS, # ~720 1h bars / 43k 1m bars
66
- DataType.TRADES: 3600 * NS, # 1 hour of trades
67
- DataType.ORDERBOOK: 3600 * NS, # single snapshot anyway
71
+ DataType.OHLC: 30 * 86400 * NS, # ~720 1h bars / 43k 1m bars
72
+ DataType.TRADES: 3600 * NS, # 1 hour of trades
73
+ DataType.ORDERBOOK: 3600 * NS, # single snapshot anyway
74
+ DataType.FUNDING: 365 * 86400 * NS, # ~1095 events/yr at 8h cadence — cheap
75
+ DataType.OPEN_INTEREST: 30 * 86400 * NS, # ~720 1h observations — same as OHLC
68
76
  }
69
77
 
70
78
 
79
+ def _check_market(cap: Any, target: JobTarget) -> None:
80
+ """Reject a non-spot target the capability has not declared.
81
+
82
+ ``Capability.markets`` defaults to ``None`` (spot-only) for every
83
+ existing declaration, so this preserves the capability-honesty invariant:
84
+ a source must opt in explicitly (``markets=[...]``) before a derivative
85
+ target is accepted, and rejection happens before any fetch is attempted.
86
+ """
87
+ market = target.symbol.market
88
+ if market != "spot" and market not in (cap.markets or []):
89
+ raise NoCapability(
90
+ target.exchange, f"{target.data_type.value}[{market}]", "historical"
91
+ )
92
+
93
+
71
94
  def _make_dataset_id(target: JobTarget) -> DatasetId:
72
95
  return DatasetId(
73
96
  exchange=target.exchange,
@@ -212,7 +235,12 @@ async def backfill(
212
235
  # short recent window (use a custom start date for deep history).
213
236
  lookback = _DEFAULT_LOOKBACK_NS.get(target.data_type, 30 * 86400 * NS)
214
237
  start_ns = end_ns - lookback
215
- human = "1 hour" if target.data_type == DataType.TRADES else "30 days"
238
+ if target.data_type == DataType.TRADES:
239
+ human = "1 hour"
240
+ elif target.data_type == DataType.FUNDING:
241
+ human = "365 days"
242
+ else:
243
+ human = "30 days"
216
244
  _emit_log(events, runs_store, run_id,
217
245
  f"No existing data — starting from {human} ago "
218
246
  "(set a custom start date for more)")
@@ -277,6 +305,7 @@ async def backfill(
277
305
  cap = adapter.capability_for(DataType.OHLC, "rest", "historical")
278
306
  if cap is None:
279
307
  raise NoCapability(target.exchange, "ohlc", "historical")
308
+ _check_market(cap, target)
280
309
 
281
310
  from dccd.transport.paginate import paginate_ohlc
282
311
 
@@ -328,6 +357,7 @@ async def backfill(
328
357
  cap = adapter.capability_for(DataType.TRADES, "rest", "historical")
329
358
  if cap is None:
330
359
  raise NoCapability(target.exchange, "trades", "historical")
360
+ _check_market(cap, target)
331
361
 
332
362
  from dccd.transport.paginate import paginate_trades
333
363
 
@@ -362,9 +392,107 @@ async def backfill(
362
392
  if not (stop_event and stop_event.is_set()):
363
393
  _emit_time(end_ns)
364
394
 
395
+ elif target.data_type == DataType.FUNDING:
396
+ if not isinstance(adapter, FundingHistory):
397
+ raise NoCapability(target.exchange, "funding", "historical")
398
+ cap = adapter.capability_for(DataType.FUNDING, "rest", "historical")
399
+ if cap is None:
400
+ raise NoCapability(target.exchange, "funding", "historical")
401
+ _check_market(cap, target)
402
+
403
+ # paginate_trades is duck-typed on ``.ts`` (see _get_ts in
404
+ # transport/paginate.py) and drives any cursor-paged record
405
+ # stream — funding events reuse it unchanged, no renaming.
406
+ from dccd.transport.paginate import paginate_trades
407
+
408
+ sym = target.symbol
409
+
410
+ async def _fetch_funding(
411
+ s_ns: int, e_ns: int, limit: int, cursor: str | None,
412
+ ) -> tuple[list[FundingRate], str | None]:
413
+ return await adapter.fetch_funding_page(sym, s_ns, e_ns, limit, cursor)
414
+
415
+ funding_batch: list[FundingRate] = []
416
+ async for rate in paginate_trades(_fetch_funding, cap, start_ns, end_ns):
417
+ if stop_event and stop_event.is_set():
418
+ break
419
+ funding_batch.append(rate)
420
+ _collected[0] += 1
421
+ _track_ts(rate.ts)
422
+ if _collected[0] % 200 == 0:
423
+ _emit_time(rate.ts)
424
+ if len(funding_batch) >= _FLUSH_BATCH:
425
+ total_written += await _flush(store, ds, funding_batch, prov_src)
426
+
427
+ total_written += await _flush(store, ds, funding_batch, prov_src)
428
+ if not (stop_event and stop_event.is_set()):
429
+ _emit_time(end_ns)
430
+
431
+ elif target.data_type == DataType.OPEN_INTEREST:
432
+ if not isinstance(adapter, OpenInterestHistory):
433
+ raise NoCapability(target.exchange, "open_interest", "historical")
434
+ cap = adapter.capability_for(DataType.OPEN_INTEREST, "rest", "historical")
435
+ if cap is None:
436
+ raise NoCapability(target.exchange, "open_interest", "historical")
437
+ _check_market(cap, target)
438
+
439
+ span = target.span or 3600
440
+ if cap.spans and span not in cap.spans:
441
+ raise ValueError(
442
+ f"Span {span}s not supported by {target.exchange}. "
443
+ f"Supported spans: {sorted(cap.spans)}"
444
+ )
445
+
446
+ # Honour a time-bound "recent" window (used by Binance, leaf
447
+ # 06): paginating further back just re-fetches the same recent
448
+ # observations — clamp + warn instead, mirroring the Kraken
449
+ # OHLC clamp above.
450
+ if cap.history == "recent" and cap.recent_window_s:
451
+ earliest = end_ns - cap.recent_window_s * NS
452
+ if start_ns < earliest:
453
+ _emit_log(
454
+ events, runs_store, run_id,
455
+ f"{target.exchange} open interest serves only the "
456
+ f"last {cap.recent_window_s}s; clamping start "
457
+ f"to {ns_to_dt(earliest).isoformat()}.",
458
+ level="warning",
459
+ )
460
+ start_ns = earliest
461
+
462
+ # Span-typed like OHLC but cursor-paged like TRADES/FUNDING —
463
+ # paginate_trades is duck-typed on ``.ts`` and drives it unchanged.
464
+ from dccd.transport.paginate import paginate_trades
465
+
466
+ sym = target.symbol
467
+
468
+ async def _fetch_oi(
469
+ s_ns: int, e_ns: int, limit: int, cursor: str | None,
470
+ ) -> tuple[list[OpenInterest], str | None]:
471
+ return await adapter.fetch_oi_page(sym, span, s_ns, e_ns, limit, cursor)
472
+
473
+ oi_batch: list[OpenInterest] = []
474
+ async for oi in paginate_trades(_fetch_oi, cap, start_ns, end_ns):
475
+ if stop_event and stop_event.is_set():
476
+ break
477
+ oi_batch.append(oi)
478
+ _collected[0] += 1
479
+ _track_ts(oi.ts)
480
+ if _collected[0] % 200 == 0:
481
+ _emit_time(oi.ts)
482
+ if len(oi_batch) >= _FLUSH_BATCH:
483
+ total_written += await _flush(store, ds, oi_batch, prov_src)
484
+
485
+ total_written += await _flush(store, ds, oi_batch, prov_src)
486
+ if not (stop_event and stop_event.is_set()):
487
+ _emit_time(end_ns)
488
+
365
489
  elif target.data_type == DataType.ORDERBOOK:
366
490
  if not isinstance(adapter, OrderBookSnapshotREST):
367
491
  raise NoCapability(target.exchange, "orderbook", "snapshot")
492
+ cap = adapter.capability_for(DataType.ORDERBOOK, "rest", "historical")
493
+ if cap is None:
494
+ raise NoCapability(target.exchange, "orderbook", "historical")
495
+ _check_market(cap, target)
368
496
  depth = params.depth or 50
369
497
  snap = await adapter.fetch_orderbook(target.symbol, depth)
370
498
  _track_ts(snap.ts)
@@ -39,6 +39,17 @@ class Capability(BaseModel, frozen=True):
39
39
  a "live" stream that never writes anything.
40
40
  auth_required : bool
41
41
  Whether this capability requires authentication.
42
+ markets : list[str] or None
43
+ Non-spot markets this capability serves (e.g. ``['perp']``,
44
+ ``['perp', 'quarter']``). ``None`` means spot-only — the honest
45
+ default for every existing declaration; a source must opt in
46
+ explicitly before a derivative-market target is accepted.
47
+ recent_window_s : int or None
48
+ Length, in seconds, of the recent window served when ``history``
49
+ is ``'recent'`` and that window is time-bound rather than
50
+ bar-count-bound (``max_per_request`` bars). ``None`` when the
51
+ recent window is bar-count-bound or not applicable. Used by the
52
+ Binance open-interest adapter.
42
53
 
43
54
  Examples
44
55
  --------
@@ -58,3 +69,5 @@ class Capability(BaseModel, frozen=True):
58
69
  max_depth: int | None = None
59
70
  depths: list[int] | None = None
60
71
  auth_required: bool = False
72
+ markets: list[str] | None = None
73
+ recent_window_s: int | None = None
@@ -28,8 +28,16 @@ class DatasetId(BaseModel, frozen=True):
28
28
  span: int | None = None
29
29
 
30
30
  def pair_slug(self) -> str:
31
- """Return filesystem-safe pair string (e.g. ``'BTC-USDT'``)."""
32
- return f"{self.symbol.base}-{self.symbol.quote}"
31
+ """Return filesystem-safe pair string.
32
+
33
+ Spot: ``'BTC-USDT'``. Non-spot markets append the upper-cased market
34
+ as a suffix so derivative datasets never collide with spot ones on
35
+ disk, e.g. ``'BTC-USDT_PERP'``, ``'BTC-USDT_QUARTER'``.
36
+ """
37
+ slug = f"{self.symbol.base}-{self.symbol.quote}"
38
+ if self.symbol.market != "spot":
39
+ slug += f"_{self.symbol.market.upper()}"
40
+ return slug
33
41
 
34
42
  def __str__(self) -> str:
35
43
  parts = [self.exchange, str(self.symbol), self.data_type.value]
@@ -6,7 +6,14 @@ from typing import Literal
6
6
 
7
7
  from pydantic import BaseModel
8
8
 
9
- __all__ = ["OHLCBar", "Trade", "OrderBookLevel", "OrderBookSnapshot"]
9
+ __all__ = [
10
+ "OHLCBar",
11
+ "Trade",
12
+ "OrderBookLevel",
13
+ "OrderBookSnapshot",
14
+ "FundingRate",
15
+ "OpenInterest",
16
+ ]
10
17
 
11
18
 
12
19
  class OHLCBar(BaseModel, frozen=True):
@@ -112,3 +119,55 @@ class OrderBookSnapshot(BaseModel, frozen=True):
112
119
  bids: list[OrderBookLevel]
113
120
  asks: list[OrderBookLevel]
114
121
  is_snapshot: bool = True
122
+
123
+
124
+ class FundingRate(BaseModel, frozen=True):
125
+ """One realized perpetual-futures funding event.
126
+
127
+ Attributes
128
+ ----------
129
+ ts : int
130
+ Funding time, **nanoseconds UTC**.
131
+ rate : float
132
+ Realized funding rate for this event (e.g. ``0.0001`` = 0.01%).
133
+ mark_price : float or None
134
+ Mark price at funding time (not always available).
135
+
136
+ Examples
137
+ --------
138
+ >>> f = FundingRate(ts=1_000_000_000_000_000_000, rate=0.0001)
139
+ >>> f.mark_price is None
140
+ True
141
+ """
142
+
143
+ ts: int
144
+ rate: float
145
+ mark_price: float | None = None
146
+
147
+
148
+ class OpenInterest(BaseModel, frozen=True):
149
+ """One open-interest observation for a derivative instrument.
150
+
151
+ Span-typed like OHLC: one row per fixed-cadence bucket (e.g. hourly),
152
+ rather than one row per event like :class:`FundingRate`.
153
+
154
+ Attributes
155
+ ----------
156
+ ts : int
157
+ Observation time, **nanoseconds UTC**, aligned to the requested span.
158
+ open_interest : float
159
+ Open interest in contracts/base units.
160
+ open_interest_value : float or None
161
+ Open interest expressed as notional value (quote units), when the
162
+ exchange provides it. ``None`` when not available.
163
+
164
+ Examples
165
+ --------
166
+ >>> oi = OpenInterest(ts=1_000_000_000_000_000_000, open_interest=5000.0)
167
+ >>> oi.open_interest_value is None
168
+ True
169
+ """
170
+
171
+ ts: int
172
+ open_interest: float
173
+ open_interest_value: float | None = None
@@ -0,0 +1,101 @@
1
+ """Symbol — canonical trading pair representation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from pydantic import BaseModel, field_validator
8
+
9
+ __all__ = ["Symbol"]
10
+
11
+ _ALIASES: dict[str, str] = {"XBT": "BTC"}
12
+
13
+
14
+ _MARKETS: tuple[str, ...] = ("spot", "perp", "quarter", "next_quarter")
15
+
16
+
17
+ class Symbol(BaseModel, frozen=True):
18
+ """Canonical trading pair (base/quote, spot by default).
19
+
20
+ ``market`` addresses non-spot derivative markets (``perp``, ``quarter``,
21
+ ``next_quarter``); ``str()`` only appends the ``:<market>`` suffix when
22
+ it is not ``spot``, so existing spot-only code paths (storage layout,
23
+ job ids) are unaffected.
24
+
25
+ Examples
26
+ --------
27
+ >>> Symbol(base='BTC', quote='USDT')
28
+ Symbol(base='BTC', quote='USDT', market='spot')
29
+ >>> str(Symbol(base='BTC', quote='USDT'))
30
+ 'BTC/USDT'
31
+ >>> str(Symbol(base='BTC', quote='USDT', market='perp'))
32
+ 'BTC/USDT:perp'
33
+ >>> Symbol.parse('BTC/USDT')
34
+ Symbol(base='BTC', quote='USDT', market='spot')
35
+ >>> Symbol.parse('XBT/USD')
36
+ Symbol(base='BTC', quote='USD', market='spot')
37
+ >>> Symbol.parse('BTC/USDT:perp')
38
+ Symbol(base='BTC', quote='USDT', market='perp')
39
+ """
40
+
41
+ base: str
42
+ quote: str
43
+ market: Literal["spot", "perp", "quarter", "next_quarter"] = "spot"
44
+
45
+ @field_validator("base", "quote", mode="before")
46
+ @classmethod
47
+ def _normalize(cls, v: str) -> str:
48
+ v = v.upper().strip()
49
+ return _ALIASES.get(v, v)
50
+
51
+ def __str__(self) -> str:
52
+ if self.market == "spot":
53
+ return f"{self.base}/{self.quote}"
54
+ return f"{self.base}/{self.quote}:{self.market}"
55
+
56
+ def __repr__(self) -> str:
57
+ return f"Symbol(base={self.base!r}, quote={self.quote!r}, market={self.market!r})"
58
+
59
+ @classmethod
60
+ def parse(
61
+ cls,
62
+ raw: str,
63
+ market: Literal["spot", "perp", "quarter", "next_quarter"] = "spot",
64
+ ) -> "Symbol":
65
+ """Parse a pair string with an optional separator and market suffix.
66
+
67
+ Accepted formats: ``BTC/USDT``, ``BTC-USDT``, ``BTCUSDT`` (ambiguous,
68
+ use explicit separator when possible), each optionally followed by
69
+ ``:<market>`` (e.g. ``BTC/USDT:perp``). An explicit suffix wins over
70
+ the ``market`` keyword argument.
71
+
72
+ Parameters
73
+ ----------
74
+ raw : str
75
+ Pair string, optionally suffixed with ``:<market>``.
76
+ market : 'spot', 'perp', 'quarter', or 'next_quarter'
77
+ Market to use when ``raw`` carries no ``:<market>`` suffix.
78
+
79
+ Examples
80
+ --------
81
+ >>> Symbol.parse('ETH-USD')
82
+ Symbol(base='ETH', quote='USD', market='spot')
83
+ >>> Symbol.parse('ETH-USD:quarter')
84
+ Symbol(base='ETH', quote='USD', market='quarter')
85
+ """
86
+ pair = raw
87
+ if ":" in raw:
88
+ pair, suffix = raw.split(":", 1)
89
+ if suffix not in _MARKETS:
90
+ raise ValueError(
91
+ f"Unknown market {suffix!r} in {raw!r}. "
92
+ f"Supported: {_MARKETS}"
93
+ )
94
+ market = suffix # type: ignore[assignment]
95
+ for sep in ("/", "-", "_"):
96
+ if sep in pair:
97
+ base, quote = pair.split(sep, 1)
98
+ return cls(base=base, quote=quote, market=market)
99
+ raise ValueError(
100
+ f"Cannot parse symbol {raw!r}: use a separator like '/' or '-'"
101
+ )
@@ -23,6 +23,7 @@ __all__ = [
23
23
  "span_label",
24
24
  "binance_interval",
25
25
  "bybit_interval",
26
+ "bybit_oi_interval",
26
27
  "okx_interval",
27
28
  "kraken_interval",
28
29
  "coinbase_granularity",
@@ -241,6 +242,32 @@ def bybit_interval(span: int) -> str | None:
241
242
  return result
242
243
 
243
244
 
245
+ def bybit_oi_interval(span: int) -> str | None:
246
+ """Return Bybit open-interest ``intervalTime`` string for *span* seconds.
247
+
248
+ Bybit's ``/v5/market/open-interest`` endpoint uses its own fixed set of
249
+ interval strings — distinct from :func:`bybit_interval` (the kline
250
+ interval codes).
251
+
252
+ Examples
253
+ --------
254
+ >>> bybit_oi_interval(3600)
255
+ '1h'
256
+ >>> bybit_oi_interval(86400)
257
+ '1d'
258
+ >>> bybit_oi_interval(120) is None
259
+ True
260
+ """
261
+ _map = {
262
+ 300: "5min", 900: "15min", 1800: "30min",
263
+ 3600: "1h", 14400: "4h", 86400: "1d",
264
+ }
265
+ result = _map.get(span)
266
+ if result is None:
267
+ _logger.warning("No Bybit open-interest interval for span=%d", span)
268
+ return result
269
+
270
+
244
271
  def okx_interval(span: int) -> str | None:
245
272
  """Return OKX bar string for *span* seconds.
246
273