@senpi/runtime 3.0.9-dev.20260710204324 → 3.0.9-dev.feat-strategy-compos.20260716013009
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.
- package/dist/cli/composer-commands.d.ts +37 -0
- package/dist/cli/composer-commands.d.ts.map +1 -0
- package/dist/cli/composer-commands.js +287 -0
- package/dist/cli/composer-commands.js.map +1 -0
- package/dist/cli/senpi-commands.d.ts.map +1 -1
- package/dist/cli/senpi-commands.js +2 -0
- package/dist/cli/senpi-commands.js.map +1 -1
- package/dist/cli/validate-runtime-config.mjs +124 -0
- package/dist/composer/AUTHORING.md +233 -0
- package/dist/composer/__init__.py +29 -0
- package/dist/composer/authoring/__init__.py +49 -0
- package/dist/composer/authoring/answers.py +226 -0
- package/dist/composer/authoring/archetypes/__init__.py +25 -0
- package/dist/composer/authoring/archetypes/_common.py +218 -0
- package/dist/composer/authoring/archetypes/classifier.py +109 -0
- package/dist/composer/authoring/archetypes/skeleton.py +54 -0
- package/dist/composer/authoring/archetypes/thesis_fund.py +103 -0
- package/dist/composer/authoring/archetypes/trend_momentum.py +104 -0
- package/dist/composer/authoring/builder.py +191 -0
- package/dist/composer/authoring/emit.py +264 -0
- package/dist/composer/authoring/gaps.py +115 -0
- package/dist/composer/authoring/generate.py +131 -0
- package/dist/composer/authoring/presets.py +168 -0
- package/dist/composer/authoring/runtime_emit.py +266 -0
- package/dist/composer/authoring/strategy_manifest.py +94 -0
- package/dist/composer/cli.py +355 -0
- package/dist/composer/compiler/__init__.py +22 -0
- package/dist/composer/compiler/compile.py +550 -0
- package/dist/composer/examples/breakout_swing.graph.yaml +121 -0
- package/dist/composer/examples/conviction_scorer.graph.yaml +216 -0
- package/dist/composer/examples/macro_thesis_basket.graph.yaml +247 -0
- package/dist/composer/examples/pre_listing_classifier.graph.yaml +204 -0
- package/dist/composer/examples/trend_momentum_majors.graph.yaml +133 -0
- package/dist/composer/generated/README.md +22 -0
- package/dist/composer/generated/catalog.md +84 -0
- package/dist/composer/generated/describe.md +703 -0
- package/dist/composer/generated/graph.schema.json +1203 -0
- package/dist/composer/primitives/__init__.py +239 -0
- package/dist/composer/primitives/_candles.py +76 -0
- package/dist/composer/primitives/adapter.py +120 -0
- package/dist/composer/primitives/emitters.py +142 -0
- package/dist/composer/primitives/filters.py +71 -0
- package/dist/composer/primitives/indicators.py +203 -0
- package/dist/composer/primitives/rankers.py +40 -0
- package/dist/composer/primitives/scorers.py +100 -0
- package/dist/composer/primitives/sources.py +405 -0
- package/dist/composer/primitives/stateful.py +52 -0
- package/dist/composer/pure_fn/__init__.py +34 -0
- package/dist/composer/pure_fn/checks.py +39 -0
- package/dist/composer/pure_fn/models.py +177 -0
- package/dist/composer/pure_fn/purity.py +311 -0
- package/dist/composer/pure_fn/runtests.py +155 -0
- package/dist/composer/registry/__init__.py +40 -0
- package/dist/composer/registry/generate.py +422 -0
- package/dist/composer/registry/models.py +331 -0
- package/dist/composer/registry/nodes.py +673 -0
- package/dist/composer/requirements.txt +21 -0
- package/dist/composer/templates/__init__.py +13 -0
- package/dist/composer/templates/scan.py.j2 +31 -0
- package/dist/composer/validator/__init__.py +29 -0
- package/dist/composer/validator/desugar.py +133 -0
- package/dist/composer/validator/errors.py +191 -0
- package/dist/composer/validator/graph_checks.py +348 -0
- package/dist/composer/validator/loader.py +110 -0
- package/dist/composer/validator/schema_checks.py +147 -0
- package/dist/composer/validator/validate.py +86 -0
- package/dist/composer/verbs/__init__.py +33 -0
- package/dist/composer/verbs/check.py +193 -0
- package/dist/composer/verbs/deploy.py +223 -0
- package/dist/composer/verbs/docs.py +30 -0
- package/dist/composer/verbs/runtime_validate.py +262 -0
- package/dist/composer/verbs/smoke.py +115 -0
- package/dist/composer/verbs/status.py +205 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -9
- package/dist/index.js.map +1 -1
- package/dist/runtime-api/config.d.ts +2 -2
- package/dist/runtime-api/config.js +4 -4
- package/dist/runtime-api/config.js.map +1 -1
- package/dist/runtime-api/handlers/ingest-signals.d.ts +3 -5
- package/dist/runtime-api/handlers/ingest-signals.d.ts.map +1 -1
- package/dist/runtime-api/handlers/ingest-signals.js +5 -14
- package/dist/runtime-api/handlers/ingest-signals.js.map +1 -1
- package/dist/runtime-api/intake/intake-mount.d.ts.map +1 -1
- package/dist/runtime-api/intake/intake-mount.js +2 -8
- package/dist/runtime-api/intake/intake-mount.js.map +1 -1
- package/dist/skills-manager/manifest.js +1 -1
- package/dist/skills-manager/manifest.js.map +1 -1
- package/dist/skills-manager/skills-manifest.json +1 -1
- package/package.json +4 -2
- package/dist/runtime-api/intake/ingest-mutex.d.ts +0 -16
- package/dist/runtime-api/intake/ingest-mutex.d.ts.map +0 -1
- package/dist/runtime-api/intake/ingest-mutex.js +0 -18
- package/dist/runtime-api/intake/ingest-mutex.js.map +0 -1
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""sources — pure normalizers for the raw MCP responses the data-source nodes read.
|
|
2
|
+
|
|
3
|
+
Split of concerns (slice-3 golden design): the ACTUAL MCP read (``ctx.senpi_mcp.
|
|
4
|
+
call_tool``) lives in the thin ``adapter.McpSourceAdapter``; these functions are the
|
|
5
|
+
PURE part — they take the raw response(s) the adapter fetched and reduce them to the
|
|
6
|
+
node's typed output ports. That split is what lets the golden tests stub source data
|
|
7
|
+
at the adapter/MCP boundary and still exercise the real normalization.
|
|
8
|
+
|
|
9
|
+
Response shapes and reductions are ported from the corpus originals under
|
|
10
|
+
``/Users/duncan/Senpi/skills/strategies/{stag,hawk}/main/scanners/scan.py``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from ._candles import _f
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def candles_fetch(raw_by_asset: dict, *, intervals: list) -> dict:
|
|
19
|
+
"""Normalize per-asset ``market_get_asset_data`` responses into the candles port.
|
|
20
|
+
|
|
21
|
+
Output: ``{asset: {interval: [candle_dict, ...]}}`` (the ``candles`` port type).
|
|
22
|
+
Ported from stag ``_fetch_candles`` / hawk ``_asset_data``: unwrap ``data`` then
|
|
23
|
+
``candles[<interval>]``. A missing / falsy / success:false response drops the asset.
|
|
24
|
+
"""
|
|
25
|
+
out: dict = {}
|
|
26
|
+
for asset in sorted(raw_by_asset):
|
|
27
|
+
raw = raw_by_asset[asset]
|
|
28
|
+
if not raw:
|
|
29
|
+
continue
|
|
30
|
+
if isinstance(raw, dict) and raw.get("success") is False:
|
|
31
|
+
continue
|
|
32
|
+
block = raw.get("data", raw) if isinstance(raw, dict) else {}
|
|
33
|
+
if not isinstance(block, dict):
|
|
34
|
+
continue
|
|
35
|
+
cands = block.get("candles", {}) or {}
|
|
36
|
+
if not isinstance(cands, dict):
|
|
37
|
+
continue
|
|
38
|
+
entry = {iv: (cands.get(iv, []) or []) for iv in intervals}
|
|
39
|
+
# Carry asset_context (markPx/prevDayPx) alongside the candles so own_return_24h
|
|
40
|
+
# can derive a 24h return without a second read (thesis-fund). Indicators ignore
|
|
41
|
+
# the extra key (they read candles[asset][interval]); a graph without asset_context
|
|
42
|
+
# (stag/hawk/bison fixtures) is byte-unchanged since the key is simply absent.
|
|
43
|
+
ac = block.get("asset_context")
|
|
44
|
+
if isinstance(ac, dict) and ac:
|
|
45
|
+
entry["asset_context"] = ac
|
|
46
|
+
out[asset] = entry
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def instrument_list(raw) -> list:
|
|
51
|
+
"""Normalize ``market_list_instruments`` into a list of instrument RECORDS. Port:
|
|
52
|
+
instruments (asset_list). Ported from magpie ``_fetch_ipop_universe`` + thesis-fund
|
|
53
|
+
``_get_universe_meta``.
|
|
54
|
+
|
|
55
|
+
Each record: ``{name, funding (|abs|), max_leverage, is_delisted, day_volume}``. The
|
|
56
|
+
records (not bare names) are the ``asset_list`` value flowing into universe_discover /
|
|
57
|
+
classifier_predicate so those predicates can gate on venue fields; universe_discover
|
|
58
|
+
projects back to bare names for the tradeable universe. Sorted by name for determinism.
|
|
59
|
+
"""
|
|
60
|
+
data = raw.get("data", raw) if isinstance(raw, dict) else raw
|
|
61
|
+
insts = data.get("instruments", data) if isinstance(data, dict) else data
|
|
62
|
+
if isinstance(insts, dict):
|
|
63
|
+
insts = insts.get("instruments", [])
|
|
64
|
+
if not isinstance(insts, list):
|
|
65
|
+
return []
|
|
66
|
+
out: list = []
|
|
67
|
+
for inst in insts:
|
|
68
|
+
if not isinstance(inst, dict):
|
|
69
|
+
continue
|
|
70
|
+
ctxb = inst.get("context", {}) if isinstance(inst.get("context"), dict) else {}
|
|
71
|
+
name = inst.get("name") or ctxb.get("coin")
|
|
72
|
+
if not name or not isinstance(name, str):
|
|
73
|
+
continue
|
|
74
|
+
out.append({
|
|
75
|
+
"name": name,
|
|
76
|
+
"funding": abs(_f(ctxb.get("funding", 0))),
|
|
77
|
+
"max_leverage": _f(inst.get("max_leverage", inst.get("maxLeverage", 0))),
|
|
78
|
+
"is_delisted": bool(inst.get("is_delisted", False)),
|
|
79
|
+
"day_volume": _f(ctxb.get("dayNtlVlm", 0)),
|
|
80
|
+
})
|
|
81
|
+
return sorted(out, key=lambda r: r["name"])
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def universe_discover(instruments: list, *, min_day_volume: float,
|
|
85
|
+
max_leverage_cap: float, name_prefix: str) -> list:
|
|
86
|
+
"""Derive the tradeable universe (bare NAMES) by filtering instrument records. Port:
|
|
87
|
+
universe (asset_list). Ported from magpie ``ipop_passes_universe`` (the prefix /
|
|
88
|
+
leverage / min-volume portion); the funding portion lives in classifier_predicate, so a
|
|
89
|
+
faithful magpie discovery chains classifier_predicate -> universe_discover.
|
|
90
|
+
|
|
91
|
+
Generalizes thesis-fund's identity "is this on the live board" check: with the default
|
|
92
|
+
params (no prefix, cap 5, min-volume 0) a plain-name list passes through unchanged.
|
|
93
|
+
"""
|
|
94
|
+
out: list = []
|
|
95
|
+
for inst in instruments or []:
|
|
96
|
+
rec = inst if isinstance(inst, dict) else {"name": inst}
|
|
97
|
+
name = rec.get("name")
|
|
98
|
+
if not isinstance(name, str):
|
|
99
|
+
continue
|
|
100
|
+
if name_prefix and not name.startswith(name_prefix):
|
|
101
|
+
continue
|
|
102
|
+
if rec.get("is_delisted"):
|
|
103
|
+
continue
|
|
104
|
+
lev = _f(rec.get("max_leverage", 0))
|
|
105
|
+
if lev and lev > max_leverage_cap:
|
|
106
|
+
continue
|
|
107
|
+
if _f(rec.get("day_volume", 0)) < min_day_volume:
|
|
108
|
+
continue
|
|
109
|
+
out.append(name)
|
|
110
|
+
return sorted(out)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def own_return_24h(candles: dict) -> dict:
|
|
114
|
+
"""Per-asset 24h percent return from the asset_context carried on candles. Port:
|
|
115
|
+
return_24h (feature_map). Ported from thesis-fund ``_asset_market`` ret_24h:
|
|
116
|
+
``(markPx - prevDayPx) / prevDayPx * 100`` when both are positive; else omitted.
|
|
117
|
+
"""
|
|
118
|
+
out: dict = {}
|
|
119
|
+
for asset in sorted(candles):
|
|
120
|
+
block = candles[asset] if isinstance(candles[asset], dict) else {}
|
|
121
|
+
ac = block.get("asset_context")
|
|
122
|
+
if not isinstance(ac, dict):
|
|
123
|
+
continue
|
|
124
|
+
mark = _f(ac.get("markPx", 0))
|
|
125
|
+
prev = _f(ac.get("prevDayPx", 0))
|
|
126
|
+
if prev > 0 and mark > 0:
|
|
127
|
+
out[asset] = ((mark - prev) / prev) * 100.0
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def clearinghouse_state(raw) -> tuple[list, float]:
|
|
132
|
+
"""Reduce a ``strategy_get_clearinghouse_state`` response to (held, equity).
|
|
133
|
+
|
|
134
|
+
Ports: held (asset_list), equity (scalar). Ported from hawk ``_get_account`` +
|
|
135
|
+
stag ``_held_assets``: dual-DEX max() account value across main/xyz (never sum ->
|
|
136
|
+
no double-count of the shared cross-margin balance); held = coins with a non-zero
|
|
137
|
+
``szi`` in either sub-DEX. Includes the read-sanity guard: margin/notional in use
|
|
138
|
+
but an EMPTY positions list is a corrupt read -> (held=[], equity=0.0).
|
|
139
|
+
"""
|
|
140
|
+
data = raw.get("data", raw) if isinstance(raw, dict) else {}
|
|
141
|
+
if not isinstance(data, dict):
|
|
142
|
+
return [], 0.0
|
|
143
|
+
|
|
144
|
+
held: set = set()
|
|
145
|
+
equity = 0.0
|
|
146
|
+
for section in ("main", "xyz"):
|
|
147
|
+
s = data.get(section, {})
|
|
148
|
+
if not isinstance(s, dict):
|
|
149
|
+
continue
|
|
150
|
+
ms = s.get("marginSummary", {}) if isinstance(s.get("marginSummary"), dict) else {}
|
|
151
|
+
equity = max(equity, _f(ms.get("accountValue", 0)))
|
|
152
|
+
for ap in s.get("assetPositions", []) or []:
|
|
153
|
+
pos = ap.get("position", ap) if isinstance(ap, dict) else {}
|
|
154
|
+
if _f(pos.get("szi", 0)) != 0:
|
|
155
|
+
coin = str(pos.get("coin", "")).upper()
|
|
156
|
+
if coin:
|
|
157
|
+
held.add(coin)
|
|
158
|
+
|
|
159
|
+
in_use = 0.0
|
|
160
|
+
for section in ("main", "xyz"):
|
|
161
|
+
s = data.get(section, {}) if isinstance(data, dict) else {}
|
|
162
|
+
ms = s.get("marginSummary", {}) if isinstance(s, dict) else {}
|
|
163
|
+
if not isinstance(ms, dict):
|
|
164
|
+
continue
|
|
165
|
+
in_use = max(in_use, _f(ms.get("totalMarginUsed", 0)), abs(_f(ms.get("totalNtlPos", 0))))
|
|
166
|
+
if in_use > 1.0 and not held:
|
|
167
|
+
return [], 0.0
|
|
168
|
+
|
|
169
|
+
return sorted(held), equity
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def sm_lean(raw, *, assets: list, agree_threshold: float) -> dict:
|
|
173
|
+
"""Reduce ``leaderboard_get_markets`` to a per-asset smart-money lean. Port: lean.
|
|
174
|
+
|
|
175
|
+
Ported from stag/hawk ``_sm_direction`` / ``_get_sm_direction``: for each asset,
|
|
176
|
+
long_ratio = long_pct / (long_pct + short_pct) * 100. Output feature value is the
|
|
177
|
+
long_ratio percent in [0, 100] (a LONG-side lean; higher = more net-long smart
|
|
178
|
+
money). Assets not found on the board are omitted; total<=0 -> 50.0 (neutral).
|
|
179
|
+
``agree_threshold`` is carried for signature/param parity — the alignment threshold
|
|
180
|
+
is applied by the scorer that consumes this feature (corpus: stag 0.60, hawk 0.55).
|
|
181
|
+
"""
|
|
182
|
+
markets = raw.get("data", raw) if isinstance(raw, dict) else raw
|
|
183
|
+
if isinstance(markets, dict):
|
|
184
|
+
markets = markets.get("markets", markets.get("leaderboard", markets))
|
|
185
|
+
if isinstance(markets, dict):
|
|
186
|
+
markets = markets.get("markets", [])
|
|
187
|
+
if not isinstance(markets, list):
|
|
188
|
+
markets = []
|
|
189
|
+
|
|
190
|
+
out: dict = {}
|
|
191
|
+
# Output keys preserve the asset name AS WIRED (not force-upper-cased): matching against
|
|
192
|
+
# the leaderboard is case-insensitive, but the feature_map must be keyed the same way the
|
|
193
|
+
# candles/indicator feature_maps are (which preserve case), so a scorer can join them on
|
|
194
|
+
# one asset key. Dynamic-universe names like "xyz:ACME" would otherwise mismatch.
|
|
195
|
+
for asset in sorted({str(a) for a in assets}):
|
|
196
|
+
au = str(asset).upper()
|
|
197
|
+
long_pct = 0.0
|
|
198
|
+
short_pct = 0.0
|
|
199
|
+
found = False
|
|
200
|
+
for m in markets:
|
|
201
|
+
if not isinstance(m, dict):
|
|
202
|
+
continue
|
|
203
|
+
token = str(m.get("token", m.get("coin", m.get("asset", "")))).upper()
|
|
204
|
+
if token != au:
|
|
205
|
+
continue
|
|
206
|
+
found = True
|
|
207
|
+
d = str(m.get("direction", "")).upper()
|
|
208
|
+
pct = _f(m.get("pct_of_top_traders_gain", m.get("longPct", 0)))
|
|
209
|
+
if d == "LONG":
|
|
210
|
+
long_pct = pct
|
|
211
|
+
elif d == "SHORT":
|
|
212
|
+
short_pct = pct
|
|
213
|
+
if not found:
|
|
214
|
+
continue
|
|
215
|
+
total = long_pct + short_pct
|
|
216
|
+
out[asset] = 50.0 if total <= 0 else (long_pct / total) * 100.0
|
|
217
|
+
return out
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
# ============================================================ world-coverage (batch C)
|
|
221
|
+
# Every normalizer below is PURE (raw MCP response -> typed output ports); the adapter does
|
|
222
|
+
# the actual read. Response shapes are ported 1:1 from src/senpi/client.ts call sites cited
|
|
223
|
+
# in /Users/duncan/Senpi/.context/strategy-composer/mcp-surface-recon.md §2, verified against
|
|
224
|
+
# the scaffold surface — no speculative fields.
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def market_prices(raw, *, assets: list) -> dict:
|
|
228
|
+
"""Reduce a ``market_get_prices`` response to a per-asset price feature_map. Port:
|
|
229
|
+
prices (feature_map). Response: ``{prices: {<asset-or-"dex:asset">: number}}`` (or a
|
|
230
|
+
bare map). Mirrors sm_lean's join semantics: the price map is filtered to the wired
|
|
231
|
+
``assets`` and keyed AS WIRED (matched case-insensitively), so it joins the case-
|
|
232
|
+
preserving candle/indicator feature_maps on one asset key. Assets absent from the
|
|
233
|
+
response are omitted.
|
|
234
|
+
"""
|
|
235
|
+
prices = raw.get("prices", raw) if isinstance(raw, dict) else raw
|
|
236
|
+
if not isinstance(prices, dict):
|
|
237
|
+
return {}
|
|
238
|
+
by_upper = {str(k).upper(): v for k, v in prices.items()}
|
|
239
|
+
out: dict = {}
|
|
240
|
+
for asset in sorted({str(a) for a in assets}):
|
|
241
|
+
v = by_upper.get(str(asset).upper())
|
|
242
|
+
if v is None:
|
|
243
|
+
continue
|
|
244
|
+
out[asset] = _f(v)
|
|
245
|
+
return out
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def strategy_list(raw) -> list:
|
|
249
|
+
"""Normalize ``strategy_list`` into a list of strategy-metadata RECORDS. Port:
|
|
250
|
+
strategies (record_list). Response: ``{data:{strategies:[{id, strategyWalletAddress,
|
|
251
|
+
traderAddress, status, strategyType, strategyName, createdAt, totalFunded}]}}``. Fields
|
|
252
|
+
ported 1:1; ``total_funded`` coerced to float. Sorted by ``id`` for determinism.
|
|
253
|
+
"""
|
|
254
|
+
data = raw.get("data", raw) if isinstance(raw, dict) else raw
|
|
255
|
+
rows = data.get("strategies", data) if isinstance(data, dict) else data
|
|
256
|
+
if not isinstance(rows, list):
|
|
257
|
+
return []
|
|
258
|
+
out: list = []
|
|
259
|
+
for r in rows:
|
|
260
|
+
if not isinstance(r, dict):
|
|
261
|
+
continue
|
|
262
|
+
out.append({
|
|
263
|
+
"id": str(r.get("id", "")),
|
|
264
|
+
"wallet": str(r.get("strategyWalletAddress", "")),
|
|
265
|
+
"trader": str(r.get("traderAddress", "")),
|
|
266
|
+
"status": str(r.get("status", "")),
|
|
267
|
+
"strategy_type": str(r.get("strategyType", "")),
|
|
268
|
+
"name": str(r.get("strategyName", "")),
|
|
269
|
+
"created_at": str(r.get("createdAt", "")),
|
|
270
|
+
"total_funded": _f(r.get("totalFunded", 0)),
|
|
271
|
+
})
|
|
272
|
+
return sorted(out, key=lambda x: x["id"])
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def open_orders(raw) -> list:
|
|
276
|
+
"""Normalize ``strategy_get_open_orders`` into a list of order RECORDS. Port: orders
|
|
277
|
+
(record_list). Response: ``{orders:[{orderId, coin, side, size, price, orderType,
|
|
278
|
+
status, timestamp}]}`` (or a bare array). Multiple orders can exist per coin, so this
|
|
279
|
+
is a record list, not an asset-keyed map. Sorted by (coin, orderId) for determinism.
|
|
280
|
+
"""
|
|
281
|
+
orders = raw.get("orders", raw) if isinstance(raw, dict) else raw
|
|
282
|
+
if not isinstance(orders, list):
|
|
283
|
+
return []
|
|
284
|
+
out: list = []
|
|
285
|
+
for o in orders:
|
|
286
|
+
if not isinstance(o, dict):
|
|
287
|
+
continue
|
|
288
|
+
out.append({
|
|
289
|
+
"order_id": str(o.get("orderId", "")),
|
|
290
|
+
"coin": str(o.get("coin", "")).upper(),
|
|
291
|
+
"side": str(o.get("side", "")),
|
|
292
|
+
"size": _f(o.get("size", 0)),
|
|
293
|
+
"price": _f(o.get("price", 0)),
|
|
294
|
+
"order_type": str(o.get("orderType", "")),
|
|
295
|
+
"status": str(o.get("status", "")),
|
|
296
|
+
"timestamp": _f(o.get("timestamp", 0)),
|
|
297
|
+
})
|
|
298
|
+
return sorted(out, key=lambda x: (x["coin"], x["order_id"]))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def trader_history(raw) -> list:
|
|
302
|
+
"""Normalize ``discovery_get_trader_history`` into a list of CLOSED-trade RECORDS.
|
|
303
|
+
Port: closed_positions (record_list). Response: ``{closed_positions:[{coin, dex?, type,
|
|
304
|
+
entryPx, exitPx, szi, realizedPnl, closeTime, openTime, totalFees}]}``. ``closeTime`` /
|
|
305
|
+
``openTime`` are Unix SECONDS (carried through unchanged). Sorted by (closeTime, coin).
|
|
306
|
+
"""
|
|
307
|
+
data = raw.get("data", raw) if isinstance(raw, dict) else raw
|
|
308
|
+
rows = data.get("closed_positions", data) if isinstance(data, dict) else data
|
|
309
|
+
if not isinstance(rows, list):
|
|
310
|
+
return []
|
|
311
|
+
out: list = []
|
|
312
|
+
for r in rows:
|
|
313
|
+
if not isinstance(r, dict):
|
|
314
|
+
continue
|
|
315
|
+
out.append({
|
|
316
|
+
"coin": str(r.get("coin", "")).upper(),
|
|
317
|
+
"dex": str(r.get("dex", "")),
|
|
318
|
+
"type": str(r.get("type", "")),
|
|
319
|
+
"entry_px": _f(r.get("entryPx", 0)),
|
|
320
|
+
"exit_px": _f(r.get("exitPx", 0)),
|
|
321
|
+
"szi": _f(r.get("szi", 0)),
|
|
322
|
+
"realized_pnl": _f(r.get("realizedPnl", 0)),
|
|
323
|
+
"total_fees": _f(r.get("totalFees", 0)),
|
|
324
|
+
"close_time": _f(r.get("closeTime", 0)),
|
|
325
|
+
"open_time": _f(r.get("openTime", 0)),
|
|
326
|
+
})
|
|
327
|
+
return sorted(out, key=lambda x: (x["close_time"], x["coin"]))
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def asset_trading_limits(raw_by_asset: dict) -> dict:
|
|
331
|
+
"""Reduce per-asset ``strategy_get_asset_trading_limits`` responses to a per-asset venue
|
|
332
|
+
max-leverage feature_map. Port: max_leverage (feature_map). The adapter fans the single-
|
|
333
|
+
asset MCP call out over the universe (mirroring asset_data's fanout); each response is
|
|
334
|
+
``{leverage:{value}}`` or ``{maxLeverage}``. A missing / falsy response drops the asset.
|
|
335
|
+
"""
|
|
336
|
+
out: dict = {}
|
|
337
|
+
for asset in sorted(raw_by_asset):
|
|
338
|
+
raw = raw_by_asset[asset]
|
|
339
|
+
if not isinstance(raw, dict):
|
|
340
|
+
continue
|
|
341
|
+
lev = raw.get("leverage")
|
|
342
|
+
if isinstance(lev, dict):
|
|
343
|
+
val = _f(lev.get("value", 0))
|
|
344
|
+
else:
|
|
345
|
+
val = _f(raw.get("maxLeverage", raw.get("max_leverage", 0)))
|
|
346
|
+
if val > 0:
|
|
347
|
+
out[asset] = val
|
|
348
|
+
return out
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def strategy_pnl_snapshot(raw) -> tuple[float, float, float]:
|
|
352
|
+
"""Reduce ``strategy_get_pnl_and_account_value_history`` to today's snapshot scalars.
|
|
353
|
+
Ports: today_pnl (scalar), today_account_value (scalar), today_drawdown (scalar).
|
|
354
|
+
Response: ``{history_by_period:{...}, today_snapshot?:{pnl, account_value, drawdown}}``.
|
|
355
|
+
Only ``today_snapshot`` is decomposed (each field an account-level scalar); the nested
|
|
356
|
+
multi-period ``history_by_period`` is NOT exposed (it needs record_list — deferred). A
|
|
357
|
+
missing snapshot yields (0.0, 0.0, 0.0).
|
|
358
|
+
"""
|
|
359
|
+
data = raw.get("data", raw) if isinstance(raw, dict) else {}
|
|
360
|
+
if not isinstance(data, dict):
|
|
361
|
+
return 0.0, 0.0, 0.0
|
|
362
|
+
snap = data.get("today_snapshot")
|
|
363
|
+
if not isinstance(snap, dict):
|
|
364
|
+
return 0.0, 0.0, 0.0
|
|
365
|
+
return (
|
|
366
|
+
_f(snap.get("pnl", 0)),
|
|
367
|
+
_f(snap.get("account_value", 0)),
|
|
368
|
+
_f(snap.get("drawdown", 0)),
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def trader_state(raw) -> tuple[list, float]:
|
|
373
|
+
"""Reduce a ``discovery_get_trader_state`` response to (held, equity) for an ARBITRARY
|
|
374
|
+
wallet. Ports: held (asset_list), equity (scalar). This is clearinghouse_state's twin
|
|
375
|
+
generalized off the strategy's own wallet (recon §2g / §7) — same (held, equity)
|
|
376
|
+
contract, enabling copy-trading / leaderboard-following archetypes. Response:
|
|
377
|
+
``{traders:[{address, openPositions:[{coin, szi, ...}], marginSummary:{accountValue}}]}``.
|
|
378
|
+
Mirrors clearinghouse_state's read-sanity guard: notional/margin in use but an EMPTY
|
|
379
|
+
positions list is a corrupt read -> (held=[], equity=0.0).
|
|
380
|
+
"""
|
|
381
|
+
data = raw.get("data", raw) if isinstance(raw, dict) else {}
|
|
382
|
+
if not isinstance(data, dict):
|
|
383
|
+
return [], 0.0
|
|
384
|
+
traders = data.get("traders", [])
|
|
385
|
+
if not isinstance(traders, list) or not traders:
|
|
386
|
+
return [], 0.0
|
|
387
|
+
t = traders[0] if isinstance(traders[0], dict) else {}
|
|
388
|
+
|
|
389
|
+
ms = t.get("marginSummary", {}) if isinstance(t.get("marginSummary"), dict) else {}
|
|
390
|
+
equity = _f(ms.get("accountValue", 0))
|
|
391
|
+
|
|
392
|
+
held: set = set()
|
|
393
|
+
for pos in t.get("openPositions", []) or []:
|
|
394
|
+
if not isinstance(pos, dict):
|
|
395
|
+
continue
|
|
396
|
+
if _f(pos.get("szi", 0)) != 0:
|
|
397
|
+
coin = str(pos.get("coin", "")).upper()
|
|
398
|
+
if coin:
|
|
399
|
+
held.add(coin)
|
|
400
|
+
|
|
401
|
+
in_use = max(_f(ms.get("totalMarginUsed", 0)), abs(_f(ms.get("totalNtlPos", 0))))
|
|
402
|
+
if in_use > 1.0 and not held:
|
|
403
|
+
return [], 0.0
|
|
404
|
+
|
|
405
|
+
return sorted(held), equity
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""stateful — the universal TTL signal-dedup node, compiled onto ctx.state (D2).
|
|
2
|
+
|
|
3
|
+
The corpus dedup pattern is identical across all five packages: load last()'s dedup
|
|
4
|
+
map, prune entries older than ``prune_factor * ttl``, expose the assets still within
|
|
5
|
+
``ttl`` as the exclusion set, and after emitting append this tick's signals with the
|
|
6
|
+
current timestamp. Ported from stag/hawk ``scan.scan`` (recent/signaled map + 4x-TTL
|
|
7
|
+
prune).
|
|
8
|
+
|
|
9
|
+
The node is split into READ (prologue) and WRITE (epilogue) halves because its
|
|
10
|
+
``recent`` output is consumed EARLY (prior-tick data, before the pipeline runs) while
|
|
11
|
+
its ``emitted`` input is produced LATE (this tick's signals). This is exactly the
|
|
12
|
+
"stateful outputs carry prior-tick data" semantic the validator's cycle check honors.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _last_map(state) -> dict:
|
|
19
|
+
if state is None or len(state) == 0:
|
|
20
|
+
return {}
|
|
21
|
+
last = state.last() or {}
|
|
22
|
+
recent = last.get("recent", {})
|
|
23
|
+
return dict(recent) if isinstance(recent, dict) else {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def ttl_dedup_state_read(state, *, ttl_seconds: int, prune_factor: int, now: float) -> tuple[list, dict]:
|
|
27
|
+
"""READ half: prune the persisted dedup map and return (recent, working_map).
|
|
28
|
+
|
|
29
|
+
``recent`` (the ``recent`` output port, asset_list) = assets signaled within
|
|
30
|
+
``ttl_seconds``. ``working_map`` = the pruned {asset: ts} map, carried to the WRITE
|
|
31
|
+
half (entries older than ``prune_factor * ttl_seconds`` are dropped).
|
|
32
|
+
"""
|
|
33
|
+
cutoff = now - (ttl_seconds * prune_factor)
|
|
34
|
+
working = {k.upper(): v for k, v in _last_map(state).items() if v >= cutoff}
|
|
35
|
+
recent = sorted(a for a, ts in working.items() if (now - ts) < ttl_seconds)
|
|
36
|
+
return recent, working
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def ttl_dedup_state_write(state, working_map: dict, *, emitted: list, now: float) -> None:
|
|
40
|
+
"""WRITE half (state_out port): record this tick's emitted signals and persist.
|
|
41
|
+
|
|
42
|
+
Stamps each emitted asset with ``now`` in the working map and appends the updated
|
|
43
|
+
map to ctx.state. A None state (history disabled) is a no-op. The scaffold owns the
|
|
44
|
+
per-tick commit/rollback around scan().
|
|
45
|
+
"""
|
|
46
|
+
for sig in emitted:
|
|
47
|
+
asset = str(sig.get("asset", "")).upper()
|
|
48
|
+
if asset:
|
|
49
|
+
working_map[asset] = now
|
|
50
|
+
if state is not None:
|
|
51
|
+
state.append({"recent": working_map})
|
|
52
|
+
return None
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""pure_fn — per-graph pure-function nodes (D2 kind 2): the OPEN extension point.
|
|
2
|
+
|
|
3
|
+
The registry (``composer.registry``) is the CLOSED vocabulary of runtime-owned primitive
|
|
4
|
+
nodes. A ``pure_fn`` node is the complement: an LLM-written Python function declared inline
|
|
5
|
+
in the graph, with declared typed input/output ports (same closed :class:`PortType`
|
|
6
|
+
vocabulary) and a function body. Full code flexibility is preserved while the telemetry
|
|
7
|
+
loop learns which functions to promote to primitives (D2), but it is fenced by a static
|
|
8
|
+
purity gate — no ctx, no MCP, no I/O — so it can never be a custom data source (D3).
|
|
9
|
+
|
|
10
|
+
Package surface (kept to the leaf ``models`` so importing this package never pulls the
|
|
11
|
+
validator — the purity/test stages live in submodules imported directly where used, to
|
|
12
|
+
avoid an import cycle with ``composer.validator``):
|
|
13
|
+
|
|
14
|
+
models — PureFnNode / PureFnParam / parse_pure_fn / is_pure_fn_entry.
|
|
15
|
+
purity (submodule) — check_purity: the static AST allowlist (CMP04x teaching errors).
|
|
16
|
+
runtests (submodule) — run_inline_tests: run inline fixture tests (CMP05x).
|
|
17
|
+
checks (submodule) — check: the validator stage tying purity + tests together.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from .models import (
|
|
21
|
+
PureFnNode,
|
|
22
|
+
PureFnParam,
|
|
23
|
+
is_pure_fn_entry,
|
|
24
|
+
parse_pure_fn,
|
|
25
|
+
parse_single_def,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"PureFnNode",
|
|
30
|
+
"PureFnParam",
|
|
31
|
+
"parse_pure_fn",
|
|
32
|
+
"parse_single_def",
|
|
33
|
+
"is_pure_fn_entry",
|
|
34
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""checks — the validator stage for pure_fn nodes (purity CMP04x + inline tests CMP05x).
|
|
2
|
+
|
|
3
|
+
Runs AFTER the graph-semantic checks. For each ``kind: pure_fn`` node it statically
|
|
4
|
+
purity-checks the body (``purity.check_purity``) and, only if the body is pure, runs its
|
|
5
|
+
inline fixture tests (``runtests.run_inline_tests``). Errors from every node collect into
|
|
6
|
+
one list so the author sees all defects at once (the SERR037 collection rule).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from composer.validator.errors import TeachingError
|
|
12
|
+
|
|
13
|
+
from .models import is_pure_fn_entry, parse_pure_fn
|
|
14
|
+
from .purity import check_purity
|
|
15
|
+
from .runtests import run_inline_tests
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def check(doc: dict, line_index: dict) -> list[TeachingError]:
|
|
19
|
+
errors: list[TeachingError] = []
|
|
20
|
+
nodes = doc.get("nodes")
|
|
21
|
+
if not isinstance(nodes, list):
|
|
22
|
+
return errors
|
|
23
|
+
|
|
24
|
+
used_fn_names: set[str] = set()
|
|
25
|
+
for entry in nodes:
|
|
26
|
+
if not is_pure_fn_entry(entry):
|
|
27
|
+
continue
|
|
28
|
+
node_id = entry.get("id")
|
|
29
|
+
line = line_index.get("nodes", {}).get(node_id) if isinstance(node_id, str) else None
|
|
30
|
+
pfn = parse_pure_fn(entry, line)
|
|
31
|
+
|
|
32
|
+
purity_errors = check_purity(pfn, used_fn_names)
|
|
33
|
+
errors.extend(purity_errors)
|
|
34
|
+
# Only run the fixtures once the body is known pure — otherwise the failures are
|
|
35
|
+
# noise on top of the real (purity) defect.
|
|
36
|
+
if not purity_errors:
|
|
37
|
+
errors.extend(run_inline_tests(pfn))
|
|
38
|
+
|
|
39
|
+
return errors
|