@senpi/trading-recipe 1.0.37 → 1.0.39

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 (32) hide show
  1. package/dist/scanners/__tests__/fixtures/strategy-monitor-scenarios.d.ts +21 -0
  2. package/dist/scanners/__tests__/fixtures/strategy-monitor-scenarios.d.ts.map +1 -0
  3. package/dist/scanners/__tests__/fixtures/strategy-monitor-scenarios.js +197 -0
  4. package/dist/scanners/__tests__/fixtures/strategy-monitor-scenarios.js.map +1 -0
  5. package/dist/scanners/implementations/index.d.ts +1 -0
  6. package/dist/scanners/implementations/index.d.ts.map +1 -1
  7. package/dist/scanners/implementations/index.js +1 -0
  8. package/dist/scanners/implementations/index.js.map +1 -1
  9. package/dist/scanners/implementations/liquidation-watchdog.d.ts +8 -16
  10. package/dist/scanners/implementations/liquidation-watchdog.d.ts.map +1 -1
  11. package/dist/scanners/implementations/liquidation-watchdog.js +35 -14
  12. package/dist/scanners/implementations/liquidation-watchdog.js.map +1 -1
  13. package/dist/scanners/implementations/sm-flip.d.ts.map +1 -1
  14. package/dist/scanners/implementations/sm-flip.js +3 -2
  15. package/dist/scanners/implementations/sm-flip.js.map +1 -1
  16. package/dist/scanners/implementations/strategy-monitor.d.ts +118 -0
  17. package/dist/scanners/implementations/strategy-monitor.d.ts.map +1 -0
  18. package/dist/scanners/implementations/strategy-monitor.js +341 -0
  19. package/dist/scanners/implementations/strategy-monitor.js.map +1 -0
  20. package/dist/scanners/index.d.ts +1 -0
  21. package/dist/scanners/index.d.ts.map +1 -1
  22. package/dist/scanners/index.js +1 -0
  23. package/dist/scanners/index.js.map +1 -1
  24. package/dist/scanners/providers/factory.d.ts.map +1 -1
  25. package/dist/scanners/providers/factory.js +63 -21
  26. package/dist/scanners/providers/factory.js.map +1 -1
  27. package/examples/scanners-liquidation-watchdog.mjs +0 -1
  28. package/examples/strategies/dsl.yaml +52 -0
  29. package/examples/strategies/fox-minimal-loosened.yaml +0 -1
  30. package/examples/strategies/fox-minimal.yaml +0 -1
  31. package/openclaw.plugin.json +1 -1
  32. package/package.json +1 -1
@@ -0,0 +1,118 @@
1
+ import { type Static } from "@sinclair/typebox";
2
+ import type { ClearingHousePosition } from "./liquidation-watchdog.js";
3
+ declare const strategyMonitorConfigSchema: import("@sinclair/typebox").TObject<{
4
+ sizeChangeEpsilon: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
5
+ }>;
6
+ /**
7
+ * Scanner config for `strategy-monitor`.
8
+ *
9
+ * @property sizeChangeEpsilon — Absolute threshold below which position size
10
+ * differences are treated as unchanged. Prevents false INCREASED/DECREASED
11
+ * deltas caused by IEEE 754 floating-point drift between consecutive MCP
12
+ * snapshots (e.g. `1.0` → `1.0000000001`).
13
+ *
14
+ * Used in two places:
15
+ * - {@link normalizeStrategyMonitorPositions}: positions with absolute size
16
+ * at or below epsilon are discarded (treated as "no position").
17
+ * - {@link diffStrategyMonitorPositions}: same-key, same-direction positions
18
+ * whose size difference falls within epsilon are treated as unchanged.
19
+ *
20
+ * Default `1e-9` is small enough to suppress float noise without masking
21
+ * real sub-unit size changes on any major perpetual venue.
22
+ */
23
+ export type StrategyMonitorConfig = Static<typeof strategyMonitorConfigSchema>;
24
+ /**
25
+ * Supported position delta categories emitted by the strategy monitor.
26
+ *
27
+ * Assumption:
28
+ * one state transition for one position key maps to exactly one delta type per
29
+ * run. A flipped position does not also emit increased/decreased in the same
30
+ * iteration.
31
+ */
32
+ export type StrategyMonitorDeltaType = "POSITION_OPENED" | "POSITION_CLOSED" | "POSITION_INCREASED" | "POSITION_DECREASED" | "POSITION_FLIPPED";
33
+ /**
34
+ * Canonical in-memory snapshot for one open strategy position.
35
+ *
36
+ * Constraint:
37
+ * position identity is tracked by the composite `(dex, asset)` pair so the
38
+ * same base asset can be monitored independently across multiple venues.
39
+ */
40
+ export interface StrategyMonitorPositionSnapshot {
41
+ key: string;
42
+ asset: string;
43
+ dex: string;
44
+ direction: "LONG" | "SHORT";
45
+ size: number;
46
+ entryPrice: number;
47
+ leverage: number;
48
+ liquidationPrice: number | null;
49
+ unrealizedPnl: number;
50
+ roe: number;
51
+ }
52
+ /**
53
+ * One replay-safe delta between two canonical snapshots of the same position
54
+ * key.
55
+ *
56
+ * `previous` and `current` are both carried so the delta stream can later be
57
+ * replayed without re-fetching clearing house state.
58
+ */
59
+ export interface StrategyMonitorDelta {
60
+ type: StrategyMonitorDeltaType;
61
+ asset: string;
62
+ dex: string;
63
+ positionKey: string;
64
+ previous: StrategyMonitorPositionSnapshot | null;
65
+ current: StrategyMonitorPositionSnapshot | null;
66
+ sizeDelta: number | null;
67
+ }
68
+ /**
69
+ * Persisted scanner-local state for `strategy-monitor`.
70
+ *
71
+ * Only the latest canonical snapshot is stored here. The historical delta
72
+ * series lives in persisted scan results.
73
+ */
74
+ export interface StrategyMonitorState {
75
+ iteration: number;
76
+ lastObservedAt: number;
77
+ currentPositions: Record<string, StrategyMonitorPositionSnapshot>;
78
+ }
79
+ /**
80
+ * Normalizes clearing-house positions into a canonical snapshot keyed by
81
+ * composite `dex:asset` identity.
82
+ *
83
+ * Assumptions and constraints:
84
+ * - empty asset names are ignored
85
+ * - zero-size and near-zero-size rows are ignored
86
+ * - duplicate `(dex, asset)` rows are resolved as "last one wins"
87
+ * - position size is stored as an absolute value; direction is tracked
88
+ * separately
89
+ */
90
+ export declare function normalizeStrategyMonitorPositions(positions: readonly ClearingHousePosition[], sizeChangeEpsilon?: number): Record<string, StrategyMonitorPositionSnapshot>;
91
+ /**
92
+ * Compares two canonical snapshot maps and returns the position deltas needed
93
+ * to move from `previous` to `current`.
94
+ *
95
+ * Precedence:
96
+ * flipped > opened/closed > increased/decreased
97
+ */
98
+ export declare function diffStrategyMonitorPositions(previous: Record<string, StrategyMonitorPositionSnapshot>, current: Record<string, StrategyMonitorPositionSnapshot>, sizeChangeEpsilon?: number): StrategyMonitorDelta[];
99
+ /**
100
+ * Applies one emitted delta to a snapshot map.
101
+ *
102
+ * This is primarily intended for tests and future replay support.
103
+ */
104
+ export declare function applyStrategyMonitorDelta(snapshot: Record<string, StrategyMonitorPositionSnapshot>, delta: StrategyMonitorDelta): Record<string, StrategyMonitorPositionSnapshot>;
105
+ /**
106
+ * Creates the strategy-monitor scanner.
107
+ *
108
+ * Behavior:
109
+ * - reads the latest clearing-house snapshot for the registered strategy wallet
110
+ * - diffs it against the previously persisted canonical snapshot
111
+ * - persists the new canonical snapshot
112
+ * - emits one non-actionable signal per detected delta
113
+ */
114
+ export declare function strategyMonitorScanner(): import("../index.js").Scanner<{
115
+ sizeChangeEpsilon?: number | undefined;
116
+ }, StrategyMonitorState>;
117
+ export {};
118
+ //# sourceMappingURL=strategy-monitor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy-monitor.d.ts","sourceRoot":"","sources":["../../../src/scanners/implementations/strategy-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAKtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAEvE,QAAA,MAAM,2BAA2B;;EAE/B,CAAC;AAEH;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC,OAAO,2BAA2B,CAAC,CAAC;AAG/E;;;;;;;GAOG;AACH,MAAM,MAAM,wBAAwB,GAChC,iBAAiB,GACjB,iBAAiB,GACjB,oBAAoB,GACpB,oBAAoB,GACpB,kBAAkB,CAAC;AAEvB;;;;;;GAMG;AACH,MAAM,WAAW,+BAA+B;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,gBAAgB,EAAE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ner.js";
3
+ import { providerInput } from "../input-descriptors.js";
4
+ import { PersistencePolicy, RetentionPolicy } from "../scanner-definition.js";
5
+ const strategyMonitorConfigSchema = Type.Object({
6
+ sizeChangeEpsilon: Type.Optional(Type.Number({ minimum: 0, default: 1e-9 })),
7
+ });
8
+ const DEFAULT_SIZE_CHANGE_EPSILON = 1e-9;
9
+ const directionSchema = Type.Union([
10
+ Type.Literal("LONG"),
11
+ Type.Literal("SHORT"),
12
+ ]);
13
+ const positionSnapshotSchema = Type.Object({
14
+ key: Type.String(),
15
+ asset: Type.String(),
16
+ dex: Type.String(),
17
+ direction: directionSchema,
18
+ size: Type.Number({ minimum: 0 }),
19
+ entryPrice: Type.Number(),
20
+ leverage: Type.Number(),
21
+ liquidationPrice: Type.Union([Type.Number(), Type.Null()]),
22
+ unrealizedPnl: Type.Number(),
23
+ roe: Type.Number(),
24
+ });
25
+ const strategyMonitorStateSchema = Type.Object({
26
+ iteration: Type.Number({ minimum: 0 }),
27
+ lastObservedAt: Type.Number({ minimum: 0 }),
28
+ currentPositions: Type.Record(Type.String(), positionSnapshotSchema),
29
+ });
30
+ const defaultConfig = {
31
+ sizeChangeEpsilon: DEFAULT_SIZE_CHANGE_EPSILON,
32
+ };
33
+ const defaultState = {
34
+ iteration: 0,
35
+ lastObservedAt: 0,
36
+ currentPositions: {},
37
+ };
38
+ /** Resolves optional config values into a fully populated runtime config. */
39
+ function resolveConfig(config) {
40
+ return {
41
+ ...defaultConfig,
42
+ ...Object.fromEntries(Object.entries(config).filter(([, value]) => value !== undefined)),
43
+ };
44
+ }
45
+ /** Small guard used when normalizing provider payloads. */
46
+ function isFiniteNumber(value) {
47
+ return Number.isFinite(value);
48
+ }
49
+ function resolveDirection(size) {
50
+ return size >= 0 ? "LONG" : "SHORT";
51
+ }
52
+ function normalizeRoe(returnOnEquity) {
53
+ return returnOnEquity * 100;
54
+ }
55
+ /** Produces the stable composite identity used for scanner state and replay. */
56
+ function buildPositionKey(asset, dex) {
57
+ const normalizedDex = dex.trim() || "main";
58
+ return `${normalizedDex}:${asset}`;
59
+ }
60
+ /** Returns a shallow copy of one canonical position snapshot. */
61
+ function cloneSnapshot(snapshot) {
62
+ return { ...snapshot };
63
+ }
64
+ /** Returns a cloned snapshot map so callers can update state immutably. */
65
+ function cloneSnapshotMap(snapshots) {
66
+ return Object.fromEntries(Object.entries(snapshots).map(([key, snapshot]) => [key, cloneSnapshot(snapshot)]));
67
+ }
68
+ /**
69
+ * Normalizes clearing-house positions into a canonical snapshot keyed by
70
+ * composite `dex:asset` identity.
71
+ *
72
+ * Assumptions and constraints:
73
+ * - empty asset names are ignored
74
+ * - zero-size and near-zero-size rows are ignored
75
+ * - duplicate `(dex, asset)` rows are resolved as "last one wins"
76
+ * - position size is stored as an absolute value; direction is tracked
77
+ * separately
78
+ */
79
+ export function normalizeStrategyMonitorPositions(positions, sizeChangeEpsilon = DEFAULT_SIZE_CHANGE_EPSILON) {
80
+ const normalized = {};
81
+ for (const position of positions) {
82
+ const asset = position.coin.trim();
83
+ if (!asset) {
84
+ continue;
85
+ }
86
+ const dex = position.dex.trim() || "main";
87
+ // Discard near-zero positions: sizes at or below epsilon are treated as
88
+ // "no position" to avoid ghost entries from float noise.
89
+ const absoluteSize = Math.abs(position.szi);
90
+ if (!isFiniteNumber(absoluteSize) || absoluteSize <= sizeChangeEpsilon) {
91
+ continue;
92
+ }
93
+ const key = buildPositionKey(asset, dex);
94
+ normalized[key] = {
95
+ key,
96
+ asset,
97
+ dex,
98
+ direction: resolveDirection(position.szi),
99
+ size: absoluteSize,
100
+ entryPrice: position.entryPx,
101
+ leverage: position.leverage,
102
+ liquidationPrice: position.liquidationPx,
103
+ unrealizedPnl: position.unrealizedPnl,
104
+ roe: normalizeRoe(position.returnOnEquity),
105
+ };
106
+ }
107
+ return normalized;
108
+ }
109
+ /** Computes the signed size difference represented by one delta. */
110
+ function computeDeltaSize(previous, current) {
111
+ if (previous && current) {
112
+ return current.size - previous.size;
113
+ }
114
+ if (current) {
115
+ return current.size;
116
+ }
117
+ if (previous) {
118
+ return -previous.size;
119
+ }
120
+ return null;
121
+ }
122
+ /** Returns whichever snapshot is available so asset/key metadata can be derived once. */
123
+ function resolveDeltaSnapshot(previous, current) {
124
+ const snapshot = current ?? previous;
125
+ if (!snapshot) {
126
+ throw new Error("Strategy monitor delta requires previous or current snapshot.");
127
+ }
128
+ return snapshot;
129
+ }
130
+ /**
131
+ * Builds one replay-safe delta payload from the compared snapshots.
132
+ *
133
+ * This helper centralizes cloning and size-delta computation so the diff logic
134
+ * can stay focused on classification.
135
+ */
136
+ function buildDelta(type, previous, current) {
137
+ const snapshot = resolveDeltaSnapshot(previous, current);
138
+ return {
139
+ type,
140
+ asset: snapshot.asset,
141
+ dex: snapshot.dex,
142
+ positionKey: snapshot.key,
143
+ previous: previous ? cloneSnapshot(previous) : null,
144
+ current: current ? cloneSnapshot(current) : null,
145
+ sizeDelta: computeDeltaSize(previous, current),
146
+ };
147
+ }
148
+ /** Produces a stable key list so delta ordering stays deterministic across runs and tests. */
149
+ function collectComparableKeys(previous, current) {
150
+ return [...new Set([...Object.keys(previous), ...Object.keys(current)])].sort();
151
+ }
152
+ /**
153
+ * Compares two canonical snapshot maps and returns the position deltas needed
154
+ * to move from `previous` to `current`.
155
+ *
156
+ * Precedence:
157
+ * flipped > opened/closed > increased/decreased
158
+ */
159
+ export function diffStrategyMonitorPositions(previous, current, sizeChangeEpsilon = DEFAULT_SIZE_CHANGE_EPSILON) {
160
+ const keys = collectComparableKeys(previous, current);
161
+ const deltas = [];
162
+ for (const key of keys) {
163
+ const previousPosition = previous[key] ?? null;
164
+ const currentPosition = current[key] ?? null;
165
+ if (!previousPosition && currentPosition) {
166
+ deltas.push(buildDelta("POSITION_OPENED", null, currentPosition));
167
+ continue;
168
+ }
169
+ if (previousPosition && !currentPosition) {
170
+ deltas.push(buildDelta("POSITION_CLOSED", previousPosition, null));
171
+ continue;
172
+ }
173
+ if (!previousPosition || !currentPosition) {
174
+ continue;
175
+ }
176
+ if (previousPosition.direction !== currentPosition.direction) {
177
+ deltas.push(buildDelta("POSITION_FLIPPED", previousPosition, currentPosition));
178
+ continue;
179
+ }
180
+ // Only emit size-change deltas when the difference exceeds epsilon,
181
+ // suppressing false positives from floating-point drift between runs.
182
+ const sizeDelta = currentPosition.size - previousPosition.size;
183
+ if (sizeDelta > sizeChangeEpsilon) {
184
+ deltas.push(buildDelta("POSITION_INCREASED", previousPosition, currentPosition));
185
+ continue;
186
+ }
187
+ if (sizeDelta < -sizeChangeEpsilon) {
188
+ deltas.push(buildDelta("POSITION_DECREASED", previousPosition, currentPosition));
189
+ }
190
+ }
191
+ return deltas;
192
+ }
193
+ /**
194
+ * Applies one emitted delta to a snapshot map.
195
+ *
196
+ * This is primarily intended for tests and future replay support.
197
+ */
198
+ export function applyStrategyMonitorDelta(snapshot, delta) {
199
+ const next = cloneSnapshotMap(snapshot);
200
+ if (delta.type === "POSITION_CLOSED") {
201
+ delete next[delta.positionKey];
202
+ return next;
203
+ }
204
+ if (!delta.current) {
205
+ throw new Error(`Strategy monitor delta '${delta.type}' is missing current snapshot.`);
206
+ }
207
+ next[delta.positionKey] = cloneSnapshot(delta.current);
208
+ return next;
209
+ }
210
+ /** Maps one delta type into explainable boolean factors for the emitted signal. */
211
+ function deltaFactors(type) {
212
+ return {
213
+ opened: type === "POSITION_OPENED",
214
+ closed: type === "POSITION_CLOSED",
215
+ increased: type === "POSITION_INCREASED",
216
+ decreased: type === "POSITION_DECREASED",
217
+ flipped: type === "POSITION_FLIPPED",
218
+ };
219
+ }
220
+ /** Chooses the most relevant direction to expose on the emitted delta signal. */
221
+ function deltaDirection(delta) {
222
+ return delta.current?.direction ?? delta.previous?.direction ?? null;
223
+ }
224
+ /** Converts one internal delta payload into the normalized scanner signal shape. */
225
+ function deltaToSignal(delta, params) {
226
+ return {
227
+ address: params.address,
228
+ scannerId: params.scannerId,
229
+ signalType: delta.type,
230
+ asset: delta.asset,
231
+ direction: deltaDirection(delta),
232
+ score: 1,
233
+ timestamp: params.timestamp,
234
+ factors: deltaFactors(delta.type),
235
+ meta: {
236
+ iteration: params.iteration,
237
+ dex: delta.dex,
238
+ positionKey: delta.positionKey,
239
+ previous: delta.previous,
240
+ current: delta.current,
241
+ sizeDelta: delta.sizeDelta,
242
+ },
243
+ };
244
+ }
245
+ /** Summarizes delta counts by type for the run result metadata. */
246
+ function summarizeDeltas(deltas) {
247
+ const summary = {
248
+ opened: 0,
249
+ closed: 0,
250
+ increased: 0,
251
+ decreased: 0,
252
+ flipped: 0,
253
+ };
254
+ for (const delta of deltas) {
255
+ switch (delta.type) {
256
+ case "POSITION_OPENED":
257
+ summary.opened += 1;
258
+ break;
259
+ case "POSITION_CLOSED":
260
+ summary.closed += 1;
261
+ break;
262
+ case "POSITION_INCREASED":
263
+ summary.increased += 1;
264
+ break;
265
+ case "POSITION_DECREASED":
266
+ summary.decreased += 1;
267
+ break;
268
+ case "POSITION_FLIPPED":
269
+ summary.flipped += 1;
270
+ break;
271
+ }
272
+ }
273
+ return summary;
274
+ }
275
+ /**
276
+ * Creates the strategy-monitor scanner.
277
+ *
278
+ * Behavior:
279
+ * - reads the latest clearing-house snapshot for the registered strategy wallet
280
+ * - diffs it against the previously persisted canonical snapshot
281
+ * - persists the new canonical snapshot
282
+ * - emits one non-actionable signal per detected delta
283
+ */
284
+ export function strategyMonitorScanner() {
285
+ return createScanner({
286
+ id: "strategy-monitor",
287
+ signalType: "STRATEGY_MONITOR",
288
+ outputs: {
289
+ signals: true,
290
+ context: false,
291
+ },
292
+ description: "Tracks strategy position-state deltas from clearing house snapshots.",
293
+ intervalSeconds: 60,
294
+ retention: RetentionPolicy.ROLLING_WINDOW,
295
+ retentionMaxRuns: 200,
296
+ persistence: PersistencePolicy.ALWAYS,
297
+ inputs: [providerInput.clearingHouseState()],
298
+ configSchema: strategyMonitorConfigSchema,
299
+ defaultConfig,
300
+ stateSchema: strategyMonitorStateSchema,
301
+ defaultState,
302
+ hooks: {
303
+ isActionable: () => false,
304
+ },
305
+ scan: async (ctx) => {
306
+ const now = ctx.now();
307
+ const config = resolveConfig(ctx.config);
308
+ const clearingHouseState = ctx.inputs.clearingHouseState;
309
+ if (!clearingHouseState) {
310
+ throw new Error("Strategy monitor requires clearing house state.");
311
+ }
312
+ const currentPositions = normalizeStrategyMonitorPositions(clearingHouseState.positions, config.sizeChangeEpsilon);
313
+ const previousPositions = ctx.state.currentPositions ?? {};
314
+ const deltas = diffStrategyMonitorPositions(previousPositions, currentPositions, config.sizeChangeEpsilon);
315
+ const nextState = {
316
+ iteration: ctx.state.iteration + 1,
317
+ lastObservedAt: now,
318
+ currentPositions: cloneSnapshotMap(currentPositions),
319
+ };
320
+ await ctx.setState(nextState);
321
+ const deltaSummary = summarizeDeltas(deltas);
322
+ return {
323
+ timestamp: now,
324
+ scannedCount: Object.keys(currentPositions).length,
325
+ signals: deltas.map((delta) => deltaToSignal(delta, {
326
+ address: ctx.address,
327
+ scannerId: ctx.scannerId,
328
+ iteration: nextState.iteration,
329
+ timestamp: now,
330
+ })),
331
+ summary: {
332
+ iteration: nextState.iteration,
333
+ positionCount: Object.keys(currentPositions).length,
334
+ deltaCount: deltas.length,
335
+ ...deltaSummary,
336
+ },
337
+ };
338
+ },
339
+ });
340
+ }
341
+ //# sourceMappingURL=strategy-monitor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy-monitor.js","sourceRoot":"","sources":["../../../src/scanners/implementations/strategy-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAe,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAI9E,MAAM,2BAA2B,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9C,iBAAiB,EAAE,IAAI,CAAC,QAAQ,CAA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K,CAAC,gBAAgB,IAAI,EAAE,CAAC;YAC3D,MAAM,MAAM,GAAG,4BAA4B,CACzC,iBAAiB,EACjB,gBAAgB,EAChB,MAAM,CAAC,iBAAiB,CACzB,CAAC;YAEF,MAAM,SAAS,GAAyB;gBACtC,SAAS,EAAE,GAAG,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC;gBAClC,cAAc,EAAE,GAAG;gBACnB,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB,CAAC;aACrD,CAAC;YACF,MAAM,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;YAE9B,MAAM,YAAY,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;YAE7C,OAAO;gBACL,SAAS,EAAE,GAAG;gBACd,YAAY,EAAE,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,MAAM;gBAClD,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAC5B,aAAa,CAAC,KAAK,EAAE;oBACnB,OAAO,EAAE,GAAG,CAAC,OAAO;oBACpB,SAAS,EAAE,GAAG,CAAC,SAAS;oBACxB,SAAS,EAAE,SAAS,CAAC,SAAS;oBAC9B,SAAS,EAAE,GAAG;iBACf,CAAC,CACH;gBACD,OAAO,EAAE;oBACP,SAAS,EAAE,SAAS,CAAC,SAAS;oBAC9B,aAAa,EAAE,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,MAAM;oBACnD,UAAU,EAAE,MAAM,CAAC,MAAM;oBACzB,GAAG,YAAY;iBAChB;aACF,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -20,6 +20,7 @@ export { prescreenerScanner } from "./implementations/prescreener.js";
20
20
  export { marketRegimeScanner } from "./implementations/market-regime.js";
21
21
  export { smFlipScanner } from "./implementations/sm-flip.js";
22
22
  export { opportunityScanner } from "./implementations/opportunity.js";
23
+ export { strategyMonitorScanner, type StrategyMonitorConfig, type StrategyMonitorDelta, type StrategyMonitorDeltaType, type StrategyMonitorPositionSnapshot, type StrategyMonitorState, } from "./implementations/strategy-monitor.js";
23
24
  export { liquidationWatchdogScanner, type ClearingHouseState, type ClearingHousePosition, type WatchdogConfig, type WatchdogAlert, } from "./implementations/liquidation-watchdog.js";
24
25
  export { marketRegimeArtifact, MarketRegime, type MarketRegimeArtifact, } from "./artifacts.js";
25
26
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scanners/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,GAC1B,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,EAC1B,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,KAAK,2BAA2B,GACjC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EACL,aAAa,EACb,KAAK,8BAA8B,EACnC,KAAK,sBAAsB,EAC3B,KAAK,0BAA0B,EAC/B,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,iCAAiC,EACtC,KAAK,wBAAwB,GAC9B,MAAM,wBAAwB,CAAC;AAEhC,YAAY,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AACvE,YAAY,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AACrE,YAAY,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,YAAY,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EACL,i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,OAAO,EACL,sBAAsB,EACtB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,EAC7B,KAAK,+BAA+B,EACpC,KAAK,oBAAoB,GAC1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,0BAA0B,EAC1B,KAAK,kBAAkB,EACvB,KAAK,qBAAqB,EAC1B,KAAK,cAAc,EACnB,KAAK,aAAa,GACnB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,KAAK,oBAAoB,GAC1B,MAAM,gBAAgB,CAAC"}
@@ -13,6 +13,7 @@ export { prescreenerScanner } from "./implementations/prescreener.js";
13
13
  export { marketRegimeScanner } from "./implementations/market-regime.js";
14
14
  export { smFlipScanner } from "./implementations/sm-flip.js";
15
15
  export { opportunityScanner } from "./implementations/opportunity.js";
16
+ export { strategyMonitorScanner, } from "./implementations/strategy-monitor.js";
16
17
  export { liquidationWatchdogScanner, } from "./implementations/liquidation-watchdog.js";
17
18
  export { marketRegimeArtifact, MarketRegime, } from "./artifacts.js";
18
19
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/scanners/index.ts"],"names":[],"mappings":"AASA,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAK3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,aAAa,EAA6B,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EACL,aAAa,GASd,MAAM,wBAAwB,CAAC;AAMhC,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EACL,iBAAiB,EACjB,eAAe,GAEhB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EACjB,mBAAmB,GAUpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAML,UAAU,GAKX,MAAM,YAAY,CAAC;AAQpB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,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,UAAU,CAAC,EAAE,uBAAuB,CAAC;IACrC,QAAQ,CAAC,EAAE,qBAAqB,CAAC;IACjC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,sBAAsB,CAAC;CACpC;AAED,yEAAyE;AACzE,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,kCAAkC,GAC1C,oBAAoB,CAkJtB"}
@@ -1,3 +1,4 @@
1
+ import { asNumber, asString, isRecord } from "../../utils/response.js";
1
2
  import { normalizeAssetCandles, normalizeInstrumentsWithDiagnostics, normalizeSmMarketsWithDiagnostics, } from "./adapter.js";
2
3
  import { createConsoleProviderLogger, createProviderClient, createWinstonProviderLogger, } from "./client.js";
3
4
  import { ProviderCache } from "./cache.js";
@@ -146,30 +147,71 @@ function dedupeAssets(assets) {
146
147
  function cacheKey(prefix, ...parts) {
147
148
  return `${prefix}:${parts.join(":")}`;
148
149
  }
149
- /** Normalizes raw clearinghouse state payload from MCP into typed ClearingHouseState. */
150
+ /**
151
+ * Normalizes the raw `strategy_get_clearinghouse_state` payload into the same
152
+ * contract used by `StrategyStateImpl`.
153
+ *
154
+ * The MCP response is expected to be keyed by venue, for example:
155
+ * `{ main: { crossMarginSummary, withdrawable, assetPositions }, xyz: { ... } }`.
156
+ */
150
157
  function normalizeClearingHouseState(raw) {
151
158
  const data = (raw && typeof raw === "object" ? raw : {});
152
- const positions = Array.isArray(data.positions)
153
- ? data.positions.map((p) => ({
154
- asset: String(p.asset ?? ""),
155
- direction: String(p.direction ?? "LONG").toUpperCase() === "SHORT" ? "SHORT" : "LONG",
156
- size: Number(p.size ?? 0),
157
- entryPrice: Number(p.entryPrice ?? p.entry_price ?? 0),
158
- markPrice: Number(p.markPrice ?? p.mark_price ?? 0),
159
- liquidationPrice: p.liquidationPrice != null || p.liquidation_price != null
160
- ? Number(p.liquidationPrice ?? p.liquidation_price)
161
- : null,
162
- unrealizedPnl: Number(p.unrealizedPnl ?? p.unrealized_pnl ?? 0),
163
- roe: Number(p.roe ?? 0),
164
- leverage: Number(p.leverage ?? 1),
165
- marginType: String(p.marginType ?? p.margin_type ?? "cross") === "isolated" ? "isolated" : "cross",
166
- }))
167
- : [];
159
+ let accountValue = 0;
160
+ let totalMarginUsed = 0;
161
+ let totalUnrealizedPnl = 0;
162
+ let totalNtlPos = 0;
163
+ let withdrawable = 0;
164
+ const positions = [];
165
+ for (const [dexKey, dexValue] of Object.entries(data)) {
166
+ if (!isRecord(dexValue)) {
167
+ continue;
168
+ }
169
+ const summary = dexValue.crossMarginSummary;
170
+ if (isRecord(summary)) {
171
+ accountValue += asNumber(summary.accountValue) ?? 0;
172
+ totalMarginUsed += asNumber(summary.totalMarginUsed) ?? 0;
173
+ totalUnrealizedPnl += asNumber(summary.totalUnrealizedPnl) ?? 0;
174
+ totalNtlPos += asNumber(summary.totalNtlPos) ?? 0;
175
+ }
176
+ withdrawable += asNumber(dexValue.withdrawable) ?? 0;
177
+ const assetPositions = dexValue.assetPositions;
178
+ if (!Array.isArray(assetPositions)) {
179
+ continue;
180
+ }
181
+ for (const item of assetPositions) {
182
+ if (!isRecord(item)) {
183
+ continue;
184
+ }
185
+ const positionRecord = isRecord(item.position)
186
+ ? item.position
187
+ : item;
188
+ const szi = asNumber(positionRecord.szi) ?? 0;
189
+ if (szi === 0) {
190
+ continue;
191
+ }
192
+ let leverage = asNumber(positionRecord.leverage);
193
+ if (leverage == null && isRecord(positionRecord.leverage)) {
194
+ leverage = asNumber(positionRecord.leverage.value);
195
+ }
196
+ positions.push({
197
+ coin: asString(positionRecord.coin) ?? "",
198
+ dex: dexKey,
199
+ szi,
200
+ entryPx: asNumber(positionRecord.entryPx) ?? 0,
201
+ leverage: leverage ?? 0,
202
+ unrealizedPnl: asNumber(positionRecord.unrealizedPnl) ?? 0,
203
+ marginUsed: asNumber(positionRecord.marginUsed) ?? 0,
204
+ liquidationPx: asNumber(positionRecord.liquidationPx) ?? null,
205
+ returnOnEquity: asNumber(positionRecord.returnOnEquity) ?? 0,
206
+ });
207
+ }
208
+ }
168
209
  return {
169
- accountValue: Number(data.accountValue ?? data.account_value ?? 0),
170
- totalMarginUsed: Number(data.totalMarginUsed ?? data.total_margin_used ?? 0),
171
- crossMaintenanceMargin: Number(data.crossMaintenanceMargin ?? data.cross_maintenance_margin ?? 0),
172
- availableBalance: Number(data.availableBalance ?? data.available_balance ?? 0),
210
+ accountValue,
211
+ totalMarginUsed,
212
+ totalUnrealizedPnl,
213
+ totalNtlPos,
214
+ withdrawable,
173
215
  positions,
174
216
  };
175
217
  }