@openfinclaw/fin-strategy-engine 2026.3.3

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Peter Steinberger
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.test.ts ADDED
@@ -0,0 +1,269 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { OpenClawPluginApi } from "openfinclaw/plugin-sdk";
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
+ import plugin from "./index.js";
7
+ import { BacktestEngine } from "./src/backtest-engine.js";
8
+ import { StrategyRegistry } from "./src/strategy-registry.js";
9
+
10
+ let mockedHomeDir = "";
11
+
12
+ vi.mock("node:os", async (importOriginal) => {
13
+ const actual = await importOriginal<typeof import("node:os")>();
14
+ return {
15
+ ...actual,
16
+ homedir: () => mockedHomeDir || actual.homedir(),
17
+ };
18
+ });
19
+
20
+ function createFakeApi(stateDir: string) {
21
+ const tools = new Map<
22
+ string,
23
+ { execute: (id: string, params: Record<string, unknown>) => Promise<unknown> }
24
+ >();
25
+ const services = new Map<string, unknown>();
26
+ const api = {
27
+ id: "fin-strategy-engine",
28
+ name: "Strategy Engine",
29
+ source: "test",
30
+ config: {},
31
+ pluginConfig: {},
32
+ runtime: { version: "test", services },
33
+ logger: { info() {}, warn() {}, error() {}, debug() {} },
34
+ registerTool(tool: {
35
+ name: string;
36
+ execute: (id: string, params: Record<string, unknown>) => Promise<unknown>;
37
+ }) {
38
+ tools.set(tool.name, tool);
39
+ },
40
+ registerHook() {},
41
+ registerHttpHandler() {},
42
+ registerHttpRoute() {},
43
+ registerChannel() {},
44
+ registerGatewayMethod() {},
45
+ registerCli() {},
46
+ registerService(svc: { id: string; instance: unknown }) {
47
+ services.set(svc.id, svc.instance);
48
+ },
49
+ registerProvider() {},
50
+ registerCommand() {},
51
+ resolvePath: (p: string) => join(stateDir, p),
52
+ on() {},
53
+ } as unknown as OpenClawPluginApi;
54
+ return { api, tools, services };
55
+ }
56
+
57
+ function parseResult(result: unknown): unknown {
58
+ const res = result as { content: Array<{ text: string }> };
59
+ return JSON.parse(res.content[0]!.text);
60
+ }
61
+
62
+ describe("fin-strategy-engine plugin", () => {
63
+ let tempDir: string;
64
+ let tools: Map<
65
+ string,
66
+ { execute: (id: string, params: Record<string, unknown>) => Promise<unknown> }
67
+ >;
68
+ let services: Map<string, unknown>;
69
+
70
+ beforeEach(() => {
71
+ tempDir = mkdtempSync(join(tmpdir(), "fin-strategy-engine-test-"));
72
+ mockedHomeDir = tempDir;
73
+ const fake = createFakeApi(tempDir);
74
+ tools = fake.tools;
75
+ services = fake.services;
76
+ plugin.register(fake.api);
77
+ });
78
+
79
+ afterEach(() => {
80
+ rmSync(tempDir, { recursive: true, force: true });
81
+ });
82
+
83
+ it("registers all 4 tools", () => {
84
+ expect(tools.has("fin_strategy_create")).toBe(true);
85
+ expect(tools.has("fin_strategy_list")).toBe(true);
86
+ expect(tools.has("fin_backtest_run")).toBe(true);
87
+ expect(tools.has("fin_backtest_result")).toBe(true);
88
+ });
89
+
90
+ it("registers both services", () => {
91
+ expect(services.has("fin-strategy-registry")).toBe(true);
92
+ expect(services.has("fin-backtest-engine")).toBe(true);
93
+ expect(services.get("fin-strategy-registry")).toBeInstanceOf(StrategyRegistry);
94
+ expect(services.get("fin-backtest-engine")).toBeInstanceOf(BacktestEngine);
95
+ });
96
+
97
+ describe("fin_strategy_create", () => {
98
+ it("creates an SMA crossover strategy", async () => {
99
+ const tool = tools.get("fin_strategy_create")!;
100
+ const result = parseResult(
101
+ await tool.execute("call-1", {
102
+ name: "My SMA Strategy",
103
+ type: "sma-crossover",
104
+ parameters: { fastPeriod: 5, slowPeriod: 20 },
105
+ symbols: ["ETH/USDT"],
106
+ }),
107
+ ) as Record<string, unknown>;
108
+
109
+ expect(result.created).toBe(true);
110
+ expect(result.name).toBe("My SMA Strategy");
111
+ expect(result.level).toBe("L0_INCUBATE");
112
+ });
113
+
114
+ it("creates an RSI mean reversion strategy", async () => {
115
+ const tool = tools.get("fin_strategy_create")!;
116
+ const result = parseResult(
117
+ await tool.execute("call-2", {
118
+ name: "My RSI Strategy",
119
+ type: "rsi-mean-reversion",
120
+ parameters: { period: 7, oversold: 25, overbought: 75 },
121
+ }),
122
+ ) as Record<string, unknown>;
123
+
124
+ expect(result.created).toBe(true);
125
+ expect(result.name).toBe("My RSI Strategy");
126
+ });
127
+
128
+ it("creates a Bollinger Bands strategy", async () => {
129
+ const tool = tools.get("fin_strategy_create")!;
130
+ const result = parseResult(
131
+ await tool.execute("call-bb", {
132
+ name: "My BB Strategy",
133
+ type: "bollinger-bands",
134
+ parameters: { period: 15, stdDev: 1.5 },
135
+ }),
136
+ ) as Record<string, unknown>;
137
+
138
+ expect(result.created).toBe(true);
139
+ expect(result.name).toBe("My BB Strategy");
140
+ expect(result.level).toBe("L0_INCUBATE");
141
+ });
142
+
143
+ it("creates a MACD Divergence strategy", async () => {
144
+ const tool = tools.get("fin_strategy_create")!;
145
+ const result = parseResult(
146
+ await tool.execute("call-macd", {
147
+ name: "My MACD Strategy",
148
+ type: "macd-divergence",
149
+ parameters: { fastPeriod: 8, slowPeriod: 21, signalPeriod: 5 },
150
+ }),
151
+ ) as Record<string, unknown>;
152
+
153
+ expect(result.created).toBe(true);
154
+ expect(result.name).toBe("My MACD Strategy");
155
+ expect(result.level).toBe("L0_INCUBATE");
156
+ });
157
+
158
+ it("rejects unknown strategy type", async () => {
159
+ const tool = tools.get("fin_strategy_create")!;
160
+ const result = parseResult(
161
+ await tool.execute("call-3", { name: "Bad", type: "custom" }),
162
+ ) as Record<string, unknown>;
163
+
164
+ expect(result.error).toBeDefined();
165
+ });
166
+ });
167
+
168
+ describe("fin_strategy_list", () => {
169
+ it("returns empty list initially", async () => {
170
+ const tool = tools.get("fin_strategy_list")!;
171
+ const result = parseResult(await tool.execute("call-4", {})) as Record<string, unknown>;
172
+
173
+ expect(result.total).toBe(0);
174
+ expect(result.strategies).toEqual([]);
175
+ });
176
+
177
+ it("lists created strategies", async () => {
178
+ const createTool = tools.get("fin_strategy_create")!;
179
+ await createTool.execute("c1", { name: "S1", type: "sma-crossover" });
180
+ await createTool.execute("c2", { name: "S2", type: "rsi-mean-reversion" });
181
+
182
+ const listTool = tools.get("fin_strategy_list")!;
183
+ const result = parseResult(await listTool.execute("call-5", {})) as Record<string, unknown>;
184
+
185
+ expect(result.total).toBe(2);
186
+ });
187
+ });
188
+
189
+ describe("fin_backtest_result", () => {
190
+ it("returns error for nonexistent strategy", async () => {
191
+ const tool = tools.get("fin_backtest_result")!;
192
+ const result = parseResult(
193
+ await tool.execute("call-6", { strategyId: "nonexistent" }),
194
+ ) as Record<string, unknown>;
195
+
196
+ expect(result.error).toContain("not found");
197
+ });
198
+
199
+ it("returns error when no backtest has been run", async () => {
200
+ const createTool = tools.get("fin_strategy_create")!;
201
+ const created = parseResult(
202
+ await createTool.execute("c3", { name: "S3", type: "sma-crossover" }),
203
+ ) as Record<string, unknown>;
204
+
205
+ const tool = tools.get("fin_backtest_result")!;
206
+ const result = parseResult(
207
+ await tool.execute("call-7", { strategyId: created.id as string }),
208
+ ) as Record<string, unknown>;
209
+
210
+ expect(result.error).toContain("No backtest");
211
+ });
212
+ });
213
+
214
+ describe("fin_backtest_run", () => {
215
+ it("returns error when data provider is missing", async () => {
216
+ const createTool = tools.get("fin_strategy_create")!;
217
+ const created = parseResult(
218
+ await createTool.execute("c4", { name: "S4", type: "sma-crossover" }),
219
+ ) as Record<string, unknown>;
220
+
221
+ const tool = tools.get("fin_backtest_run")!;
222
+ const result = parseResult(
223
+ await tool.execute("call-8", { strategyId: created.id as string }),
224
+ ) as Record<string, unknown>;
225
+
226
+ expect(result.error).toContain("Data provider");
227
+ });
228
+
229
+ it("uses object-based data provider contract", async () => {
230
+ const createTool = tools.get("fin_strategy_create")!;
231
+ const created = parseResult(
232
+ await createTool.execute("c5", { name: "S5", type: "sma-crossover" }),
233
+ ) as Record<string, unknown>;
234
+
235
+ const getOHLCV = vi.fn(
236
+ async (params: { symbol: string; market: string; timeframe: string; limit?: number }) => {
237
+ const bars = params.limit ?? 365;
238
+ return Array.from({ length: bars }, (_, index) => {
239
+ const open = 100 + index * 0.1;
240
+ return {
241
+ timestamp: Date.UTC(2026, 0, 1) + index * 86_400_000,
242
+ open,
243
+ high: open + 1,
244
+ low: open - 1,
245
+ close: open + Math.sin(index / 8),
246
+ volume: 1000 + index,
247
+ };
248
+ });
249
+ },
250
+ );
251
+ services.set("fin-data-provider", { getOHLCV });
252
+
253
+ const tool = tools.get("fin_backtest_run")!;
254
+ const result = parseResult(
255
+ await tool.execute("call-9", { strategyId: created.id as string }),
256
+ ) as Record<string, unknown>;
257
+
258
+ expect(result.error).toBeUndefined();
259
+ expect(getOHLCV).toHaveBeenCalledWith(
260
+ expect.objectContaining({
261
+ symbol: "BTC/USDT",
262
+ market: "crypto",
263
+ timeframe: "1d",
264
+ limit: 365,
265
+ }),
266
+ );
267
+ });
268
+ });
269
+ });
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": "2026.3.3",
4
+ "description": "Strategy engine — indicators, backtest, evolution",
5
+ "type": "module",
6
+ "publishConfig": {
7
+ "access": "public",
8
+ "registry": "https://registry.npmjs.org"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "*.ts",
13
+ "openclaw.plugin.json"
14
+ ],
15
+ "devDependencies": {
16
+ "openfinclaw": "2026.3.3"
17
+ },
18
+ "peerDependencies": {
19
+ "openfinclaw": ">=2026.2.0"
20
+ },
21
+ "openclaw": {
22
+ "extensions": [
23
+ "./index.ts"
24
+ ]
25
+ },
26
+ "keywords": [
27
+ "openclaw",
28
+ "openfinclaw",
29
+ "financial",
30
+ "strategy",
31
+ "backtest"
32
+ ],
33
+ "homepage": "https://github.com/cryptoSUN2049/openFinclaw#readme",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/cryptoSUN2049/openFinclaw.git",
37
+ "directory": "extensions/fin-strategy-engine"
38
+ },
39
+ "license": "MIT"
40
+ }