@openfinclaw/fin-strategy-engine 0.0.1
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/LICENSE +21 -0
- package/index.test.ts +269 -0
- package/index.ts +578 -0
- package/openclaw.plugin.json +11 -0
- package/package.json +40 -0
- package/src/backtest-engine.live.test.ts +313 -0
- package/src/backtest-engine.test.ts +368 -0
- package/src/backtest-engine.ts +362 -0
- package/src/builtin-strategies/bollinger-bands.test.ts +96 -0
- package/src/builtin-strategies/bollinger-bands.ts +75 -0
- package/src/builtin-strategies/custom-rule-engine.ts +274 -0
- package/src/builtin-strategies/macd-divergence.test.ts +122 -0
- package/src/builtin-strategies/macd-divergence.ts +77 -0
- package/src/builtin-strategies/multi-timeframe-confluence.test.ts +287 -0
- package/src/builtin-strategies/multi-timeframe-confluence.ts +253 -0
- package/src/builtin-strategies/regime-adaptive.test.ts +210 -0
- package/src/builtin-strategies/regime-adaptive.ts +285 -0
- package/src/builtin-strategies/risk-parity-triple-screen.test.ts +295 -0
- package/src/builtin-strategies/risk-parity-triple-screen.ts +295 -0
- package/src/builtin-strategies/rsi-mean-reversion.test.ts +143 -0
- package/src/builtin-strategies/rsi-mean-reversion.ts +74 -0
- package/src/builtin-strategies/sma-crossover.test.ts +113 -0
- package/src/builtin-strategies/sma-crossover.ts +85 -0
- package/src/builtin-strategies/trend-following-momentum.test.ts +228 -0
- package/src/builtin-strategies/trend-following-momentum.ts +209 -0
- package/src/builtin-strategies/volatility-mean-reversion.test.ts +193 -0
- package/src/builtin-strategies/volatility-mean-reversion.ts +212 -0
- package/src/composite-pipeline.live.test.ts +347 -0
- package/src/e2e-pipeline.test.ts +494 -0
- package/src/fitness.test.ts +103 -0
- package/src/fitness.ts +61 -0
- package/src/full-pipeline.live.test.ts +339 -0
- package/src/indicators.test.ts +224 -0
- package/src/indicators.ts +238 -0
- package/src/stats.test.ts +215 -0
- package/src/stats.ts +115 -0
- package/src/strategy-registry.test.ts +235 -0
- package/src/strategy-registry.ts +183 -0
- package/src/types.ts +19 -0
- package/src/walk-forward.test.ts +185 -0
- package/src/walk-forward.ts +114 -0
package/index.ts
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { OpenClawPluginApi } from "openfinclaw/plugin-sdk";
|
|
5
|
+
import { BacktestEngine, buildIndicatorLib } from "./src/backtest-engine.js";
|
|
6
|
+
import { createBollingerBands } from "./src/builtin-strategies/bollinger-bands.js";
|
|
7
|
+
import { buildCustomStrategy } from "./src/builtin-strategies/custom-rule-engine.js";
|
|
8
|
+
import { createMacdDivergence } from "./src/builtin-strategies/macd-divergence.js";
|
|
9
|
+
import { createMultiTimeframeConfluence } from "./src/builtin-strategies/multi-timeframe-confluence.js";
|
|
10
|
+
import { createRegimeAdaptive } from "./src/builtin-strategies/regime-adaptive.js";
|
|
11
|
+
import { createRiskParityTripleScreen } from "./src/builtin-strategies/risk-parity-triple-screen.js";
|
|
12
|
+
import { createRsiMeanReversion } from "./src/builtin-strategies/rsi-mean-reversion.js";
|
|
13
|
+
import { createSmaCrossover } from "./src/builtin-strategies/sma-crossover.js";
|
|
14
|
+
import { createTrendFollowingMomentum } from "./src/builtin-strategies/trend-following-momentum.js";
|
|
15
|
+
import { createVolatilityMeanReversion } from "./src/builtin-strategies/volatility-mean-reversion.js";
|
|
16
|
+
import { StrategyRegistry } from "./src/strategy-registry.js";
|
|
17
|
+
import type { BacktestConfig, StrategyContext, StrategyDefinition } from "./src/types.js";
|
|
18
|
+
|
|
19
|
+
type OhlcvBar = {
|
|
20
|
+
timestamp: number;
|
|
21
|
+
open: number;
|
|
22
|
+
high: number;
|
|
23
|
+
low: number;
|
|
24
|
+
close: number;
|
|
25
|
+
volume: number;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const json = (payload: unknown) => ({
|
|
29
|
+
content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
|
|
30
|
+
details: payload,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const plugin = {
|
|
34
|
+
id: "fin-strategy-engine",
|
|
35
|
+
name: "Strategy Engine",
|
|
36
|
+
description: "Strategy lifecycle: indicators, backtest, walk-forward, evolution",
|
|
37
|
+
kind: "financial" as const,
|
|
38
|
+
register(api: OpenClawPluginApi) {
|
|
39
|
+
const registryPath = join(homedir(), ".openfinclaw", "strategy", "fin-strategies.json");
|
|
40
|
+
const registry = new StrategyRegistry(registryPath);
|
|
41
|
+
const engine = new BacktestEngine();
|
|
42
|
+
|
|
43
|
+
// Register services
|
|
44
|
+
api.registerService({
|
|
45
|
+
id: "fin-strategy-registry",
|
|
46
|
+
start: () => {},
|
|
47
|
+
instance: registry,
|
|
48
|
+
} as Parameters<typeof api.registerService>[0]);
|
|
49
|
+
|
|
50
|
+
api.registerService({
|
|
51
|
+
id: "fin-backtest-engine",
|
|
52
|
+
start: () => {},
|
|
53
|
+
instance: engine,
|
|
54
|
+
} as Parameters<typeof api.registerService>[0]);
|
|
55
|
+
|
|
56
|
+
// --- fin_strategy_create ---
|
|
57
|
+
api.registerTool(
|
|
58
|
+
{
|
|
59
|
+
name: "fin_strategy_create",
|
|
60
|
+
label: "Create Strategy",
|
|
61
|
+
description: "Create a new trading strategy from a built-in template or custom definition",
|
|
62
|
+
parameters: Type.Object({
|
|
63
|
+
name: Type.String({ description: "Strategy display name" }),
|
|
64
|
+
type: Type.Unsafe<
|
|
65
|
+
| "sma-crossover"
|
|
66
|
+
| "rsi-mean-reversion"
|
|
67
|
+
| "bollinger-bands"
|
|
68
|
+
| "macd-divergence"
|
|
69
|
+
| "trend-following-momentum"
|
|
70
|
+
| "volatility-mean-reversion"
|
|
71
|
+
| "regime-adaptive"
|
|
72
|
+
| "multi-timeframe-confluence"
|
|
73
|
+
| "risk-parity-triple-screen"
|
|
74
|
+
| "custom"
|
|
75
|
+
>({
|
|
76
|
+
type: "string",
|
|
77
|
+
enum: [
|
|
78
|
+
"sma-crossover",
|
|
79
|
+
"rsi-mean-reversion",
|
|
80
|
+
"bollinger-bands",
|
|
81
|
+
"macd-divergence",
|
|
82
|
+
"trend-following-momentum",
|
|
83
|
+
"volatility-mean-reversion",
|
|
84
|
+
"regime-adaptive",
|
|
85
|
+
"multi-timeframe-confluence",
|
|
86
|
+
"risk-parity-triple-screen",
|
|
87
|
+
"custom",
|
|
88
|
+
],
|
|
89
|
+
description: "Strategy template type",
|
|
90
|
+
}),
|
|
91
|
+
parameters: Type.Optional(
|
|
92
|
+
Type.Object(
|
|
93
|
+
{},
|
|
94
|
+
{
|
|
95
|
+
additionalProperties: true,
|
|
96
|
+
description: "Strategy parameters (e.g. fastPeriod, slowPeriod)",
|
|
97
|
+
},
|
|
98
|
+
),
|
|
99
|
+
),
|
|
100
|
+
symbols: Type.Optional(
|
|
101
|
+
Type.Array(Type.String(), { description: "Trading pair symbols (e.g. BTC/USDT)" }),
|
|
102
|
+
),
|
|
103
|
+
timeframes: Type.Optional(
|
|
104
|
+
Type.Array(Type.String(), { description: "Timeframes (e.g. 1d, 4h)" }),
|
|
105
|
+
),
|
|
106
|
+
rules: Type.Optional(
|
|
107
|
+
Type.Object(
|
|
108
|
+
{
|
|
109
|
+
buy: Type.String({
|
|
110
|
+
description: "Buy rule expression (e.g. 'rsi < 30 AND close > sma')",
|
|
111
|
+
}),
|
|
112
|
+
sell: Type.String({
|
|
113
|
+
description: "Sell rule expression (e.g. 'rsi > 70 OR close < sma')",
|
|
114
|
+
}),
|
|
115
|
+
},
|
|
116
|
+
{ description: "Custom strategy rules (required when type=custom)" },
|
|
117
|
+
),
|
|
118
|
+
),
|
|
119
|
+
customParams: Type.Optional(
|
|
120
|
+
Type.Object(
|
|
121
|
+
{},
|
|
122
|
+
{
|
|
123
|
+
additionalProperties: true,
|
|
124
|
+
description: "Custom strategy parameters (e.g. rsiPeriod, smaPeriod)",
|
|
125
|
+
},
|
|
126
|
+
),
|
|
127
|
+
),
|
|
128
|
+
}),
|
|
129
|
+
async execute(_id: string, params: Record<string, unknown>) {
|
|
130
|
+
try {
|
|
131
|
+
const name = params.name as string;
|
|
132
|
+
const type = params.type as string;
|
|
133
|
+
const stratParams = (params.parameters ?? {}) as Record<string, number>;
|
|
134
|
+
const symbols = (params.symbols as string[] | undefined) ?? ["BTC/USDT"];
|
|
135
|
+
const timeframes = (params.timeframes as string[] | undefined) ?? ["1d"];
|
|
136
|
+
|
|
137
|
+
let definition: StrategyDefinition;
|
|
138
|
+
|
|
139
|
+
if (type === "sma-crossover") {
|
|
140
|
+
definition = createSmaCrossover(stratParams);
|
|
141
|
+
} else if (type === "rsi-mean-reversion") {
|
|
142
|
+
definition = createRsiMeanReversion(stratParams);
|
|
143
|
+
} else if (type === "bollinger-bands") {
|
|
144
|
+
definition = createBollingerBands(stratParams);
|
|
145
|
+
} else if (type === "macd-divergence") {
|
|
146
|
+
definition = createMacdDivergence(stratParams);
|
|
147
|
+
} else if (type === "trend-following-momentum") {
|
|
148
|
+
definition = createTrendFollowingMomentum(stratParams);
|
|
149
|
+
} else if (type === "volatility-mean-reversion") {
|
|
150
|
+
definition = createVolatilityMeanReversion(stratParams);
|
|
151
|
+
} else if (type === "regime-adaptive") {
|
|
152
|
+
definition = createRegimeAdaptive(stratParams);
|
|
153
|
+
} else if (type === "multi-timeframe-confluence") {
|
|
154
|
+
definition = createMultiTimeframeConfluence(stratParams);
|
|
155
|
+
} else if (type === "risk-parity-triple-screen") {
|
|
156
|
+
definition = createRiskParityTripleScreen(stratParams);
|
|
157
|
+
} else if (type === "custom") {
|
|
158
|
+
const rules = params.rules as { buy: string; sell: string } | undefined;
|
|
159
|
+
if (!rules?.buy || !rules?.sell) {
|
|
160
|
+
return json({
|
|
161
|
+
error: "Custom strategies require 'rules' with 'buy' and 'sell' expressions",
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
const rawParams = (params.customParams ?? stratParams) as Record<string, unknown>;
|
|
165
|
+
// Validate all custom params are numeric
|
|
166
|
+
const customParams: Record<string, number> = {};
|
|
167
|
+
for (const [k, v] of Object.entries(rawParams)) {
|
|
168
|
+
const num = Number(v);
|
|
169
|
+
if (Number.isNaN(num)) {
|
|
170
|
+
return json({
|
|
171
|
+
error: `Custom parameter "${k}" must be numeric, got: ${typeof v}`,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
customParams[k] = num;
|
|
175
|
+
}
|
|
176
|
+
definition = buildCustomStrategy(name, rules, customParams, symbols, timeframes);
|
|
177
|
+
} else {
|
|
178
|
+
return json({ error: `Unknown strategy type: ${type}` });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Override metadata
|
|
182
|
+
definition.id = `${type}-${Date.now()}`;
|
|
183
|
+
definition.name = name;
|
|
184
|
+
definition.symbols = symbols;
|
|
185
|
+
definition.timeframes = timeframes;
|
|
186
|
+
|
|
187
|
+
const record = registry.create(definition);
|
|
188
|
+
|
|
189
|
+
return json({
|
|
190
|
+
created: true,
|
|
191
|
+
id: record.id,
|
|
192
|
+
name: record.name,
|
|
193
|
+
level: record.level,
|
|
194
|
+
parameters: definition.parameters,
|
|
195
|
+
});
|
|
196
|
+
} catch (err) {
|
|
197
|
+
return json({ error: err instanceof Error ? err.message : String(err) });
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
{ names: ["fin_strategy_create"] },
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
// --- fin_strategy_list ---
|
|
205
|
+
api.registerTool(
|
|
206
|
+
{
|
|
207
|
+
name: "fin_strategy_list",
|
|
208
|
+
label: "List Strategies",
|
|
209
|
+
description: "List registered trading strategies with their status and metrics",
|
|
210
|
+
parameters: Type.Object({
|
|
211
|
+
level: Type.Optional(
|
|
212
|
+
Type.Unsafe<"L0_INCUBATE" | "L1_BACKTEST" | "L2_PAPER" | "L3_LIVE" | "KILLED">({
|
|
213
|
+
type: "string",
|
|
214
|
+
enum: ["L0_INCUBATE", "L1_BACKTEST", "L2_PAPER", "L3_LIVE", "KILLED"],
|
|
215
|
+
description: "Filter by strategy level",
|
|
216
|
+
}),
|
|
217
|
+
),
|
|
218
|
+
}),
|
|
219
|
+
async execute(_id: string, params: Record<string, unknown>) {
|
|
220
|
+
try {
|
|
221
|
+
const level = params.level as string | undefined;
|
|
222
|
+
const strategies = registry.list(level ? { level: level as "L0_INCUBATE" } : undefined);
|
|
223
|
+
|
|
224
|
+
const summary = strategies.map((s) => ({
|
|
225
|
+
id: s.id,
|
|
226
|
+
name: s.name,
|
|
227
|
+
level: s.level,
|
|
228
|
+
version: s.version,
|
|
229
|
+
lastBacktest: s.lastBacktest
|
|
230
|
+
? {
|
|
231
|
+
totalReturn: s.lastBacktest.totalReturn,
|
|
232
|
+
sharpe: s.lastBacktest.sharpe,
|
|
233
|
+
maxDrawdown: s.lastBacktest.maxDrawdown,
|
|
234
|
+
totalTrades: s.lastBacktest.totalTrades,
|
|
235
|
+
}
|
|
236
|
+
: null,
|
|
237
|
+
lastWalkForward: s.lastWalkForward
|
|
238
|
+
? { passed: s.lastWalkForward.passed, ratio: s.lastWalkForward.ratio }
|
|
239
|
+
: null,
|
|
240
|
+
updatedAt: new Date(s.updatedAt).toISOString(),
|
|
241
|
+
}));
|
|
242
|
+
|
|
243
|
+
return json({ total: summary.length, strategies: summary });
|
|
244
|
+
} catch (err) {
|
|
245
|
+
return json({ error: err instanceof Error ? err.message : String(err) });
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
{ names: ["fin_strategy_list"] },
|
|
250
|
+
);
|
|
251
|
+
|
|
252
|
+
// --- fin_backtest_run ---
|
|
253
|
+
api.registerTool(
|
|
254
|
+
{
|
|
255
|
+
name: "fin_backtest_run",
|
|
256
|
+
label: "Run Backtest",
|
|
257
|
+
description: "Run a backtest for a registered strategy using historical data",
|
|
258
|
+
parameters: Type.Object({
|
|
259
|
+
strategyId: Type.String({ description: "ID of the strategy to backtest" }),
|
|
260
|
+
capital: Type.Optional(Type.Number({ description: "Initial capital (default 10000)" })),
|
|
261
|
+
commission: Type.Optional(
|
|
262
|
+
Type.Number({ description: "Commission rate as decimal (e.g. 0.001 = 0.1%)" }),
|
|
263
|
+
),
|
|
264
|
+
slippage: Type.Optional(
|
|
265
|
+
Type.Number({ description: "Slippage in basis points (e.g. 5 = 0.05%)" }),
|
|
266
|
+
),
|
|
267
|
+
}),
|
|
268
|
+
async execute(_id: string, params: Record<string, unknown>) {
|
|
269
|
+
try {
|
|
270
|
+
const strategyId = params.strategyId as string;
|
|
271
|
+
const record = registry.get(strategyId);
|
|
272
|
+
if (!record) {
|
|
273
|
+
return json({ error: `Strategy ${strategyId} not found` });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const config: BacktestConfig = {
|
|
277
|
+
capital: (params.capital as number) ?? 10000,
|
|
278
|
+
commissionRate: (params.commission as number) ?? 0.001,
|
|
279
|
+
slippageBps: (params.slippage as number) ?? 5,
|
|
280
|
+
market: record.definition.markets[0] ?? "crypto",
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
// Get data from the data provider service
|
|
284
|
+
const runtime = api.runtime as unknown as { services?: Map<string, unknown> };
|
|
285
|
+
const dataProvider = runtime.services?.get?.("fin-data-provider") as
|
|
286
|
+
| {
|
|
287
|
+
getOHLCV?: (
|
|
288
|
+
paramsOrSymbol:
|
|
289
|
+
| {
|
|
290
|
+
symbol: string;
|
|
291
|
+
market: "crypto" | "equity" | "commodity";
|
|
292
|
+
timeframe: string;
|
|
293
|
+
limit?: number;
|
|
294
|
+
since?: number;
|
|
295
|
+
}
|
|
296
|
+
| string,
|
|
297
|
+
timeframe?: string,
|
|
298
|
+
limit?: number,
|
|
299
|
+
) => Promise<OhlcvBar[]>;
|
|
300
|
+
}
|
|
301
|
+
| undefined;
|
|
302
|
+
|
|
303
|
+
if (!dataProvider?.getOHLCV) {
|
|
304
|
+
return json({
|
|
305
|
+
error: "Data provider not available. Load findoo-datahub-plugin first.",
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const symbol = record.definition.symbols[0] ?? "BTC/USDT";
|
|
310
|
+
const timeframe = record.definition.timeframes[0] ?? "1d";
|
|
311
|
+
const getOHLCV = dataProvider.getOHLCV;
|
|
312
|
+
const ohlcvData =
|
|
313
|
+
getOHLCV.length <= 1
|
|
314
|
+
? await getOHLCV({
|
|
315
|
+
symbol,
|
|
316
|
+
market: config.market,
|
|
317
|
+
timeframe,
|
|
318
|
+
limit: 365,
|
|
319
|
+
})
|
|
320
|
+
: await getOHLCV(symbol, timeframe, 365);
|
|
321
|
+
|
|
322
|
+
const result = await engine.run(record.definition, ohlcvData, config);
|
|
323
|
+
registry.updateBacktest(strategyId, result);
|
|
324
|
+
|
|
325
|
+
return json({
|
|
326
|
+
strategyId,
|
|
327
|
+
totalReturn: `${result.totalReturn.toFixed(2)}%`,
|
|
328
|
+
sharpe: result.sharpe.toFixed(3),
|
|
329
|
+
sortino: result.sortino.toFixed(3),
|
|
330
|
+
maxDrawdown: `${result.maxDrawdown.toFixed(2)}%`,
|
|
331
|
+
winRate: `${result.winRate.toFixed(1)}%`,
|
|
332
|
+
profitFactor: result.profitFactor.toFixed(2),
|
|
333
|
+
totalTrades: result.totalTrades,
|
|
334
|
+
finalEquity: result.finalEquity.toFixed(2),
|
|
335
|
+
});
|
|
336
|
+
} catch (err) {
|
|
337
|
+
return json({ error: err instanceof Error ? err.message : String(err) });
|
|
338
|
+
}
|
|
339
|
+
},
|
|
340
|
+
},
|
|
341
|
+
{ names: ["fin_backtest_run"] },
|
|
342
|
+
);
|
|
343
|
+
|
|
344
|
+
// --- fin_backtest_result ---
|
|
345
|
+
api.registerTool(
|
|
346
|
+
{
|
|
347
|
+
name: "fin_backtest_result",
|
|
348
|
+
label: "Backtest Result",
|
|
349
|
+
description: "Retrieve the last backtest result for a strategy",
|
|
350
|
+
parameters: Type.Object({
|
|
351
|
+
strategyId: Type.String({ description: "ID of the strategy" }),
|
|
352
|
+
}),
|
|
353
|
+
async execute(_id: string, params: Record<string, unknown>) {
|
|
354
|
+
try {
|
|
355
|
+
const strategyId = params.strategyId as string;
|
|
356
|
+
const record = registry.get(strategyId);
|
|
357
|
+
if (!record) {
|
|
358
|
+
return json({ error: `Strategy ${strategyId} not found` });
|
|
359
|
+
}
|
|
360
|
+
if (!record.lastBacktest) {
|
|
361
|
+
return json({ error: `No backtest result for strategy ${strategyId}` });
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const bt = record.lastBacktest;
|
|
365
|
+
return json({
|
|
366
|
+
strategyId,
|
|
367
|
+
totalReturn: bt.totalReturn,
|
|
368
|
+
sharpe: bt.sharpe,
|
|
369
|
+
sortino: bt.sortino,
|
|
370
|
+
maxDrawdown: bt.maxDrawdown,
|
|
371
|
+
calmar: bt.calmar,
|
|
372
|
+
winRate: bt.winRate,
|
|
373
|
+
profitFactor: bt.profitFactor,
|
|
374
|
+
totalTrades: bt.totalTrades,
|
|
375
|
+
initialCapital: bt.initialCapital,
|
|
376
|
+
finalEquity: bt.finalEquity,
|
|
377
|
+
trades: bt.trades.slice(0, 50), // limit output
|
|
378
|
+
});
|
|
379
|
+
} catch (err) {
|
|
380
|
+
return json({ error: err instanceof Error ? err.message : String(err) });
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
},
|
|
384
|
+
{ names: ["fin_backtest_result"] },
|
|
385
|
+
);
|
|
386
|
+
|
|
387
|
+
// --- fin_strategy_tick ---
|
|
388
|
+
// Per-strategy tick memory, persisted across ticks on the record object
|
|
389
|
+
const tickMemory = new Map<string, Map<string, unknown>>();
|
|
390
|
+
|
|
391
|
+
api.registerTool(
|
|
392
|
+
{
|
|
393
|
+
name: "fin_strategy_tick",
|
|
394
|
+
label: "Strategy Tick",
|
|
395
|
+
description:
|
|
396
|
+
"Feed the latest market bar to a running strategy. If a signal fires, " +
|
|
397
|
+
"submit order to paper engine (L2) or live engine (L3) automatically.",
|
|
398
|
+
parameters: Type.Object({
|
|
399
|
+
strategyId: Type.String({ description: "Strategy ID to tick" }),
|
|
400
|
+
symbol: Type.Optional(
|
|
401
|
+
Type.String({ description: "Override symbol (default: strategy's first symbol)" }),
|
|
402
|
+
),
|
|
403
|
+
timeframe: Type.Optional(
|
|
404
|
+
Type.String({ description: "Override timeframe (default: strategy's first)" }),
|
|
405
|
+
),
|
|
406
|
+
}),
|
|
407
|
+
async execute(_id: string, params: Record<string, unknown>) {
|
|
408
|
+
try {
|
|
409
|
+
const strategyId = params.strategyId as string;
|
|
410
|
+
const record = registry.get(strategyId);
|
|
411
|
+
if (!record) return json({ error: `Strategy ${strategyId} not found` });
|
|
412
|
+
if (record.level !== "L2_PAPER" && record.level !== "L3_LIVE") {
|
|
413
|
+
return json({
|
|
414
|
+
error: `Strategy ${strategyId} is ${record.level}, must be L2_PAPER or L3_LIVE to tick`,
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// Get data provider
|
|
419
|
+
const runtime = api.runtime as unknown as { services?: Map<string, unknown> };
|
|
420
|
+
const dataProvider = runtime.services?.get?.("fin-data-provider") as
|
|
421
|
+
| {
|
|
422
|
+
getOHLCV?: (
|
|
423
|
+
paramsOrSymbol:
|
|
424
|
+
| {
|
|
425
|
+
symbol: string;
|
|
426
|
+
market: string;
|
|
427
|
+
timeframe: string;
|
|
428
|
+
limit?: number;
|
|
429
|
+
}
|
|
430
|
+
| string,
|
|
431
|
+
timeframe?: string,
|
|
432
|
+
limit?: number,
|
|
433
|
+
) => Promise<OhlcvBar[]>;
|
|
434
|
+
}
|
|
435
|
+
| undefined;
|
|
436
|
+
|
|
437
|
+
if (!dataProvider?.getOHLCV) {
|
|
438
|
+
return json({ error: "Data provider not available. Load findoo-datahub-plugin." });
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const symbol = (params.symbol as string) ?? record.definition.symbols[0] ?? "BTC/USDT";
|
|
442
|
+
const timeframe =
|
|
443
|
+
(params.timeframe as string) ?? record.definition.timeframes[0] ?? "1h";
|
|
444
|
+
const market = record.definition.markets[0] ?? "crypto";
|
|
445
|
+
|
|
446
|
+
const getOHLCV = dataProvider.getOHLCV;
|
|
447
|
+
const ohlcv =
|
|
448
|
+
getOHLCV.length <= 1
|
|
449
|
+
? await getOHLCV({ symbol, market, timeframe, limit: 200 })
|
|
450
|
+
: await getOHLCV(symbol, timeframe, 200);
|
|
451
|
+
|
|
452
|
+
if (!ohlcv || ohlcv.length === 0) {
|
|
453
|
+
return json({ error: `No OHLCV data for ${symbol} ${timeframe}` });
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const latestBar = ohlcv[ohlcv.length - 1]!;
|
|
457
|
+
const indicators = buildIndicatorLib(ohlcv);
|
|
458
|
+
|
|
459
|
+
// Get paper engine for portfolio state
|
|
460
|
+
const paperEngine = runtime.services?.get?.("fin-paper-engine") as
|
|
461
|
+
| {
|
|
462
|
+
getAccountState?: (id: string) => {
|
|
463
|
+
equity: number;
|
|
464
|
+
cash?: number;
|
|
465
|
+
orders?: Array<{ strategyId?: string }>;
|
|
466
|
+
} | null;
|
|
467
|
+
submitOrder?: (accountId: string, order: unknown, price: number) => unknown;
|
|
468
|
+
listAccounts?: () => Array<{ id: string; equity: number }>;
|
|
469
|
+
}
|
|
470
|
+
| undefined;
|
|
471
|
+
|
|
472
|
+
const portfolio = paperEngine?.getAccountState?.("default") ?? {
|
|
473
|
+
equity: 10000,
|
|
474
|
+
cash: 10000,
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
// Ensure per-strategy tick memory
|
|
478
|
+
if (!tickMemory.has(strategyId)) {
|
|
479
|
+
tickMemory.set(strategyId, new Map());
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const ctx: StrategyContext = {
|
|
483
|
+
portfolio: {
|
|
484
|
+
equity: (portfolio as { equity: number }).equity,
|
|
485
|
+
cash:
|
|
486
|
+
(portfolio as { cash?: number }).cash ?? (portfolio as { equity: number }).equity,
|
|
487
|
+
positions: [],
|
|
488
|
+
},
|
|
489
|
+
history: ohlcv,
|
|
490
|
+
indicators,
|
|
491
|
+
regime: "sideways",
|
|
492
|
+
memory: tickMemory.get(strategyId)!,
|
|
493
|
+
log: () => {},
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
// Use regime detector if available
|
|
497
|
+
const regimeDetector = runtime.services?.get?.("fin-regime-detector") as
|
|
498
|
+
| { detect?: (bars: OhlcvBar[]) => string }
|
|
499
|
+
| undefined;
|
|
500
|
+
if (regimeDetector?.detect) {
|
|
501
|
+
ctx.regime = regimeDetector.detect(ohlcv) as typeof ctx.regime;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// Execute strategy onBar
|
|
505
|
+
const signal = await record.definition.onBar(latestBar, ctx);
|
|
506
|
+
|
|
507
|
+
if (!signal) {
|
|
508
|
+
return json({
|
|
509
|
+
strategyId,
|
|
510
|
+
symbol,
|
|
511
|
+
timeframe,
|
|
512
|
+
bar: { timestamp: latestBar.timestamp, close: latestBar.close },
|
|
513
|
+
signal: null,
|
|
514
|
+
action: "hold",
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// Route order based on level
|
|
519
|
+
let orderResult: unknown = null;
|
|
520
|
+
|
|
521
|
+
if (record.level === "L2_PAPER") {
|
|
522
|
+
if (paperEngine?.submitOrder) {
|
|
523
|
+
const quantity = ((signal.sizePct / 100) * ctx.portfolio.equity) / latestBar.close;
|
|
524
|
+
orderResult = paperEngine.submitOrder(
|
|
525
|
+
"default",
|
|
526
|
+
{
|
|
527
|
+
symbol: signal.symbol || symbol,
|
|
528
|
+
side: signal.action === "buy" ? "buy" : "sell",
|
|
529
|
+
type: signal.orderType,
|
|
530
|
+
quantity,
|
|
531
|
+
strategyId,
|
|
532
|
+
},
|
|
533
|
+
latestBar.close,
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
} else if (record.level === "L3_LIVE") {
|
|
537
|
+
const liveExecutor = runtime.services?.get?.("fin-live-executor") as
|
|
538
|
+
| { createOrder?: (...args: unknown[]) => Promise<unknown> }
|
|
539
|
+
| undefined;
|
|
540
|
+
if (liveExecutor?.createOrder) {
|
|
541
|
+
const quantity = ((signal.sizePct / 100) * ctx.portfolio.equity) / latestBar.close;
|
|
542
|
+
orderResult = await liveExecutor.createOrder(
|
|
543
|
+
signal.symbol || symbol,
|
|
544
|
+
signal.orderType,
|
|
545
|
+
signal.action === "buy" ? "buy" : "sell",
|
|
546
|
+
quantity,
|
|
547
|
+
signal.limitPrice,
|
|
548
|
+
);
|
|
549
|
+
} else {
|
|
550
|
+
orderResult = { warning: "Live executor not available, order not submitted" };
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return json({
|
|
555
|
+
strategyId,
|
|
556
|
+
symbol,
|
|
557
|
+
timeframe,
|
|
558
|
+
bar: { timestamp: latestBar.timestamp, close: latestBar.close },
|
|
559
|
+
signal: {
|
|
560
|
+
action: signal.action,
|
|
561
|
+
sizePct: signal.sizePct,
|
|
562
|
+
reason: signal.reason,
|
|
563
|
+
confidence: signal.confidence,
|
|
564
|
+
},
|
|
565
|
+
level: record.level,
|
|
566
|
+
orderResult,
|
|
567
|
+
});
|
|
568
|
+
} catch (err) {
|
|
569
|
+
return json({ error: err instanceof Error ? err.message : String(err) });
|
|
570
|
+
}
|
|
571
|
+
},
|
|
572
|
+
},
|
|
573
|
+
{ names: ["fin_strategy_tick"] },
|
|
574
|
+
);
|
|
575
|
+
},
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
export default plugin;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "fin-strategy-engine",
|
|
3
|
+
"name": "Strategy Engine",
|
|
4
|
+
"description": "Strategy lifecycle: indicators, backtest, walk-forward, evolution",
|
|
5
|
+
"kind": "financial",
|
|
6
|
+
"configSchema": {
|
|
7
|
+
"type": "object",
|
|
8
|
+
"additionalProperties": false,
|
|
9
|
+
"properties": {}
|
|
10
|
+
}
|
|
11
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@openfinclaw/fin-strategy-engine",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Strategy engine — indicators, backtest, evolution",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"backtest",
|
|
7
|
+
"financial",
|
|
8
|
+
"openclaw",
|
|
9
|
+
"openfinclaw",
|
|
10
|
+
"strategy"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/cryptoSUN2049/openFinclaw#readme",
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/cryptoSUN2049/openFinclaw.git",
|
|
17
|
+
"directory": "extensions/fin-strategy-engine"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"*.ts",
|
|
21
|
+
"src",
|
|
22
|
+
"openclaw.plugin.json"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"registry": "https://registry.npmjs.org"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"openfinclaw": "2026.3.3"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"openfinclaw": ">=2026.2.0"
|
|
34
|
+
},
|
|
35
|
+
"openclaw": {
|
|
36
|
+
"extensions": [
|
|
37
|
+
"./index.ts"
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
}
|