backtest-kit 11.7.0 โ†’ 11.8.0

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/README.md CHANGED
@@ -1,1996 +1,1996 @@
1
- <img src="https://github.com/tripolskypetr/backtest-kit/raw/refs/heads/master/assets/consciousness.svg" height="45px" align="right">
2
-
3
- # ๐Ÿงฟ Backtest Kit
4
-
5
- > A TypeScript framework for backtesting and live trading strategies on multi-asset, crypto, forex or [DEX (peer-to-peer marketplace)](https://en.wikipedia.org/wiki/Decentralized_finance#Decentralized_exchanges), spot, futures with crash-safe persistence, signal validation, and AI optimization.
6
-
7
- ![screenshot](https://raw.githubusercontent.com/tripolskypetr/backtest-kit/HEAD/assets/screenshots/screenshot16.png)
8
-
9
- [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/tripolskypetr/backtest-kit)
10
- [![npm](https://img.shields.io/npm/v/backtest-kit.svg?style=flat-square)](https://npmjs.org/package/backtest-kit)
11
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue)]()
12
- [![Build](https://github.com/tripolskypetr/backtest-kit/actions/workflows/webpack.yml/badge.svg)](https://github.com/tripolskypetr/backtest-kit/actions/workflows/webpack.yml)
13
-
14
- Build reliable trading systems: backtest on historical data, deploy live bots with recovery, and optimize strategies using LLMs like Ollama.
15
-
16
- ๐Ÿ“š **[API Reference](https://backtest-kit.github.io/documents/example_02_first_backtest.html)** | ๐ŸŒŸ **[Quick Start](https://github.com/tripolskypetr/backtest-kit/tree/master/example)** | **๐Ÿ“ฐ [Article](https://backtest-kit.github.io/documents/article_07_ai_news_trading_signals.html)**
17
-
18
- ## ๐Ÿš€ Quick Start
19
-
20
- > **New to backtest-kit?** The fastest way to get a real, production-ready setup is to clone the [reference implementation](https://github.com/tripolskypetr/backtest-kit/tree/master/example) โ€” a fully working news-sentiment AI trading system with LLM forecasting, multi-timeframe data, and a documented February 2026 backtest. Start there instead of from scratch.
21
-
22
- ### ๐ŸŽฏ The Casual Way: CLI Init
23
-
24
- > **Minimal scaffold โ€” all boilerplate stays inside `@backtest-kit/cli`:**
25
-
26
- ```bash
27
- npx @backtest-kit/cli --init --output backtest-kit-project
28
- cd backtest-kit-project
29
- npm install
30
- npm start
31
- ```
32
-
33
- The generated project contains only your strategy files. There is no bootstrap, exchange registration, or runner code to maintain โ€” all of that lives inside `@backtest-kit/cli` and is invoked via `npm start`. Library documentation is fetched automatically into `docs/lib/` on init.
34
-
35
- ### ๐Ÿ—๏ธ Alternative: Sidekick CLI
36
-
37
- > **Full-control scaffold โ€” all wiring is in your project files:**
38
-
39
- ```bash
40
- npx -y @backtest-kit/sidekick my-trading-bot
41
- cd my-trading-bot
42
- npm start
43
- ```
44
-
45
- Sidekick generates a project where the exchange adapter, frame definitions, risk rules, strategy logic, and runner script all live as editable source files inside the project. Use it when you need full visibility and control over every part of the setup.
46
-
47
- ### ๐Ÿณ Running in Docker
48
-
49
- > **Automatic restarts โ€” Zero-downtime trading:**
50
-
51
- ```bash
52
- npx @backtest-kit/cli --docker
53
- cd backtest-kit-docker
54
- MODE=live SYMBOL=TRXUSDT STRATEGY_FILE=./content/feb_2026/feb_2026.strategy.ts docker-compose up -d
55
- docker-compose logs -f
56
- ```
57
-
58
- CLI can create a ready-to-use Docker workspace: self-contained directory with `docker-compose.yaml` and a strategy entry point. CLI supports [Multiple Symbol in Parallel](https://www.npmjs.com/package/@backtest-kit/cli#-multiple-symbol-parallel) for powerusers.
59
-
60
- ### ๐Ÿ“ฆ Manual Installation
61
-
62
- > **Want to see the code?** ๐Ÿ‘‰ [Demo app](https://github.com/tripolskypetr/backtest-kit/tree/master/example) ๐Ÿ‘ˆ
63
-
64
- ```bash
65
- npm install backtest-kit ccxt ollama uuid
66
- ```
67
-
68
- Install the core library and peer dependencies manually. Use this approach when integrating backtest-kit into an existing project or when you need full control over your package setup.
69
-
70
- ## โœจ Why Choose Backtest Kit?
71
-
72
- - ๐Ÿš€ **Production-Ready**: Seamless switch between backtest/live modes; identical code across environments.
73
- - ๐Ÿ’พ **Crash-Safe**: Atomic persistence recovers states after crashes, preventing duplicates or losses.
74
- - โœ… **Validation**: Checks signals for TP/SL logic, risk/reward ratios, whipsaw protection and portfolio limits.
75
- - ๐Ÿ”„ **Efficient Execution**: Streaming architecture for large datasets; VWAP pricing for realism.
76
- - ๐Ÿค– **AI Integration**: LLM-powered strategy generation (Optimizer) with multi-timeframe analysis.
77
- - ๐Ÿ“Š **Reports & Metrics**: Auto Markdown reports with PNL, Sharpe Ratio, win rate, and more.
78
- - ๐Ÿ“ **Portfolio Heatmap**: Cross-symbol portfolio with Pooled Sharpe, Sortino & Calmar Ratio, Recovery Factor, Expectancy and other measures
79
- - ๐Ÿ›ก๏ธ **Risk Management**: Custom rules for position limits, time windows, and multi-strategy coordination.
80
- - ๐Ÿ”Œ **Pluggable**: Custom data sources (CCXT), persistence (file/Redis), and sizing calculators.
81
- - ๐Ÿ—ƒ๏ธ **Transactional Live Orders**: Broker adapter intercepts every trade mutation before internal state changes โ€” exchange rejection rolls back the operation atomically.
82
- - โฐ **Built-in Crontab**: Register periodic or fire-once jobs that fire on virtual-time boundaries with singleshot coordination across parallel backtests โ€” one handler invocation per boundary, no double-fires.
83
- - ๐Ÿงช **Tested**: 775+ unit/integration tests for validation, recovery, and events.
84
- - ๐Ÿ”“ **Self hosted**: Zero dependency on third-party node_modules or platforms; run entirely in your own environment.
85
-
86
- ## ๐Ÿ“‹ Supported Order Types
87
-
88
- > With the calculation of PnL, Peak Profit and Max Drawdown for each Entry
89
-
90
- - Market/Limit entries
91
- - TP/SL/OCO exits
92
- - Grid with auto-cancel on unmet conditions
93
- - Partial profit/loss levels
94
- - Trailing stop-loss
95
- - Breakeven protection
96
- - Stop limit entries (before OCO)
97
- - Dollar cost averaging
98
- - Time attack / Infinite hold
99
-
100
- ## ๐Ÿ“š Code Samples
101
-
102
- ### โš™๏ธ Basic Configuration
103
- ```typescript
104
- import { setLogger, setConfig } from 'backtest-kit';
105
-
106
- // Enable logging
107
- setLogger({
108
- log: console.log,
109
- debug: console.debug,
110
- info: console.info,
111
- warn: console.warn,
112
- });
113
-
114
- // Global config (optional)
115
- setConfig({
116
- CC_PERCENT_SLIPPAGE: 0.1, // % slippage
117
- CC_PERCENT_FEE: 0.1, // % fee
118
- CC_SCHEDULE_AWAIT_MINUTES: 120, // Pending signal timeout
119
- });
120
- ```
121
-
122
- ### ๐Ÿ”ง Register Components
123
- ```typescript
124
- import ccxt from 'ccxt';
125
- import { addExchangeSchema, addStrategySchema, addFrameSchema, addRiskSchema } from 'backtest-kit';
126
-
127
- // Exchange (data source)
128
- addExchangeSchema({
129
- exchangeName: 'binance',
130
- getCandles: async (symbol, interval, since, limit) => {
131
- const exchange = new ccxt.binance();
132
- const ohlcv = await exchange.fetchOHLCV(symbol, interval, since.getTime(), limit);
133
- return ohlcv.map(([timestamp, open, high, low, close, volume]) => ({ timestamp, open, high, low, close, volume }));
134
- },
135
- formatPrice: (symbol, price) => price.toFixed(2),
136
- formatQuantity: (symbol, quantity) => quantity.toFixed(8),
137
- });
138
-
139
- // Risk profile
140
- addRiskSchema({
141
- riskName: 'demo',
142
- validations: [
143
- // TP at least 1%
144
- ({ pendingSignal, currentPrice }) => {
145
- const { priceOpen = currentPrice, priceTakeProfit, position } = pendingSignal;
146
- const tpDistance = position === 'long' ? ((priceTakeProfit - priceOpen) / priceOpen) * 100 : ((priceOpen - priceTakeProfit) / priceOpen) * 100;
147
- if (tpDistance < 1) throw new Error(`TP too close: ${tpDistance.toFixed(2)}%`);
148
- },
149
- // R/R at least 2:1
150
- ({ pendingSignal, currentPrice }) => {
151
- const { priceOpen = currentPrice, priceTakeProfit, priceStopLoss, position } = pendingSignal;
152
- const reward = position === 'long' ? priceTakeProfit - priceOpen : priceOpen - priceTakeProfit;
153
- const risk = position === 'long' ? priceOpen - priceStopLoss : priceStopLoss - priceOpen;
154
- if (reward / risk < 2) throw new Error('Poor R/R ratio');
155
- },
156
- ],
157
- });
158
-
159
- // Time frame
160
- addFrameSchema({
161
- frameName: '1d-test',
162
- interval: '1m',
163
- startDate: new Date('2025-12-01'),
164
- endDate: new Date('2025-12-02'),
165
- });
166
- ```
167
-
168
- ### ๐Ÿ’ก Example Strategy (with LLM)
169
- ```typescript
170
- import { v4 as uuid } from 'uuid';
171
- import { addStrategySchema, getCandles, dumpAgentAnswer, dumpRecord } from 'backtest-kit';
172
- import { json } from './utils/json.mjs'; // LLM wrapper
173
- import { getMessages } from './utils/messages.mjs'; // Market data prep
174
-
175
- addStrategySchema({
176
- strategyName: 'llm-strategy',
177
- interval: '5m',
178
- riskName: 'demo',
179
- getSignal: async (symbol) => {
180
-
181
- const candles1h = await getCandles(symbol, "1h", 24);
182
- const candles15m = await getCandles(symbol, "15m", 48);
183
- const candles5m = await getCandles(symbol, "5m", 60);
184
- const candles1m = await getCandles(symbol, "1m", 60);
185
-
186
- const messages = await getMessages(symbol, {
187
- candles1h,
188
- candles15m,
189
- candles5m,
190
- candles1m,
191
- }); // Calculate indicators / Fetch news
192
-
193
- const resultId = uuid();
194
- const signal = await json(messages); // LLM generates signal
195
-
196
- await dumpAgentAnswer({
197
- dumpId: "position-context",
198
- bucketName: "multi-timeframe-strategy",
199
- messages: messages, // pass saved messages here
200
- description: "agent reasoning for this signal",
201
- });
202
-
203
- await dumpRecord({
204
- dumpId: "position-entry",
205
- bucketName: "multi-timeframe-strategy",
206
- record: signal, // pass saved signal record here
207
- description: "signal entry parameters",
208
- });
209
-
210
- return { ...signal, id: resultId };
211
- },
212
- });
213
- ```
214
-
215
- ### ๐Ÿงช Run Backtest
216
- ```typescript
217
- import { Backtest, listenSignalBacktest, listenDoneBacktest } from 'backtest-kit';
218
-
219
- Backtest.background('BTCUSDT', {
220
- strategyName: 'llm-strategy',
221
- exchangeName: 'binance',
222
- frameName: '1d-test',
223
- });
224
-
225
- listenSignalBacktest((event) => console.log(event));
226
- listenDoneBacktest(async (event) => {
227
- await Backtest.dump(event.symbol, event.strategyName); // Generate report
228
- });
229
- ```
230
-
231
- ### ๐Ÿ“ˆ Run Live Trading
232
- ```typescript
233
- import { Live, listenSignalLive } from 'backtest-kit';
234
-
235
- Live.background('BTCUSDT', {
236
- strategyName: 'llm-strategy',
237
- exchangeName: 'binance', // Use API keys in .env
238
- });
239
-
240
- listenSignalLive((event) => console.log(event));
241
- ```
242
-
243
- ### ๐Ÿ“ก Monitoring & Events
244
-
245
- - Use `listenRisk`, `listenError`, `listenPartialProfit/Loss` for alerts.
246
- - Dump reports: `Backtest.dump()`, `Live.dump()`.
247
-
248
- ## ๐ŸŒ Global Configuration
249
-
250
- Customize via `setConfig()`:
251
-
252
- - `CC_SCHEDULE_AWAIT_MINUTES`: Pending timeout (default: 120).
253
- - `CC_AVG_PRICE_CANDLES_COUNT`: VWAP candles (default: 5).
254
-
255
- ## ๐Ÿ’ป Developer Note
256
-
257
- Backtest Kit is **not a data-processing library** - it is a **time execution engine**. Think of the engine as an **async stream of time**, where your strategy is evaluated step by step.
258
-
259
- ### ๐Ÿ” How PNL Works
260
-
261
- These three functions work together to dynamically manage the position. To reduce position linearity, by default, each DCA entry is formatted as a fixed **unit of $100**. This can be changed. No mathematical knowledge is required.
262
-
263
- **Public API:**
264
- - **`commitAverageBuy`** โ€” adds a new DCA entry. By default, **only accepted when current price is below a new low**. Silently rejected otherwise. This prevents averaging up. Can be overridden using `setConfig`
265
- - **`commitPartialProfit`** โ€” closes X% of the position at a profit. Locks in gains while keeping exposure.
266
- - **`commitPartialLoss`** โ€” closes X% of the position at a loss. Cuts exposure before the stop-loss is hit.
267
-
268
- <details>
269
- <summary>
270
- The Math
271
- </summary>
272
-
273
- **Scenario:** LONG entry @ 1000, 4 DCA attempts (1 rejected), 3 partials, closed at TP.
274
- `totalInvested = $400` (4 ร— $100, rejected attempt not counted).
275
-
276
- **Entries**
277
- ```
278
- entry#1 @ 1000 โ†’ 0.10000 coins
279
- commitPartialProfit(30%) @ 1150 โ† cnt=1
280
- entry#2 @ 950 โ†’ 0.10526 coins
281
- entry#3 @ 880 โ†’ 0.11364 coins
282
- commitPartialLoss(20%) @ 860 โ† cnt=3
283
- entry#4 @ 920 โ†’ 0.10870 coins
284
- commitPartialProfit(40%) @ 1050 โ† cnt=4
285
- entry#5 @ 980 โœ— REJECTED (980 > ep3โ‰ˆ929.92)
286
- totalInvested = $400
287
- ```
288
-
289
- **Partial#1 โ€” commitPartialProfit @ 1150, 30%, cnt=1**
290
- ```
291
- effectivePrice = hm(1000) = 1000
292
- costBasis = $100
293
- partialDollarValue = 30% ร— 100 = $30 โ†’ weight = 30/400 = 0.075
294
- pnl = (1150โˆ’1000)/1000 ร— 100 = +15.00%
295
- costBasis โ†’ $70
296
- coins sold: 0.03000 ร— 1150 = $34.50
297
- remaining: 0.07000
298
- ```
299
-
300
- **DCA after Partial#1**
301
- ```
302
- entry#2 @ 950 (950 < ep1=1000 โœ“ accepted)
303
- entry#3 @ 880 (880 < ep1=1000 โœ“ accepted)
304
- coins: 0.07000 + 0.10526 + 0.11364 = 0.28890
305
- ```
306
-
307
- **Partial#2 โ€” commitPartialLoss @ 860, 20%, cnt=3**
308
- ```
309
- costBasis = 70 + 100 + 100 = $270
310
- ep2 = 270 / 0.28890 โ‰ˆ 934.58
311
- partialDollarValue = 20% ร— 270 = $54 โ†’ weight = 54/400 = 0.135
312
- pnl = (860โˆ’934.58)/934.58 ร— 100 โ‰ˆ โˆ’7.98%
313
- costBasis โ†’ $216
314
- coins sold: 0.05778 ร— 860 = $49.69
315
- remaining: 0.23112
316
- ```
317
-
318
- **DCA after Partial#2**
319
- ```
320
- entry#4 @ 920 (920 < ep2=934.58 โœ“ accepted)
321
- coins: 0.23112 + 0.10870 = 0.33982
322
- ```
323
-
324
- **Partial#3 โ€” commitPartialProfit @ 1050, 40%, cnt=4**
325
- ```
326
- costBasis = 216 + 100 = $316
327
- ep3 = 316 / 0.33982 โ‰ˆ 929.92
328
- partialDollarValue = 40% ร— 316 = $126.4 โ†’ weight = 126.4/400 = 0.316
329
- pnl = (1050โˆ’929.92)/929.92 ร— 100 โ‰ˆ +12.91%
330
- costBasis โ†’ $189.6
331
- coins sold: 0.13593 ร— 1050 = $142.72
332
- remaining: 0.20389
333
- ```
334
-
335
- **DCA after Partial#3 โ€” rejected**
336
- ```
337
- entry#5 @ 980 (980 > ep3โ‰ˆ929.92 โœ— REJECTED)
338
- ```
339
-
340
- **Close at TP @ 1200**
341
- ```
342
- ep_final = ep3 โ‰ˆ 929.92 (no new entries)
343
- coins: 0.20389
344
-
345
- remainingDollarValue = 400 โˆ’ 30 โˆ’ 54 โˆ’ 126.4 = $189.6
346
- weight = 189.6/400 = 0.474
347
- pnl = (1200โˆ’929.92)/929.92 ร— 100 โ‰ˆ +29.04%
348
- coins sold: 0.20389 ร— 1200 = $244.67
349
- ```
350
-
351
- **Result (toProfitLossDto)**
352
- ```
353
- 0.075 ร— (+15.00) = +1.125
354
- 0.135 ร— (โˆ’7.98) = โˆ’1.077
355
- 0.316 ร— (+12.91) = +4.080
356
- 0.474 ร— (+29.04) = +13.765
357
- โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
358
- โ‰ˆ +17.89%
359
-
360
- Cross-check (coins):
361
- 34.50 + 49.69 + 142.72 + 244.67 = $471.58
362
- (471.58 โˆ’ 400) / 400 ร— 100 = +17.90% โœ“
363
- ```
364
- </details>
365
-
366
- #### Internals
367
-
368
- **`priceOpen`** is the harmonic mean of all accepted DCA entries. After each partial close (`commitPartialProfit` or `commitPartialLoss`), the remaining cost basis is carried forward into the harmonic mean calculation for subsequent entries โ€” so `priceOpen` shifts after every partial, which in turn changes whether the next `commitAverageBuy` call will be accepted.
369
-
370
- ### ๐Ÿ” How Broker Transactional Integrity Works
371
-
372
- `Broker.useBrokerAdapter` connects a live exchange (ccxt, Binance, etc.) to the framework with transaction safety. Every commit method fires **before** the internal position state mutates. If the exchange rejects the order, the fill times out, or the network fails, the adapter throws, the mutation is skipped, and backtest-kit retries automatically on the next tick.
373
-
374
- <details>
375
- <summary>
376
- The code
377
- </summary>
378
-
379
- **Spot**
380
-
381
- ```typescript
382
- import ccxt from "ccxt";
383
- import { singleshot, sleep } from "functools-kit";
384
- import {
385
- Broker,
386
- IBroker,
387
- BrokerSignalOpenPayload,
388
- BrokerSignalClosePayload,
389
- BrokerPartialProfitPayload,
390
- BrokerPartialLossPayload,
391
- BrokerTrailingStopPayload,
392
- BrokerTrailingTakePayload,
393
- BrokerBreakevenPayload,
394
- BrokerAverageBuyPayload,
395
- } from "backtest-kit";
396
-
397
- const FILL_POLL_INTERVAL_MS = 10_000;
398
- const FILL_POLL_ATTEMPTS = 10;
399
-
400
- /**
401
- * Sleep between cancelOrder and fetchBalance to allow Binance to settle the
402
- * cancellation โ€” reads immediately after cancel may return stale data.
403
- */
404
- const CANCEL_SETTLE_MS = 2_000;
405
-
406
- /**
407
- * Slippage buffer for stop_loss_limit on Spot โ€” limit price is set slightly
408
- * below stopPrice so the order fills even on a gap down instead of hanging.
409
- */
410
- const STOP_LIMIT_SLIPPAGE = 0.995;
411
-
412
- const getSpotExchange = singleshot(async () => {
413
- const exchange = new ccxt.binance({
414
- apiKey: process.env.BINANCE_API_KEY,
415
- secret: process.env.BINANCE_API_SECRET,
416
- options: {
417
- defaultType: "spot",
418
- adjustForTimeDifference: true,
419
- recvWindow: 60000,
420
- },
421
- enableRateLimit: true,
422
- });
423
- await exchange.loadMarkets();
424
- return exchange;
425
- });
426
-
427
- /**
428
- * Resolve base currency from market metadata โ€” safe for all quote currencies (USDT, USDC, FDUSD, etc.)
429
- */
430
- function getBase(exchange: ccxt.binance, symbol: string): string {
431
- return exchange.markets[symbol].base;
432
- }
433
-
434
- /**
435
- * Truncate qty to exchange precision, always rounding down.
436
- * Prevents over-selling due to floating point drift from fetchBalance.
437
- */
438
- function truncateQty(exchange: ccxt.binance, symbol: string, qty: number): number {
439
- return parseFloat(exchange.amountToPrecision(symbol, qty, exchange.TRUNCATE));
440
- }
441
-
442
- /**
443
- * Fetch current free balance for base currency of symbol.
444
- */
445
- async function fetchFreeQty(exchange: ccxt.binance, symbol: string): Promise<number> {
446
- const balance = await exchange.fetchBalance();
447
- const base = getBase(exchange, symbol);
448
- return parseFloat(String(balance?.free?.[base] ?? 0));
449
- }
450
-
451
- /**
452
- * Cancel all orders in parallel โ€” allSettled so a single failure (already filled,
453
- * network blip) does not leave remaining orders uncancelled.
454
- */
455
- async function cancelAllOrders(exchange: ccxt.binance, orders: ccxt.Order[], symbol: string): Promise<void> {
456
- await Promise.allSettled(orders.map((o) => exchange.cancelOrder(o.id, symbol)));
457
- }
458
-
459
- /**
460
- * Place a stop_loss_limit sell order with a slippage buffer on the limit price.
461
- * stop_loss_limit requires both stopPrice (trigger) and price (limit fill).
462
- * Setting them equal risks non-fill on gap down โ€” limit is offset by STOP_LIMIT_SLIPPAGE.
463
- */
464
- async function createStopLossOrder(
465
- exchange: ccxt.binance,
466
- symbol: string,
467
- qty: number,
468
- stopPrice: number
469
- ): Promise<void> {
470
- const limitPrice = parseFloat(exchange.priceToPrecision(symbol, stopPrice * STOP_LIMIT_SLIPPAGE));
471
- await exchange.createOrder(symbol, "stop_loss_limit", "sell", qty, limitPrice, { stopPrice });
472
- }
473
-
474
- /**
475
- * Place a limit order and poll until filled (status === "closed").
476
- * On timeout: cancel the order, settle, check partial fill and sell it via market,
477
- * restore SL/TP on remaining position so it is never left unprotected, then throw.
478
- */
479
- async function createLimitOrderAndWait(
480
- exchange: ccxt.binance,
481
- symbol: string,
482
- side: "buy" | "sell",
483
- qty: number,
484
- price: number,
485
- restore?: { tpPrice: number; slPrice: number }
486
- ): Promise<void> {
487
- const order = await exchange.createOrder(symbol, "limit", side, qty, price);
488
-
489
- for (let i = 0; i < FILL_POLL_ATTEMPTS; i++) {
490
- await sleep(FILL_POLL_INTERVAL_MS);
491
- const status = await exchange.fetchOrder(order.id, symbol);
492
- if (status.status === "closed") {
493
- return;
494
- }
495
- }
496
-
497
- await exchange.cancelOrder(order.id, symbol);
498
-
499
- // Wait for Binance to settle the cancellation before reading filled qty
500
- await sleep(CANCEL_SETTLE_MS);
501
-
502
- const final = await exchange.fetchOrder(order.id, symbol);
503
- const filledQty = final.filled ?? 0;
504
-
505
- if (filledQty > 0) {
506
- // Sell partial fill via market to restore clean exchange state before backtest-kit retries
507
- const rollbackSide = side === "buy" ? "sell" : "buy";
508
- await exchange.createOrder(symbol, "market", rollbackSide, filledQty);
509
- }
510
-
511
- // Restore SL/TP on remaining position so it is not left unprotected during retry
512
- if (restore) {
513
- const remainingQty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
514
- if (remainingQty > 0) {
515
- await exchange.createOrder(symbol, "limit", "sell", remainingQty, restore.tpPrice);
516
- await createStopLossOrder(exchange, symbol, remainingQty, restore.slPrice);
517
- }
518
- }
519
-
520
- throw new Error(`Limit order ${order.id} [${side} ${qty} ${symbol} @ ${price}] not filled in time โ€” partial fill rolled back, backtest-kit will retry`);
521
- }
522
-
523
- Broker.useBrokerAdapter(
524
- class implements IBroker {
525
-
526
- async waitForInit(): Promise<void> {
527
- await getSpotExchange();
528
- }
529
-
530
- async onSignalOpenCommit(payload: BrokerSignalOpenPayload): Promise<void> {
531
- const { symbol, cost, priceOpen, priceTakeProfit, priceStopLoss, position } = payload;
532
-
533
- // Spot does not support short selling โ€” reject immediately so backtest-kit skips the mutation
534
- if (position === "short") {
535
- throw new Error(`SpotBrokerAdapter: short position is not supported on spot (symbol=${symbol})`);
536
- }
537
-
538
- const exchange = await getSpotExchange();
539
-
540
- const qty = truncateQty(exchange, symbol, cost / priceOpen);
541
-
542
- // Guard: truncation may produce 0 if cost/price is below lot size
543
- if (qty <= 0) {
544
- throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${priceOpen}`);
545
- }
546
-
547
- const openPrice = parseFloat(exchange.priceToPrecision(symbol, priceOpen));
548
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
549
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
550
-
551
- // Entry: no restore needed โ€” position does not exist yet if entry times out
552
- await createLimitOrderAndWait(exchange, symbol, "buy", qty, openPrice);
553
-
554
- // Post-fill: if TP/SL placement fails, position is open and unprotected โ€” close via market
555
- try {
556
- await exchange.createOrder(symbol, "limit", "sell", qty, tpPrice);
557
- await createStopLossOrder(exchange, symbol, qty, slPrice);
558
- } catch (err) {
559
- await exchange.createOrder(symbol, "market", "sell", qty);
560
- throw err;
561
- }
562
- }
563
-
564
- async onSignalCloseCommit(payload: BrokerSignalClosePayload): Promise<void> {
565
- const { symbol, currentPrice, priceTakeProfit, priceStopLoss } = payload;
566
- const exchange = await getSpotExchange();
567
-
568
- const openOrders = await exchange.fetchOpenOrders(symbol);
569
- await cancelAllOrders(exchange, openOrders, symbol);
570
- await sleep(CANCEL_SETTLE_MS);
571
-
572
- const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
573
-
574
- // Position already closed by SL/TP on exchange โ€” nothing to do, commit succeeds
575
- if (qty === 0) {
576
- return;
577
- }
578
-
579
- const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
580
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
581
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
582
-
583
- // Restore SL/TP if close times out so position is not left unprotected during retry
584
- await createLimitOrderAndWait(exchange, symbol, "sell", qty, closePrice, { tpPrice, slPrice });
585
- }
586
-
587
- async onPartialProfitCommit(payload: BrokerPartialProfitPayload): Promise<void> {
588
- const { symbol, percentToClose, currentPrice, priceTakeProfit, priceStopLoss } = payload;
589
- const exchange = await getSpotExchange();
590
-
591
- const openOrders = await exchange.fetchOpenOrders(symbol);
592
- await cancelAllOrders(exchange, openOrders, symbol);
593
- await sleep(CANCEL_SETTLE_MS);
594
-
595
- const totalQty = await fetchFreeQty(exchange, symbol);
596
-
597
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
598
- if (totalQty === 0) {
599
- throw new Error(`PartialProfit skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
600
- }
601
-
602
- const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
603
- const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
604
- const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
605
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
606
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
607
-
608
- // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
609
- await createLimitOrderAndWait(exchange, symbol, "sell", qty, closePrice, { tpPrice, slPrice });
610
-
611
- // Restore SL/TP on remaining qty after successful partial close
612
- if (remainingQty > 0) {
613
- try {
614
- await exchange.createOrder(symbol, "limit", "sell", remainingQty, tpPrice);
615
- await createStopLossOrder(exchange, symbol, remainingQty, slPrice);
616
- } catch (err) {
617
- // Remaining position is unprotected โ€” close via market
618
- await exchange.createOrder(symbol, "market", "sell", remainingQty);
619
- throw err;
620
- }
621
- }
622
- }
623
-
624
- async onPartialLossCommit(payload: BrokerPartialLossPayload): Promise<void> {
625
- const { symbol, percentToClose, currentPrice, priceTakeProfit, priceStopLoss } = payload;
626
- const exchange = await getSpotExchange();
627
-
628
- const openOrders = await exchange.fetchOpenOrders(symbol);
629
- await cancelAllOrders(exchange, openOrders, symbol);
630
- await sleep(CANCEL_SETTLE_MS);
631
-
632
- const totalQty = await fetchFreeQty(exchange, symbol);
633
-
634
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
635
- if (totalQty === 0) {
636
- throw new Error(`PartialLoss skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
637
- }
638
-
639
- const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
640
- const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
641
- const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
642
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
643
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
644
-
645
- // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
646
- await createLimitOrderAndWait(exchange, symbol, "sell", qty, closePrice, { tpPrice, slPrice });
647
-
648
- // Restore SL/TP on remaining qty after successful partial close
649
- if (remainingQty > 0) {
650
- try {
651
- await exchange.createOrder(symbol, "limit", "sell", remainingQty, tpPrice);
652
- await createStopLossOrder(exchange, symbol, remainingQty, slPrice);
653
- } catch (err) {
654
- // Remaining position is unprotected โ€” close via market
655
- await exchange.createOrder(symbol, "market", "sell", remainingQty);
656
- throw err;
657
- }
658
- }
659
- }
660
-
661
- async onTrailingStopCommit(payload: BrokerTrailingStopPayload): Promise<void> {
662
- const { symbol, newStopLossPrice } = payload;
663
- const exchange = await getSpotExchange();
664
-
665
- // Cancel existing SL order only โ€” Spot has no reduceOnly, filter by side + type
666
- const orders = await exchange.fetchOpenOrders(symbol);
667
- const slOrder = orders.find((o) =>
668
- o.side === "sell" &&
669
- ["stop_loss_limit", "stop", "STOP_LOSS_LIMIT"].includes(o.type ?? "")
670
- ) ?? null;
671
- if (slOrder) {
672
- await exchange.cancelOrder(slOrder.id, symbol);
673
- await sleep(CANCEL_SETTLE_MS);
674
- }
675
-
676
- const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
677
-
678
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
679
- if (qty === 0) {
680
- throw new Error(`TrailingStop skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
681
- }
682
-
683
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
684
-
685
- await createStopLossOrder(exchange, symbol, qty, slPrice);
686
- }
687
-
688
- async onTrailingTakeCommit(payload: BrokerTrailingTakePayload): Promise<void> {
689
- const { symbol, newTakeProfitPrice } = payload;
690
- const exchange = await getSpotExchange();
691
-
692
- // Cancel existing TP order only โ€” Spot has no reduceOnly, filter by side + type
693
- const orders = await exchange.fetchOpenOrders(symbol);
694
- const tpOrder = orders.find((o) =>
695
- o.side === "sell" &&
696
- ["limit", "LIMIT"].includes(o.type ?? "")
697
- ) ?? null;
698
- if (tpOrder) {
699
- await exchange.cancelOrder(tpOrder.id, symbol);
700
- await sleep(CANCEL_SETTLE_MS);
701
- }
702
-
703
- const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
704
-
705
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
706
- if (qty === 0) {
707
- throw new Error(`TrailingTake skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
708
- }
709
-
710
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, newTakeProfitPrice));
711
-
712
- await exchange.createOrder(symbol, "limit", "sell", qty, tpPrice);
713
- }
714
-
715
- async onBreakevenCommit(payload: BrokerBreakevenPayload): Promise<void> {
716
- const { symbol, newStopLossPrice } = payload;
717
- const exchange = await getSpotExchange();
718
-
719
- // Cancel existing SL order only โ€” Spot has no reduceOnly, filter by side + type
720
- const orders = await exchange.fetchOpenOrders(symbol);
721
- const slOrder = orders.find((o) =>
722
- o.side === "sell" &&
723
- ["stop_loss_limit", "stop", "STOP_LOSS_LIMIT"].includes(o.type ?? "")
724
- ) ?? null;
725
- if (slOrder) {
726
- await exchange.cancelOrder(slOrder.id, symbol);
727
- await sleep(CANCEL_SETTLE_MS);
728
- }
729
-
730
- const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
731
-
732
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
733
- if (qty === 0) {
734
- throw new Error(`Breakeven skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
735
- }
736
-
737
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
738
-
739
- await createStopLossOrder(exchange, symbol, qty, slPrice);
740
- }
741
-
742
- async onAverageBuyCommit(payload: BrokerAverageBuyPayload): Promise<void> {
743
- const { symbol, currentPrice, cost, priceTakeProfit, priceStopLoss } = payload;
744
- const exchange = await getSpotExchange();
745
-
746
- // Cancel existing SL/TP first โ€” existing check must happen after cancel+settle
747
- // to avoid race condition where SL/TP fills between the existence check and cancel
748
- const openOrders = await exchange.fetchOpenOrders(symbol);
749
- await cancelAllOrders(exchange, openOrders, symbol);
750
- await sleep(CANCEL_SETTLE_MS);
751
-
752
- // Guard against DCA into a ghost position โ€” checked after cancel so the snapshot is fresh
753
- const existing = await fetchFreeQty(exchange, symbol);
754
- const minNotional = exchange.markets[symbol].limits?.cost?.min ?? 1;
755
-
756
- // Compare notional value rather than raw qty โ€” avoids float === 0 trap
757
- // and correctly rejects dust balances left over from previous trades
758
- if (existing * currentPrice < minNotional) {
759
- throw new Error(`AverageBuy skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
760
- }
761
-
762
- const qty = truncateQty(exchange, symbol, cost / currentPrice);
763
-
764
- // Guard: truncation may produce 0 if cost/price is below lot size
765
- if (qty <= 0) {
766
- throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${currentPrice}`);
767
- }
768
-
769
- const entryPrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
770
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
771
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
772
-
773
- // DCA entry: restore SL/TP on existing qty if times out so position is not left unprotected
774
- await createLimitOrderAndWait(exchange, symbol, "buy", qty, entryPrice, { tpPrice, slPrice });
775
-
776
- // Refetch balance after fill โ€” existing snapshot is stale after cancel + fill
777
- const totalQty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
778
-
779
- // Recreate SL/TP on fresh total qty after successful fill
780
- try {
781
- await exchange.createOrder(symbol, "limit", "sell", totalQty, tpPrice);
782
- await createStopLossOrder(exchange, symbol, totalQty, slPrice);
783
- } catch (err) {
784
- // Total position is unprotected โ€” close via market
785
- await exchange.createOrder(symbol, "market", "sell", totalQty);
786
- throw err;
787
- }
788
- }
789
- }
790
- );
791
-
792
- Broker.enable();
793
- ```
794
-
795
- **Futures**
796
-
797
- ```typescript
798
- import ccxt from "ccxt";
799
- import { singleshot, sleep } from "functools-kit";
800
- import {
801
- Broker,
802
- IBroker,
803
- BrokerSignalOpenPayload,
804
- BrokerSignalClosePayload,
805
- BrokerPartialProfitPayload,
806
- BrokerPartialLossPayload,
807
- BrokerTrailingStopPayload,
808
- BrokerTrailingTakePayload,
809
- BrokerBreakevenPayload,
810
- BrokerAverageBuyPayload,
811
- } from "backtest-kit";
812
-
813
- const FILL_POLL_INTERVAL_MS = 10_000;
814
- const FILL_POLL_ATTEMPTS = 10;
815
-
816
- /**
817
- * Sleep between cancelOrder and fetchPositions to allow Binance to settle the
818
- * cancellation โ€” reads immediately after cancel may return stale data.
819
- */
820
- const CANCEL_SETTLE_MS = 2_000;
821
-
822
- /**
823
- * 3x leverage โ€” conservative choice for $1000 total fiat.
824
- * Enough to matter, not enough to liquidate on normal volatility.
825
- * Applied per-symbol on first open via setLeverage.
826
- */
827
- const FUTURES_LEVERAGE = 3;
828
-
829
- const getFuturesExchange = singleshot(async () => {
830
- const exchange = new ccxt.binance({
831
- apiKey: process.env.BINANCE_API_KEY,
832
- secret: process.env.BINANCE_API_SECRET,
833
- options: {
834
- defaultType: "future",
835
- adjustForTimeDifference: true,
836
- recvWindow: 60000,
837
- },
838
- enableRateLimit: true,
839
- });
840
- await exchange.loadMarkets();
841
- return exchange;
842
- });
843
-
844
- /**
845
- * Truncate qty to exchange precision, always rounding down.
846
- * Prevents over-selling due to floating point drift from fetchPositions.
847
- */
848
- function truncateQty(exchange: ccxt.binance, symbol: string, qty: number): number {
849
- return parseFloat(exchange.amountToPrecision(symbol, qty, exchange.TRUNCATE));
850
- }
851
-
852
- /**
853
- * Resolve position for symbol filtered by side โ€” safe in both one-way and hedge mode.
854
- */
855
- function findPosition(positions: ccxt.Position[], symbol: string, side: "long" | "short") {
856
- // Hedge mode: positions have explicit side field
857
- const hedged = positions.find((p) => p.symbol === symbol && p.side === side);
858
- if (hedged) {
859
- return hedged;
860
- }
861
- // One-way mode: single position per symbol, side field may be undefined or mismatched
862
- const pos = positions.find((p) => p.symbol === symbol) ?? null;
863
- if (pos && pos.side && pos.side !== side) {
864
- console.warn(`findPosition: expected side="${side}" but exchange returned side="${pos.side}" for ${symbol} โ€” possible one-way/hedge mode mismatch`);
865
- }
866
- return pos;
867
- }
868
-
869
- /**
870
- * Fetch current contracts qty for symbol/side.
871
- */
872
- async function fetchContractsQty(
873
- exchange: ccxt.binance,
874
- symbol: string,
875
- side: "long" | "short"
876
- ): Promise<number> {
877
- const positions = await exchange.fetchPositions([symbol]);
878
- const pos = findPosition(positions, symbol, side);
879
- return Math.abs(parseFloat(String(pos?.contracts ?? 0)));
880
- }
881
-
882
- /**
883
- * Cancel all orders in parallel โ€” allSettled so a single failure (already filled,
884
- * network blip) does not leave remaining orders uncancelled.
885
- */
886
- async function cancelAllOrders(exchange: ccxt.binance, orders: ccxt.Order[], symbol: string): Promise<void> {
887
- await Promise.allSettled(orders.map((o) => exchange.cancelOrder(o.id, symbol)));
888
- }
889
-
890
- /**
891
- * Resolve Binance positionSide string from position direction.
892
- * Required in hedge mode to correctly route orders; ignored in one-way mode.
893
- */
894
- function toPositionSide(position: "long" | "short"): "LONG" | "SHORT" {
895
- return position === "long" ? "LONG" : "SHORT";
896
- }
897
-
898
- /**
899
- * Place a limit order and poll until filled (status === "closed").
900
- * On timeout: cancel the order, settle, check partial fill and close it via market,
901
- * restore SL/TP on remaining position so it is never left unprotected, then throw.
902
- *
903
- * positionSide is forwarded into rollback market order so hedge mode accounts
904
- * correctly route the close without -4061 error.
905
- */
906
- async function createLimitOrderAndWait(
907
- exchange: ccxt.binance,
908
- symbol: string,
909
- side: "buy" | "sell",
910
- qty: number,
911
- price: number,
912
- params: Record<string, unknown> = {},
913
- restore?: { exitSide: "buy" | "sell"; tpPrice: number; slPrice: number; positionSide: "long" | "short" }
914
- ): Promise<void> {
915
- const order = await exchange.createOrder(symbol, "limit", side, qty, price, params);
916
-
917
- for (let i = 0; i < FILL_POLL_ATTEMPTS; i++) {
918
- await sleep(FILL_POLL_INTERVAL_MS);
919
- const status = await exchange.fetchOrder(order.id, symbol);
920
- if (status.status === "closed") {
921
- return;
922
- }
923
- }
924
-
925
- await exchange.cancelOrder(order.id, symbol);
926
-
927
- // Wait for Binance to settle the cancellation before reading filled qty
928
- await sleep(CANCEL_SETTLE_MS);
929
-
930
- const final = await exchange.fetchOrder(order.id, symbol);
931
- const filledQty = final.filled ?? 0;
932
-
933
- if (filledQty > 0) {
934
- // Close partial fill via market โ€” positionSide required in hedge mode (-4061 without it)
935
- const rollbackSide = side === "buy" ? "sell" : "buy";
936
- const rollbackPositionSide = params.positionSide ?? (restore ? toPositionSide(restore.positionSide) : undefined);
937
- await exchange.createOrder(symbol, "market", rollbackSide, filledQty, undefined, {
938
- reduceOnly: true,
939
- ...(rollbackPositionSide ? { positionSide: rollbackPositionSide } : {}),
940
- });
941
- }
942
-
943
- // Restore SL/TP on remaining position so it is not left unprotected during retry
944
- if (restore) {
945
- const remainingQty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, restore.positionSide));
946
- if (remainingQty > 0) {
947
- await exchange.createOrder(symbol, "limit", restore.exitSide, remainingQty, restore.tpPrice, { reduceOnly: true });
948
- await exchange.createOrder(symbol, "stop_market", restore.exitSide, remainingQty, undefined, { stopPrice: restore.slPrice, reduceOnly: true });
949
- }
950
- }
951
-
952
- throw new Error(`Limit order ${order.id} [${side} ${qty} ${symbol} @ ${price}] not filled in time โ€” partial fill rolled back, backtest-kit will retry`);
953
- }
954
-
955
- Broker.useBrokerAdapter(
956
- class implements IBroker {
957
-
958
- async waitForInit(): Promise<void> {
959
- await getFuturesExchange();
960
- }
961
-
962
- async onSignalOpenCommit(payload: BrokerSignalOpenPayload): Promise<void> {
963
- const { symbol, cost, priceOpen, priceTakeProfit, priceStopLoss, position } = payload;
964
- const exchange = await getFuturesExchange();
965
-
966
- // Set leverage before entry โ€” ensures consistent leverage regardless of previous session state
967
- await exchange.setLeverage(FUTURES_LEVERAGE, symbol);
968
-
969
- const qty = truncateQty(exchange, symbol, cost / priceOpen);
970
-
971
- // Guard: truncation may produce 0 if cost/price is below lot size
972
- if (qty <= 0) {
973
- throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${priceOpen}`);
974
- }
975
-
976
- const openPrice = parseFloat(exchange.priceToPrecision(symbol, priceOpen));
977
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
978
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
979
- const entrySide = position === "long" ? "buy" : "sell";
980
- const exitSide = position === "long" ? "sell" : "buy";
981
- // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
982
- const positionSide = toPositionSide(position);
983
-
984
- // Entry: no restore needed โ€” position does not exist yet if entry times out
985
- await createLimitOrderAndWait(exchange, symbol, entrySide, qty, openPrice, { positionSide });
986
-
987
- // Post-fill: if TP/SL placement fails, position is open and unprotected โ€” close via market
988
- try {
989
- await exchange.createOrder(symbol, "limit", exitSide, qty, tpPrice, { reduceOnly: true, positionSide });
990
- await exchange.createOrder(symbol, "stop_market", exitSide, qty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
991
- } catch (err) {
992
- await exchange.createOrder(symbol, "market", exitSide, qty, undefined, { reduceOnly: true, positionSide });
993
- throw err;
994
- }
995
- }
996
-
997
- async onSignalCloseCommit(payload: BrokerSignalClosePayload): Promise<void> {
998
- const { symbol, position, currentPrice, priceTakeProfit, priceStopLoss } = payload;
999
- const exchange = await getFuturesExchange();
1000
-
1001
- const openOrders = await exchange.fetchOpenOrders(symbol);
1002
- await cancelAllOrders(exchange, openOrders, symbol);
1003
- await sleep(CANCEL_SETTLE_MS);
1004
-
1005
- const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1006
- const exitSide = position === "long" ? "sell" : "buy";
1007
-
1008
- // Position already closed by SL/TP on exchange โ€” throw so backtest-kit can reconcile
1009
- // the close price via its own mechanism rather than assuming a successful manual close
1010
- if (qty === 0) {
1011
- throw new Error(`SignalClose skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1012
- }
1013
-
1014
- const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1015
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1016
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1017
-
1018
- // reduceOnly: prevents accidental reversal if qty has drift vs real position
1019
- // Restore SL/TP if close times out so position is not left unprotected during retry
1020
- await createLimitOrderAndWait(
1021
- exchange, symbol, exitSide, qty, closePrice,
1022
- { reduceOnly: true },
1023
- { exitSide, tpPrice, slPrice, positionSide: position }
1024
- );
1025
- }
1026
-
1027
- async onPartialProfitCommit(payload: BrokerPartialProfitPayload): Promise<void> {
1028
- const { symbol, percentToClose, currentPrice, position, priceTakeProfit, priceStopLoss } = payload;
1029
- const exchange = await getFuturesExchange();
1030
-
1031
- const openOrders = await exchange.fetchOpenOrders(symbol);
1032
- await cancelAllOrders(exchange, openOrders, symbol);
1033
- await sleep(CANCEL_SETTLE_MS);
1034
-
1035
- const totalQty = await fetchContractsQty(exchange, symbol, position);
1036
-
1037
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1038
- if (totalQty === 0) {
1039
- throw new Error(`PartialProfit skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1040
- }
1041
-
1042
- const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
1043
- const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
1044
- const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1045
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1046
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1047
- const exitSide = position === "long" ? "sell" : "buy";
1048
- const positionSide = toPositionSide(position);
1049
-
1050
- // reduceOnly: prevents accidental reversal if qty has drift vs real position
1051
- // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
1052
- await createLimitOrderAndWait(
1053
- exchange, symbol, exitSide, qty, closePrice,
1054
- { reduceOnly: true },
1055
- { exitSide, tpPrice, slPrice, positionSide: position }
1056
- );
1057
-
1058
- // Restore SL/TP on remaining qty after successful partial close
1059
- if (remainingQty > 0) {
1060
- try {
1061
- await exchange.createOrder(symbol, "limit", exitSide, remainingQty, tpPrice, { reduceOnly: true, positionSide });
1062
- await exchange.createOrder(symbol, "stop_market", exitSide, remainingQty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1063
- } catch (err) {
1064
- // Remaining position is unprotected โ€” close via market
1065
- await exchange.createOrder(symbol, "market", exitSide, remainingQty, undefined, { reduceOnly: true, positionSide });
1066
- throw err;
1067
- }
1068
- }
1069
- }
1070
-
1071
- async onPartialLossCommit(payload: BrokerPartialLossPayload): Promise<void> {
1072
- const { symbol, percentToClose, currentPrice, position, priceTakeProfit, priceStopLoss } = payload;
1073
- const exchange = await getFuturesExchange();
1074
-
1075
- const openOrders = await exchange.fetchOpenOrders(symbol);
1076
- await cancelAllOrders(exchange, openOrders, symbol);
1077
- await sleep(CANCEL_SETTLE_MS);
1078
-
1079
- const totalQty = await fetchContractsQty(exchange, symbol, position);
1080
-
1081
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1082
- if (totalQty === 0) {
1083
- throw new Error(`PartialLoss skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1084
- }
1085
-
1086
- const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
1087
- const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
1088
- const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1089
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1090
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1091
- const exitSide = position === "long" ? "sell" : "buy";
1092
- const positionSide = toPositionSide(position);
1093
-
1094
- // reduceOnly: prevents accidental reversal if qty has drift vs real position
1095
- // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
1096
- await createLimitOrderAndWait(
1097
- exchange, symbol, exitSide, qty, closePrice,
1098
- { reduceOnly: true },
1099
- { exitSide, tpPrice, slPrice, positionSide: position }
1100
- );
1101
-
1102
- // Restore SL/TP on remaining qty after successful partial close
1103
- if (remainingQty > 0) {
1104
- try {
1105
- await exchange.createOrder(symbol, "limit", exitSide, remainingQty, tpPrice, { reduceOnly: true, positionSide });
1106
- await exchange.createOrder(symbol, "stop_market", exitSide, remainingQty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1107
- } catch (err) {
1108
- // Remaining position is unprotected โ€” close via market
1109
- await exchange.createOrder(symbol, "market", exitSide, remainingQty, undefined, { reduceOnly: true, positionSide });
1110
- throw err;
1111
- }
1112
- }
1113
- }
1114
-
1115
- async onTrailingStopCommit(payload: BrokerTrailingStopPayload): Promise<void> {
1116
- const { symbol, newStopLossPrice, position } = payload;
1117
- const exchange = await getFuturesExchange();
1118
-
1119
- // Cancel existing SL order only โ€” filter by reduceOnly to avoid cancelling unrelated orders
1120
- const orders = await exchange.fetchOpenOrders(symbol);
1121
- const slOrder = orders.find((o) =>
1122
- !!o.reduceOnly &&
1123
- ["stop_market", "stop", "STOP_MARKET"].includes(o.type ?? "")
1124
- ) ?? null;
1125
- if (slOrder) {
1126
- await exchange.cancelOrder(slOrder.id, symbol);
1127
- await sleep(CANCEL_SETTLE_MS);
1128
- }
1129
-
1130
- const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1131
- const exitSide = position === "long" ? "sell" : "buy";
1132
-
1133
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1134
- if (qty === 0) {
1135
- throw new Error(`TrailingStop skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1136
- }
1137
-
1138
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
1139
- const positionSide = toPositionSide(position);
1140
-
1141
- // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
1142
- await exchange.createOrder(symbol, "stop_market", exitSide, qty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1143
- }
1144
-
1145
- async onTrailingTakeCommit(payload: BrokerTrailingTakePayload): Promise<void> {
1146
- const { symbol, newTakeProfitPrice, position } = payload;
1147
- const exchange = await getFuturesExchange();
1148
-
1149
- // Cancel existing TP order only โ€” filter by reduceOnly to avoid cancelling unrelated orders
1150
- const orders = await exchange.fetchOpenOrders(symbol);
1151
- const tpOrder = orders.find((o) =>
1152
- !!o.reduceOnly &&
1153
- ["limit", "LIMIT"].includes(o.type ?? "")
1154
- ) ?? null;
1155
- if (tpOrder) {
1156
- await exchange.cancelOrder(tpOrder.id, symbol);
1157
- await sleep(CANCEL_SETTLE_MS);
1158
- }
1159
-
1160
- const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1161
- const exitSide = position === "long" ? "sell" : "buy";
1162
-
1163
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1164
- if (qty === 0) {
1165
- throw new Error(`TrailingTake skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1166
- }
1167
-
1168
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, newTakeProfitPrice));
1169
- const positionSide = toPositionSide(position);
1170
-
1171
- // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
1172
- await exchange.createOrder(symbol, "limit", exitSide, qty, tpPrice, { reduceOnly: true, positionSide });
1173
- }
1174
-
1175
- async onBreakevenCommit(payload: BrokerBreakevenPayload): Promise<void> {
1176
- const { symbol, newStopLossPrice, position } = payload;
1177
- const exchange = await getFuturesExchange();
1178
-
1179
- // Cancel existing SL order only โ€” filter by reduceOnly to avoid cancelling unrelated orders
1180
- const orders = await exchange.fetchOpenOrders(symbol);
1181
- const slOrder = orders.find((o) =>
1182
- !!o.reduceOnly &&
1183
- ["stop_market", "stop", "STOP_MARKET"].includes(o.type ?? "")
1184
- ) ?? null;
1185
- if (slOrder) {
1186
- await exchange.cancelOrder(slOrder.id, symbol);
1187
- await sleep(CANCEL_SETTLE_MS);
1188
- }
1189
-
1190
- const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1191
- const exitSide = position === "long" ? "sell" : "buy";
1192
-
1193
- // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1194
- if (qty === 0) {
1195
- throw new Error(`Breakeven skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1196
- }
1197
-
1198
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
1199
- const positionSide = toPositionSide(position);
1200
-
1201
- // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
1202
- await exchange.createOrder(symbol, "stop_market", exitSide, qty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1203
- }
1204
-
1205
- async onAverageBuyCommit(payload: BrokerAverageBuyPayload): Promise<void> {
1206
- const { symbol, currentPrice, cost, position, priceTakeProfit, priceStopLoss } = payload;
1207
- const exchange = await getFuturesExchange();
1208
-
1209
- // Cancel existing SL/TP first โ€” existing check must happen after cancel+settle
1210
- // to avoid race condition where SL/TP fills between the existence check and cancel
1211
- const openOrders = await exchange.fetchOpenOrders(symbol);
1212
- await cancelAllOrders(exchange, openOrders, symbol);
1213
- await sleep(CANCEL_SETTLE_MS);
1214
-
1215
- // Guard against DCA into a ghost position โ€” checked after cancel so the snapshot is fresh
1216
- const existing = await fetchContractsQty(exchange, symbol, position);
1217
- const minNotional = exchange.markets[symbol].limits?.cost?.min ?? 1;
1218
-
1219
- // Compare notional value rather than raw contracts โ€” avoids float === 0 trap
1220
- // and correctly rejects dust positions left over from previous trades
1221
- if (existing * currentPrice < minNotional) {
1222
- throw new Error(`AverageBuy skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1223
- }
1224
-
1225
- const qty = truncateQty(exchange, symbol, cost / currentPrice);
1226
-
1227
- // Guard: truncation may produce 0 if cost/price is below lot size
1228
- if (qty <= 0) {
1229
- throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${currentPrice}`);
1230
- }
1231
-
1232
- const entryPrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1233
- const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1234
- const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1235
- // positionSide required in hedge mode to add to correct side; ignored in one-way mode
1236
- const positionSide = toPositionSide(position);
1237
- const entrySide = position === "long" ? "buy" : "sell";
1238
- const exitSide = position === "long" ? "sell" : "buy";
1239
-
1240
- // DCA entry: restore SL/TP on existing qty if times out so position is not left unprotected
1241
- await createLimitOrderAndWait(
1242
- exchange, symbol, entrySide, qty, entryPrice,
1243
- { positionSide },
1244
- { exitSide, tpPrice, slPrice, positionSide: position }
1245
- );
1246
-
1247
- // Refetch contracts after fill โ€” existing snapshot is stale after cancel + fill
1248
- const totalQty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1249
-
1250
- // Recreate SL/TP on fresh total qty after successful fill
1251
- try {
1252
- await exchange.createOrder(symbol, "limit", exitSide, totalQty, tpPrice, { reduceOnly: true, positionSide });
1253
- await exchange.createOrder(symbol, "stop_market", exitSide, totalQty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1254
- } catch (err) {
1255
- // Total position is unprotected โ€” close via market
1256
- await exchange.createOrder(symbol, "market", exitSide, totalQty, undefined, { reduceOnly: true, positionSide });
1257
- throw err;
1258
- }
1259
- }
1260
- }
1261
- );
1262
-
1263
- Broker.enable();
1264
- ```
1265
-
1266
- </details>
1267
-
1268
- #### Internals
1269
-
1270
- Signal open/close events are routed automatically via an internal event bus once `Broker.enable()` is called. **No manual wiring needed.** All other operations (`partialProfit`, `trailingStop`, `breakeven`, `averageBuy`) are intercepted explicitly before the corresponding state mutation.
1271
-
1272
- ### ๐Ÿ” How Cron Works
1273
-
1274
- `Cron` is a periodic / fire-once scheduler that runs in **virtual time** โ€” the same time stream your strategies see in backtest mode. Handlers fire on candle-interval boundaries (`1m`, `5m`, `1h`, `1d`, โ€ฆ) and are coordinated across parallel `Backtest.background(symbol, ...)` runs so the same boundary never produces two concurrent invocations.
1275
-
1276
- **Public API:**
1277
- - **`Cron.register({ name, interval?, symbols?, handler })`** โ€” register a job. Returns a disposer. Re-registering the same `name` replaces the previous entry and bumps an internal generation counter (late writes from old handlers are ignored).
1278
- - **`Cron.enable()`** โ€” subscribe `Cron` to the engine's lifecycle subjects (`beforeStart`, `idlePing`, `activePing`, `schedulePing`). Wrapped in `singleshot`; call once at startup.
1279
- - **`Cron.disable()`** โ€” tear down the subscriptions installed by `enable()`. Safe to call multiple times and before `enable()`.
1280
- - **`Cron.unregister(name)`** โ€” remove a registered job.
1281
- - **`Cron.clear(symbol?)`** โ€” clear fire-once marks. `symbol` provided โ†’ fan-out marks for that symbol only; no argument โ†’ all marks. Does **not** touch in-flight handlers.
1282
-
1283
- **Two modes per `interval`:**
1284
- - **Periodic** (`interval: "1h"`) โ€” handler fires once per boundary of that interval.
1285
- - **Fire-once** (`interval` omitted) โ€” handler fires on the first matching tick and never again until `clear()` / `unregister` / re-`register`.
1286
-
1287
- **Two scopes per `symbols`:**
1288
- - **Global** (`symbols` omitted) โ€” handler fires once per boundary across all parallel backtests. First symbol to reach the boundary opens the slot; others await the same promise.
1289
- - **Fan-out** (`symbols: ["BTC", "ETH"]`) โ€” handler fires once per boundary **per whitelisted symbol**. Each symbol has its own slot.
1290
-
1291
- <details>
1292
- <summary>
1293
- The code
1294
- </summary>
1295
-
1296
- ```typescript
1297
- import { Cron, Backtest } from "backtest-kit";
1298
-
1299
- // Global hourly job โ€” fires once per virtual hour across all parallel backtests.
1300
- Cron.register({
1301
- name: "tg-signal-parser",
1302
- interval: "1h",
1303
- handler: async (symbol, when, backtest) => {
1304
- await parseTelegramSignalsToMongo(when);
1305
- },
1306
- });
1307
-
1308
- // Per-symbol fan-out โ€” fires once per hour per whitelisted symbol.
1309
- Cron.register({
1310
- name: "fetch-funding",
1311
- interval: "1h",
1312
- symbols: ["BTCUSDT", "ETHUSDT"],
1313
- handler: async (symbol, when, backtest) => {
1314
- await fetchFundingRate(symbol, when);
1315
- },
1316
- });
1317
-
1318
- // Fire-once warm-up โ€” runs once globally on the very first tick.
1319
- Cron.register({
1320
- name: "warm-cache",
1321
- handler: async (symbol, when, backtest) => {
1322
- await warmupCache();
1323
- },
1324
- });
1325
-
1326
- // Wire Cron to the engine once at startup. After this every strategy tick is
1327
- // forwarded into Cron automatically โ€” no manual listener wiring needed.
1328
- Cron.enable();
1329
-
1330
- for (const symbol of ["BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT", "TRXUSDT"]) {
1331
- Backtest.background(symbol, { strategyName, exchangeName, frameName });
1332
- }
1333
-
1334
- // On shutdown:
1335
- // Cron.disable();
1336
- ```
1337
-
1338
- </details>
1339
-
1340
- #### Internals
1341
-
1342
- `Cron.enable()` subscribes a single `singlerun`-wrapped handler to four lifecycle subjects (`beforeStart`, `idlePing`, `activePing`, `schedulePing`). `singlerun` merges all four streams into one serial queue, so concurrent ticks on the same `(symbol, virtual-minute)` cannot race to open the same slot. Each incoming tick is **base-aligned to the 1-minute boundary** before any further processing โ€” lifecycle pings may carry sub-second jitter, but Cron always reasons in whole minutes.
1343
-
1344
- Coordination keys are built as `${name}:${alignedMs}:${symbol?}:g${generation}`. Parallel backtests that hit the same key share a single in-flight promise (mutex semantics): the first opens the slot and runs the handler, others `await` the same promise and release together. After `.finally()` the slot is removed and the next boundary creates a fresh promise. Fire-once entries additionally record a `_firedOnce` mark on success so subsequent ticks skip them โ€” a failed handler is **not** marked, so it retries on the next tick. The generation suffix isolates re-registrations: a late write from a still-in-flight handler of a previous `register()` carries the old generation and never collides with the new entry.
1345
-
1346
- ### ๐Ÿ” How getCandles Works
1347
-
1348
- backtest-kit uses Node.js `AsyncLocalStorage` to automatically provide
1349
- temporal time context to your strategies.
1350
-
1351
- <details>
1352
- <summary>
1353
- The Math
1354
- </summary>
1355
-
1356
- For a candle with:
1357
- - `timestamp` = candle open time (openTime)
1358
- - `stepMs` = interval duration (e.g., 60000ms for "1m")
1359
- - Candle close time = `timestamp + stepMs`
1360
-
1361
- **Alignment:** All timestamps are aligned down to interval boundary.
1362
- For example, for 15m interval: 00:17 โ†’ 00:15, 00:44 โ†’ 00:30
1363
-
1364
- **Adapter contract:**
1365
- - First candle.timestamp must equal aligned `since`
1366
- - Adapter must return exactly `limit` candles
1367
- - Sequential timestamps: `since + i * stepMs` for i = 0..limit-1
1368
-
1369
- **How `since` is calculated from `when`:**
1370
- - `when` = current execution context time (from AsyncLocalStorage)
1371
- - `alignedWhen` = `Math.floor(when / stepMs) * stepMs` (aligned down to interval boundary)
1372
- - `since` = `alignedWhen - limit * stepMs` (go back `limit` candles from aligned when)
1373
-
1374
- **Boundary semantics (inclusive/exclusive):**
1375
- - `since` is always **inclusive** โ€” first candle has `timestamp === since`
1376
- - Exactly `limit` candles are returned
1377
- - Last candle has `timestamp === since + (limit - 1) * stepMs` โ€” **inclusive**
1378
- - For `getCandles`: `alignedWhen` is **exclusive** โ€” candle at that timestamp is NOT included (it's a pending/incomplete candle)
1379
- - For `getRawCandles`: `eDate` is **exclusive** โ€” candle at that timestamp is NOT included (it's a pending/incomplete candle)
1380
- - For `getNextCandles`: `alignedWhen` is **inclusive** โ€” first candle starts at `alignedWhen` (it's the current candle for backtest, already closed in historical data)
1381
-
1382
- - `getCandles(symbol, interval, limit)` - Returns exactly `limit` candles
1383
- - Aligns `when` down to interval boundary
1384
- - Calculates `since = alignedWhen - limit * stepMs`
1385
- - **since โ€” inclusive**, first candle.timestamp === since
1386
- - **alignedWhen โ€” exclusive**, candle at alignedWhen is NOT returned
1387
- - Range: `[since, alignedWhen)` โ€” half-open interval
1388
- - Example: `getCandles("BTCUSDT", "1m", 100)` returns 100 candles ending before aligned when
1389
-
1390
- - `getNextCandles(symbol, interval, limit)` - Returns exactly `limit` candles (backtest only)
1391
- - Aligns `when` down to interval boundary
1392
- - `since = alignedWhen` (starts from aligned when, going forward)
1393
- - **since โ€” inclusive**, first candle.timestamp === since
1394
- - Range: `[alignedWhen, alignedWhen + limit * stepMs)` โ€” half-open interval
1395
- - Throws error in live mode to prevent look-ahead bias
1396
- - Example: `getNextCandles("BTCUSDT", "1m", 10)` returns next 10 candles starting from aligned when
1397
-
1398
- - `getRawCandles(symbol, interval, limit?, sDate?, eDate?)` - Flexible parameter combinations:
1399
- - `(limit)` - since = alignedWhen - limit * stepMs, range `[since, alignedWhen)`
1400
- - `(limit, sDate)` - since = align(sDate), returns `limit` candles forward, range `[since, since + limit * stepMs)`
1401
- - `(limit, undefined, eDate)` - since = align(eDate) - limit * stepMs, **eDate โ€” exclusive**, range `[since, eDate)`
1402
- - `(undefined, sDate, eDate)` - since = align(sDate), limit calculated from range, **sDate โ€” inclusive, eDate โ€” exclusive**, range `[sDate, eDate)`
1403
- - `(limit, sDate, eDate)` - since = align(sDate), returns `limit` candles, **sDate โ€” inclusive**
1404
- - All combinations respect look-ahead bias protection (eDate/endTime <= when)
1405
-
1406
- **Persistent Cache:**
1407
- - Cache lookup calculates expected timestamps: `since + i * stepMs` for i = 0..limit-1
1408
- - Returns all candles if found, null if any missing (cache miss)
1409
- - Cache and runtime use identical timestamp calculation logic
1410
-
1411
- </details>
1412
-
1413
- #### Candle Timestamp Convention:
1414
-
1415
- According to this `timestamp` of a candle in backtest-kit is exactly the `openTime`, not ~~`closeTime`~~
1416
-
1417
- **Key principles:**
1418
- - All timestamps are aligned down to interval boundary
1419
- - First candle.timestamp must equal aligned `since`
1420
- - Adapter must return exactly `limit` candles
1421
- - Sequential timestamps: `since + i * stepMs`
1422
-
1423
-
1424
- ### ๐Ÿ” How getOrderBook Works
1425
-
1426
- Order book fetching uses the same temporal alignment as candles, but with a configurable time offset window instead of candle intervals.
1427
-
1428
- <details>
1429
- <summary>
1430
- The Math
1431
- </summary>
1432
-
1433
- **Time range calculation:**
1434
- - `when` = current execution context time (from AsyncLocalStorage)
1435
- - `offsetMinutes` = `CC_ORDER_BOOK_TIME_OFFSET_MINUTES` (configurable)
1436
- - `alignedTo` = `Math.floor(when / (offsetMinutes * 60000)) * (offsetMinutes * 60000)`
1437
- - `to` = `alignedTo` (aligned down to offset boundary)
1438
- - `from` = `alignedTo - offsetMinutes * 60000`
1439
-
1440
- **Adapter contract:**
1441
- - `getOrderBook(symbol, depth, from, to, backtest)` is called on the exchange schema
1442
- - `depth` defaults to `CC_ORDER_BOOK_MAX_DEPTH_LEVELS`
1443
- - The `from`/`to` range represents a time window of exactly `offsetMinutes` duration
1444
- - Schema implementation may use the time range (backtest) or ignore it (live trading)
1445
-
1446
- **Example with CC_ORDER_BOOK_TIME_OFFSET_MINUTES = 10:**
1447
- ```
1448
- when = 1704067920000 // 2024-01-01 00:12:00 UTC
1449
- offsetMinutes = 10
1450
- offsetMs = 10 * 60000 // 600000ms
1451
-
1452
- alignedTo = Math.floor(1704067920000 / 600000) * 600000
1453
- = 1704067800000 // 2024-01-01 00:10:00 UTC
1454
-
1455
- to = 1704067800000 // 00:10:00 UTC
1456
- from = 1704067200000 // 00:00:00 UTC
1457
- ```
1458
- </details>
1459
-
1460
- #### Order Book Timestamp Convention:
1461
-
1462
- Unlike candles, most exchanges (e.g. Binance `GET /api/v3/depth`) only expose the **current** order book with no historical query support โ€” for backtest you must provide your own snapshot storage.
1463
-
1464
- **Key principles:**
1465
- - Time range is aligned down to `CC_ORDER_BOOK_TIME_OFFSET_MINUTES` boundary
1466
- - `to` = aligned timestamp, `from` = `to - offsetMinutes * 60000`
1467
- - `depth` defaults to `CC_ORDER_BOOK_MAX_DEPTH_LEVELS`
1468
- - Adapter receives `(symbol, depth, from, to, backtest)` โ€” may ignore `from`/`to` in live mode
1469
-
1470
- ### ๐Ÿ” How getAggregatedTrades Works
1471
-
1472
- Aggregated trades fetching uses the same look-ahead bias protection as candles - `to` is always aligned down to the nearest minute boundary so future trades are never visible to the strategy.
1473
-
1474
- **Key principles:**
1475
- - `to` is always aligned down to the 1-minute boundary โ€” prevents look-ahead bias
1476
- - Without `limit`: returns one full window (`CC_AGGREGATED_TRADES_MAX_MINUTES`)
1477
- - With `limit`: paginates backwards until collected, then slices to most recent `limit`
1478
- - Adapter receives `(symbol, from, to, backtest)` โ€” may ignore `from`/`to` in live mode
1479
-
1480
- <details>
1481
- <summary>
1482
- The Math
1483
- </summary>
1484
-
1485
- **Time range calculation:**
1486
- - `when` = current execution context time (from AsyncLocalStorage)
1487
- - `alignedTo` = `Math.floor(when / 60000) * 60000` (aligned down to 1-minute boundary)
1488
- - `windowMs` = `CC_AGGREGATED_TRADES_MAX_MINUTES * 60000 โˆ’ 60000`
1489
- - `to` = `alignedTo`, `from` = `alignedTo โˆ’ windowMs`
1490
-
1491
- **Without `limit`:** fetches a single window and returns it as-is.
1492
-
1493
- **With `limit`:** paginates backwards in `CC_AGGREGATED_TRADES_MAX_MINUTES` chunks until at least `limit` trades are collected, then slices to the most recent `limit` trades.
1494
-
1495
- **Example with CC_AGGREGATED_TRADES_MAX_MINUTES = 60, limit = 200:**
1496
- ```
1497
- when = 1704067920000 // 2024-01-01 00:12:00 UTC
1498
- alignedTo = 1704067800000 // 2024-01-01 00:12:00 โ†’ aligned to 00:12:00
1499
- windowMs = 59 * 60000 // 3540000ms = 59 minutes
1500
-
1501
- Window 1: from = 00:12:00 โˆ’ 59m = 23:13:00
1502
- to = 00:12:00
1503
- โ†’ got 120 trades โ€” not enough
1504
-
1505
- Window 2: from = 23:13:00 โˆ’ 59m = 22:14:00
1506
- to = 23:13:00
1507
- โ†’ got 100 more โ†’ total 220 trades
1508
-
1509
- result = last 200 of 220 (most recent)
1510
- ```
1511
-
1512
- **Adapter contract:**
1513
- - `getAggregatedTrades(symbol, from, to, backtest)` is called on the exchange schema
1514
- - `from`/`to` are `Date` objects
1515
- - Schema implementation may use the time range (backtest) or ignore it (live trading)
1516
-
1517
- </details>
1518
-
1519
- #### Aggregated Trades Timestamp Convention:
1520
-
1521
- **Compatible with:** [garch](https://www.npmjs.com/package/garch) for volatility modelling and [volume-anomaly](https://www.npmjs.com/package/volume-anomaly) for detecting abnormal trade volume โ€” both accept the same `from`/`to` time range format that `getAggregatedTrades` produces.
1522
-
1523
- ### ๐Ÿ”ฌ Technical Details: Timestamp Alignment
1524
-
1525
- **Why align timestamps to interval boundaries?**
1526
-
1527
- Because candle APIs return data starting from exact interval boundaries:
1528
-
1529
- ```typescript
1530
- // 15-minute interval example:
1531
- when = 1704067920000 // 00:12:00
1532
- step = 15 // 15 minutes
1533
- stepMs = 15 * 60000 // 900000ms
1534
-
1535
- // Alignment: round down to nearest interval boundary
1536
- alignedWhen = Math.floor(when / stepMs) * stepMs
1537
- // = Math.floor(1704067920000 / 900000) * 900000
1538
- // = 1704067200000 (00:00:00)
1539
-
1540
- // Calculate since for 4 candles backwards:
1541
- since = alignedWhen - 4 * stepMs
1542
- // = 1704067200000 - 4 * 900000
1543
- // = 1704063600000 (23:00:00 previous day)
1544
-
1545
- // Expected candles:
1546
- // [0] timestamp = 1704063600000 (23:00)
1547
- // [1] timestamp = 1704064500000 (23:15)
1548
- // [2] timestamp = 1704065400000 (23:30)
1549
- // [3] timestamp = 1704066300000 (23:45)
1550
- ```
1551
-
1552
- **Pending candle exclusion:** The candle at `00:00:00` (alignedWhen) is NOT included in the result. At `when=00:12:00`, this candle covers the period `[00:00, 00:15)` and is still open (pending). Pending candles have incomplete OHLCV data that would distort technical indicators. Only fully closed candles are returned.
1553
-
1554
- **Validation is applied consistently across:**
1555
- - โœ… `getCandles()` - validates first timestamp and count
1556
- - โœ… `getNextCandles()` - validates first timestamp and count
1557
- - โœ… `getRawCandles()` - validates first timestamp and count
1558
- - โœ… Cache read - calculates exact expected timestamps
1559
- - โœ… Cache write - stores validated candles
1560
-
1561
- **Result:** Deterministic candle retrieval with exact timestamp matching.
1562
-
1563
- ### ๐Ÿ• Timezone Warning: Candle Boundaries Are UTC-Based
1564
-
1565
- All candle timestamp alignment uses UTC (Unix epoch). For intervals like `4h`, boundaries are `00:00, 04:00, 08:00, 12:00, 16:00, 20:00 UTC`. If your local timezone offset is not a multiple of the interval, the `since` timestamps will look "uneven" in local time.
1566
-
1567
- For example, in UTC+5 the same 4h candle request logs as:
1568
-
1569
- ```
1570
- since: Sat Sep 20 2025 13:00:00 GMT+0500 โ† looks uneven (13:00)
1571
- since: Sat Sep 20 2025 17:00:00 GMT+0500 โ† looks uneven (17:00)
1572
- since: Sat Sep 20 2025 21:00:00 GMT+0500 โ† looks uneven (21:00)
1573
- since: Sun Sep 21 2025 05:00:00 GMT+0500 โ† looks uneven (05:00)
1574
- ```
1575
-
1576
- But in UTC these are perfectly aligned 4h boundaries:
1577
-
1578
- ```
1579
- since: Sat, 20 Sep 2025 08:00:00 GMT โ† 08:00 UTC โœ“
1580
- since: Sat, 20 Sep 2025 12:00:00 GMT โ† 12:00 UTC โœ“
1581
- since: Sat, 20 Sep 2025 16:00:00 GMT โ† 16:00 UTC โœ“
1582
- since: Sun, 21 Sep 2025 00:00:00 GMT โ† 00:00 UTC โœ“
1583
- ```
1584
-
1585
- Use `toUTCString()` or `toISOString()` in callbacks to see the actual aligned UTC times.
1586
-
1587
- ### ๐Ÿ’ญ What this means:
1588
- - `getCandles()` always returns data UP TO the current backtest timestamp using `async_hooks`
1589
- - Multi-timeframe data is automatically synchronized
1590
- - **Impossible to introduce look-ahead bias** - all time boundaries are enforced
1591
- - Same code works in both backtest and live modes
1592
- - Boundary semantics prevent edge cases in signal generation
1593
-
1594
-
1595
- ## ๐Ÿง  Two Ways to Run the Engine
1596
-
1597
- Backtest Kit exposes the same runtime in two equivalent forms. Both approaches use **the same engine and guarantees** - only the consumption model differs.
1598
-
1599
- ### 1๏ธโƒฃ Event-driven (background execution)
1600
-
1601
- Suitable for production bots, monitoring, and long-running processes.
1602
-
1603
- ```typescript
1604
- Backtest.background('BTCUSDT', config);
1605
-
1606
- listenSignalBacktest(event => { /* handle signals */ });
1607
- listenDoneBacktest(event => { /* finalize / dump report */ });
1608
- ```
1609
-
1610
- ### 2๏ธโƒฃ Async Iterator (pull-based execution)
1611
-
1612
- Suitable for research, scripting, testing, and LLM agents.
1613
-
1614
- ```typescript
1615
- for await (const event of Backtest.run('BTCUSDT', config)) {
1616
- // signal | trade | progress | done
1617
- }
1618
- ```
1619
-
1620
- ## โš”๏ธ Think of it as...
1621
-
1622
- **Open-source QuantConnect/MetaTrader without the vendor lock-in**
1623
-
1624
- Unlike cloud-based platforms, backtest-kit runs entirely in your environment. You own the entire stack from data ingestion to live execution. In addition to Ollama, you can use [neural-trader](https://www.npmjs.com/package/neural-trader) in `getSignal` function or any other third party library
1625
-
1626
- - No C#/C++ required - pure TypeScript/JavaScript
1627
- - Self-hosted - your code, your data, your infrastructure
1628
- - No platform fees or hidden costs
1629
- - Full control over execution and data sources
1630
- - [GUI](https://npmjs.com/package/@backtest-kit/ui) for visualization and monitoring
1631
-
1632
- ## ๐ŸŒ Ecosystem
1633
-
1634
- The `backtest-kit` ecosystem extends beyond the core library, offering complementary packages and tools to enhance your trading system development experience:
1635
-
1636
-
1637
- ### @backtest-kit/cli
1638
-
1639
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/cli)** ๐Ÿ“Ÿ
1640
-
1641
- The **@backtest-kit/cli** package is a zero-boilerplate CLI runner for backtest-kit strategies. Point it at your strategy file and run backtests, paper trading, or live bots โ€” no infrastructure code required.
1642
-
1643
- #### Key Features
1644
- - ๐Ÿš€ **Zero Config**: Run a backtest with one command โ€” no setup code needed
1645
- - ๐Ÿ”„ **Three Modes**: `--backtest`, `--paper`, `--live` with graceful SIGINT shutdown
1646
- - ๐Ÿ’พ **Auto Cache**: Warms OHLCV candle cache for all intervals before the backtest starts
1647
- - ๐ŸŒ **Web Dashboard**: Launch `@backtest-kit/ui` with a single `--ui` flag
1648
- - ๐Ÿ“ฌ **Telegram Alerts**: Formatted trade notifications with price charts via `--telegram`
1649
- - ๐Ÿ—‚๏ธ **Monorepo Ready**: Each strategy's `dump/`, `modules/`, and `template/` are automatically isolated by entry point directory
1650
-
1651
- #### Use Case
1652
- The fastest way to run any backtest-kit strategy from the command line. Instead of writing boilerplate for storage, notifications, candle caching, and signal logging, add one dependency and wire up your `package.json` scripts. Works equally well for a single-strategy project or a monorepo with dozens of strategies in separate subdirectories.
1653
-
1654
- #### Get Started
1655
- ```bash
1656
- npx -y @backtest-kit/cli --init
1657
- ```
1658
-
1659
-
1660
- ### @backtest-kit/pinets
1661
-
1662
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/pinets)** ๐Ÿ“œ
1663
-
1664
- The **@backtest-kit/pinets** package lets you run TradingView Pine Script strategies directly in Node.js. Port your existing Pine Script indicators to backtest-kit with zero rewrite using the [PineTS](https://github.com/QuantForgeOrg/PineTS) runtime.
1665
-
1666
- #### Key Features
1667
- - ๐Ÿ“œ **Pine Script v5/v6**: Native TradingView syntax with 1:1 compatibility
1668
- - ๐ŸŽฏ **60+ Indicators**: SMA, EMA, RSI, MACD, Bollinger Bands, ATR, Stochastic built-in
1669
- - ๐Ÿ“ **File or Code**: Load `.pine` files or pass code strings directly
1670
- - ๐Ÿ—บ๏ธ **Plot Extraction**: Flexible mapping from Pine `plot()` outputs to structured signals
1671
- - โšก **Cached Execution**: Memoized file reads for repeated strategy runs
1672
-
1673
- #### Use Case
1674
- Perfect for traders who already have working TradingView strategies. Instead of rewriting your Pine Script logic in JavaScript, simply copy your `.pine` file and use `getSignal()` to extract trading signals. Works seamlessly with backtest-kit's temporal context - no look-ahead bias possible.
1675
-
1676
- #### Get Started
1677
- ```bash
1678
- npm install @backtest-kit/pinets pinets backtest-kit
1679
- ```
1680
-
1681
-
1682
- ### @backtest-kit/graph
1683
-
1684
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/graph)** ๐Ÿ”—
1685
-
1686
- The **@backtest-kit/graph** package lets you compose backtest-kit computations as a typed directed acyclic graph (DAG). Define source nodes that fetch market data and output nodes that compute derived values โ€” then resolve the whole graph in topological order with automatic parallelism.
1687
-
1688
- #### Key Features
1689
- - ๐Ÿ”Œ **DAG Execution**: Nodes are resolved bottom-up in topological order with `Promise.all` parallelism
1690
- - ๐Ÿ”’ **Type-Safe Values**: TypeScript infers the return type of every node through the graph via generics
1691
- - ๐Ÿงฑ **Two APIs**: Low-level `INode` for runtime/storage, high-level `sourceNode` + `outputNode` builders for authoring
1692
- - ๐Ÿ’พ **DB-Ready Serialization**: `serialize` / `deserialize` convert the graph to a flat `IFlatNode[]` list with `id` / `nodeIds`
1693
- - ๐ŸŒ **Context-Aware Fetch**: `sourceNode` receives `(symbol, when, exchangeName)` from the execution context automatically
1694
-
1695
- #### Use Case
1696
- Perfect for multi-timeframe strategies where multiple Pine Script or indicator computations must be combined. Instead of manually chaining async calls, define each computation as a node and let the graph resolve dependencies in parallel. Adding a new filter or timeframe requires no changes to the existing wiring.
1697
-
1698
- #### Get Started
1699
- ```bash
1700
- npm install @backtest-kit/graph backtest-kit
1701
- ```
1702
-
1703
-
1704
- ### @backtest-kit/ui
1705
-
1706
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/ui)** ๐Ÿ“Š
1707
-
1708
- The **@backtest-kit/ui** package is a full-stack UI framework for visualizing cryptocurrency trading signals, backtests, and real-time market data. Combines a Node.js backend server with a React dashboard - all in one package.
1709
-
1710
- #### Key Features
1711
- - ๐Ÿ“ˆ **Interactive Charts**: Candlestick visualization with Lightweight Charts (1m, 15m, 1h timeframes)
1712
- - ๐ŸŽฏ **Signal Tracking**: View opened, closed, scheduled, and cancelled signals with full details
1713
- - ๐Ÿ“Š **Risk Analysis**: Monitor risk rejections and position management
1714
- - ๐Ÿ”” **Notifications**: Real-time notification system for all trading events
1715
- - ๐Ÿ’น **Trailing & Breakeven**: Visualize trailing stop/take and breakeven events
1716
- - ๐ŸŽจ **Material Design**: Beautiful UI with MUI 5 and Mantine components
1717
-
1718
- #### Use Case
1719
- Perfect for monitoring your trading bots in production. Instead of building custom dashboards, `@backtest-kit/ui` provides a complete visualization layer out of the box. Each signal view includes detailed information forms, multi-timeframe candlestick charts, and JSON export for all data.
1720
-
1721
- #### Get Started
1722
- ```bash
1723
- npm install @backtest-kit/ui backtest-kit ccxt
1724
- ```
1725
-
1726
-
1727
- ### @backtest-kit/mongo
1728
-
1729
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/mongo)** ๐Ÿ’พ
1730
-
1731
- The **@backtest-kit/mongo** package replaces the default file-based `./dump/` storage with MongoDB as the source of truth and Redis as an O(1) lookup cache. All 15 `IPersist*Instance` contracts from backtest-kit are implemented โ€” strategy code stays unchanged.
1732
-
1733
- #### Key Features
1734
- - ๐Ÿ—„๏ธ **MongoDB Backend**: All 15 persistence adapters implemented with Mongoose and unique compound indexes
1735
- - โšก **O(1) Reads via Redis**: Every context-key lookup goes through ioredis โ€” one `GET` + one `findById`, no B-tree scans
1736
- - ๐Ÿ”’ **Atomic Writes**: `findOneAndUpdate` with `upsert: true` guarantees read-after-write correctness with no race conditions
1737
- - ๐Ÿ›ก๏ธ **Look-Ahead Bias Protection**: Adapters that affect signal logic store the simulation timestamp so backtest-kit can enforce temporal correctness
1738
- - ๐Ÿชฆ **Soft Delete**: Measure, Interval, and Memory records carry a `removed` flag instead of being physically deleted
1739
- - ๐Ÿ”Œ **Zero Strategy Changes**: Drop `setup()` into your entry point, everything else stays the same
1740
-
1741
- #### Use Case
1742
- Perfect for production deployments where the default file-based storage is a bottleneck or a reliability concern. During backtests, backtest-kit performs thousands of context-keyed reads per second โ€” Redis eliminates the per-request B-tree traversal and makes repeated reads effectively free. MongoDB provides durability, atomic upserts, and a queryable signal history that survives process restarts.
1743
-
1744
- #### Get Started
1745
- ```bash
1746
- npm install @backtest-kit/mongo backtest-kit mongoose ioredis
1747
- ```
1748
-
1749
-
1750
- ### @backtest-kit/ollama
1751
-
1752
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/ollama)** ๐Ÿค–
1753
-
1754
- The **@backtest-kit/ollama** package is a multi-provider LLM inference library that supports 10+ providers including OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, and Ollama with unified API and automatic token rotation.
1755
-
1756
- #### Key Features
1757
- - ๐Ÿ”Œ **10+ LLM Providers**: OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, Ollama
1758
- - ๐Ÿ”„ **Token Rotation**: Automatic API key rotation for Ollama (others throw clear errors)
1759
- - ๐ŸŽฏ **Structured Output**: Enforced JSON schema for trading signals (position, price levels, risk notes)
1760
- - ๐Ÿ”‘ **Flexible Auth**: Context-based API keys or environment variables
1761
- - โšก **Unified API**: Single interface across all providers
1762
- - ๐Ÿ“Š **Trading-First**: Built for backtest-kit with position sizing and risk management
1763
-
1764
- #### Use Case
1765
- Ideal for building multi-provider LLM strategies with fallback chains and ensemble predictions. The package returns structured trading signals with validated TP/SL levels, making it perfect for use in `getSignal` functions. Supports both backtest and live trading modes.
1766
-
1767
- #### Get Started
1768
- ```bash
1769
- npm install @backtest-kit/ollama agent-swarm-kit backtest-kit
1770
- ```
1771
-
1772
-
1773
- ### @backtest-kit/signals
1774
-
1775
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/signals)** ๐Ÿ“Š
1776
-
1777
- The **@backtest-kit/signals** package is a technical analysis and trading signal generation library designed for AI-powered trading systems. It computes 50+ indicators across 4 timeframes and generates markdown reports optimized for LLM consumption.
1778
-
1779
- #### Key Features
1780
- - ๐Ÿ“ˆ **Multi-Timeframe Analysis**: 1m, 15m, 30m, 1h with synchronized indicator computation
1781
- - ๐ŸŽฏ **50+ Technical Indicators**: RSI, MACD, Bollinger Bands, Stochastic, ADX, ATR, CCI, Fibonacci, Support/Resistance
1782
- - ๐Ÿ“Š **Order Book Analysis**: Bid/ask depth, spread, liquidity imbalance, top 20 levels
1783
- - ๐Ÿค– **AI-Ready Output**: Markdown reports formatted for LLM context injection
1784
- - โšก **Performance Optimized**: Intelligent caching with configurable TTL per timeframe
1785
-
1786
- #### Use Case
1787
- Perfect for injecting comprehensive market context into your LLM-powered strategies. Instead of manually calculating indicators, `@backtest-kit/signals` provides a single function call that adds all technical analysis to your message context. Works seamlessly with `getSignal` function in backtest-kit strategies.
1788
-
1789
- #### Get Started
1790
- ```bash
1791
- npm install @backtest-kit/signals backtest-kit
1792
- ```
1793
-
1794
-
1795
- ### @backtest-kit/sidekick
1796
-
1797
- > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/sidekick)** ๐Ÿš€
1798
-
1799
- The **@backtest-kit/sidekick** package scaffolds a project where **all wiring is visible and editable** in your project files โ€” exchange adapter, frame definitions, risk rules, strategy logic, and the runner script. Think of it as the **eject** of `@backtest-kit/cli --init`: instead of the boilerplate being hidden inside the CLI package, it lives directly in your project.
1800
-
1801
- #### Key Features
1802
- - ๐Ÿš€ **Zero Config**: Get started with one command - no setup required
1803
- - ๐Ÿ“ฆ **Complete Template**: Includes backtest strategy, risk management, and LLM integration
1804
- - ๐Ÿค– **AI-Powered**: Pre-configured with DeepSeek, Claude, and GPT-5 fallback chain
1805
- - ๐Ÿ“Š **Technical Analysis**: Built-in 50+ indicators via @backtest-kit/signals
1806
- - ๐Ÿ”‘ **Environment Setup**: Auto-generated .env with all API key placeholders
1807
- - ๐Ÿ“ **Best Practices**: Production-ready code structure with examples
1808
-
1809
- #### Use Case
1810
- The fastest way to bootstrap a new trading bot project. Instead of manually setting up dependencies, configurations, and boilerplate code, simply run one command and get a working project with LLM-powered strategy, multi-timeframe technical analysis, and risk management validation.
1811
-
1812
- #### Get Started
1813
- ```bash
1814
- npx -y @backtest-kit/sidekick my-trading-bot
1815
- cd my-trading-bot
1816
- npm start
1817
- ```
1818
-
1819
-
1820
- ## ๐Ÿ‘ช Community
1821
-
1822
- ### backtest-monorepo-parallel
1823
-
1824
- > **[Explore on GitHub](https://github.com/backtest-kit/backtest-monorepo-parallel)** ๐ŸŽ๏ธ
1825
-
1826
- The **backtest-monorepo-parallel** repository is a TypeScript monorepo template that runs **9 symbols in parallel** in a single Node process on top of shared Mongo + Redis infrastructure, with a self-enforcement runtime that exposes the workspace DI container to `./content/` strategy files. No wiring, no bundler hooks, no strategy-author changes.
1827
-
1828
- #### Key Features
1829
- - โšก **~6 300ร— Real-Time Aggregate**: 9 symbols ร— ~703ร— per-symbol replay speed, ~103 events/sec in the hot `listenActivePing โ†’ commitAverageBuy` loop on a commodity i5-13420H laptop
1830
- - ๐Ÿงต **Single-Process Concurrency**: All 9 `Backtest.background(...)` contexts share one event loop, one Mongo pool, one Redis pool โ€” no IPC, no fork overhead
1831
- - ๐Ÿ’‰ **DI Surface**: Workspace services typed via rolled-up `types.d.ts` and reachable from strategy files at evaluation time
1832
- - ๐Ÿ—‚๏ธ **Mode A / Mode B**: `--entry` flag toggles between parallel runner (`CC_SYMBOL_LIST` fan-out) and single-strategy CLI mode
1833
- - ๐Ÿงฉ **Linear Scaling Recipe**: Adding a service = +1 file, +1 symbol, +1 provider, +1 ioc entry โ€” no churn under `./content/`
1834
-
1835
- #### Use Case
1836
- Use when you need to backtest many symbols concurrently against the same strategy without spawning subprocesses, and want a scaffold where new services, collections, and Redis caches drop in alongside existing ones without restructuring. Ideal as the starting point for a production parallel-symbol backtesting setup.
1837
-
1838
- #### Get Started
1839
- ```bash
1840
- git clone https://github.com/backtest-kit/backtest-monorepo-parallel.git
1841
- ```
1842
-
1843
-
1844
- ### backtest-ollama-crontab
1845
-
1846
- > **[Explore on GitHub](https://github.com/backtest-kit/backtest-ollama-crontab)** ๐Ÿ 
1847
-
1848
- The **backtest-ollama-crontab** repository is a TypeScript monorepo template that wires a cloud/local **Ollama** into a trading-signal pipeline as a risk filter, with a **15-minute crontab** ingesting signals from any public Telegram channel. The **same code runs in both live and backtest modes** โ€” the crontab re-polls live and pulls the entire frame at startup in backtest.
1849
-
1850
- #### Key Features
1851
- - ๐Ÿค– **Local/Cloud LLM Risk Filter**: Per-signal verdict from local Ollama (`gpt-oss` quantized) returning `riskAction: "skip" | "follow"`, with empirical rules embedded in the system prompt and tunable without recompiling packages
1852
- - โฐ **Crontab-Driven Ingestion**: `Cron.register(..., interval: "15m")` for live re-polling of the Telegram channel, plus a fire-once `Cron.register(...)` (no `interval`) for backtest-time bulk prepare โ€” same code path in both modes
1853
- - ๐Ÿ“ก **Telegram MTProto Crawler**: QR-code session auth, `iterMessages` pull from any public channel into a `parser-items` Mongo collection, regex extraction of `direction / entry / targets / stoploss` into `screen-items`
1854
- - ๐Ÿง  **Outline-Based Risk Logic**: Risk outline ingests 1m/15m candles + a pre-computed metrics packet (`avgRangePct`, `momentum24hPct`) and produces a zod-validated verdict consumed by the strategy
1855
- - ๐Ÿ“ˆ **Reproducible Backtest Comparison**: same parsed-signal set, two backtests side-by-side โ€” **+52.22% โ†’ +68.90%** total PNL, Sharpe **+0.309 โ†’ +0.512**, winrate **68% โ†’ 82%**, profit factor **2.73 โ†’ 6.37** with the LLM gate enabled
1856
-
1857
- #### Use Case
1858
- Reference for integrating any local LLM into a backtest-kit pipeline as a signal filter, and for combining periodic crontab pulls (live) with one-shot bulk prepare (backtest) via the same `Cron.register` API.
1859
-
1860
- #### Get Started
1861
- ```bash
1862
- git clone https://github.com/backtest-kit/backtest-ollama-crontab.git
1863
- ```
1864
-
1865
-
1866
- ### backtest-kit-redis-mongo-docker
1867
-
1868
- > **[Explore on GitHub](https://github.com/backtest-kit/backtest-kit-redis-mongo-docker)** ๐Ÿณ
1869
-
1870
- The **backtest-kit-redis-mongo-docker** repository is a production-grade integration that replaces the default file-based `./dump/` persistence with **MongoDB** as the source of truth and **Redis** as an O(1) lookup cache, packaged with `docker-compose` for one-command deploys.
1871
-
1872
- #### Key Features
1873
- - ๐Ÿ—‚๏ธ **15 Persist Adapters**: Full implementation of every `IPersist*Instance` contract (Candle, Signal, Schedule, Risk, Partial, Breakeven, Storage, Notification, Log, Measure, Interval, Memory, Recent, State, Session) on top of MongoDB + Redis
1874
- - โš›๏ธ **Atomic Read-After-Write**: Single-round-trip `findOneAndUpdate` with unique compound indexes โ€” no E11000 leaks under concurrent writes
1875
- - โšก **Redis O(1) Cache**: Per-domain `*CacheService` over `ioredis` for context-key โ†’ id lookups; cache miss falls back to Mongo and backfills automatically
1876
- - ๐Ÿ›ก๏ธ **Look-Ahead Bias Protection**: Indexed `when: Number` column on every signal-affecting schema, fed by backtest-kit 9.0+'s `when: Date` adapter argument
1877
- - ๐Ÿณ **Docker Compose Stack**: Separate compose files for Mongo and Redis plus a main container with networks; configurable via `CC_MONGO_CONNECTION_STRING` / `CC_REDIS_*` env vars
1878
-
1879
- #### Use Case
1880
- Drop-in persistence upgrade for any backtest-kit project that outgrows the default file-based `./dump/` layout โ€” strategy code, runners, and the CLI entry point stay unchanged. Use it when you need durable storage, concurrent-safe writes, fast restart recovery, or a containerized deployment for live and paper trading.
1881
-
1882
- #### Get Started
1883
- ```bash
1884
- git clone https://github.com/backtest-kit/backtest-kit-redis-mongo-docker.git
1885
- ```
1886
-
1887
-
1888
- ### backtest-kit-skills
1889
-
1890
- > **[Explore on GitHub](https://github.com/backtest-kit/backtest-kit-skills)** ๐Ÿค–
1891
-
1892
- The **backtest-kit-skills** repository is a Claude Code agent skill and Mintlify documentation source for the backtest-kit framework โ€” AI-assisted strategy writing, debugging help, and full API reference in one place.
1893
-
1894
- #### Key Features
1895
- - ๐Ÿค– **Claude Code Skill**: Installed under `~/.claude/skills/backtest-kit/` โ€” strategy generation, debugging, and API reference
1896
- - ๐Ÿ“– **Mintlify Docs**: Full documentation site runnable locally
1897
- - ๐ŸŽฏ **Strategy Generation**: Complete TypeScript files with all schema registrations and runner setup
1898
- - ๐Ÿ› **Debugging Help**: Catches common mistakes (missing `await`, wrong TP/SL direction, top-level commit calls)
1899
- - ๐Ÿ“š **API Reference**: All schemas, commit functions, event listeners, LLM integration, graph pipelines, and persistence adapters
1900
-
1901
- #### Use Case
1902
- Install the skill once and get AI-assisted backtest-kit development inside Claude Code. The skill knows the full API surface โ€” schemas, commit functions, event listeners, broker adapters โ€” so you can describe what you want in plain language and get working TypeScript strategy code.
1903
-
1904
- #### Get Started
1905
- ```bash
1906
- npx skills add https://github.com/backtest-kit/backtest-kit-skills
1907
- ```
1908
-
1909
-
1910
- ### uzse-backtest-app
1911
-
1912
- > **[Explore on GitHub](https://github.com/backtest-kit/uzse-backtest-app)** ๐Ÿ“ˆ
1913
-
1914
- The **uzse-backtest-app** repository is a reference implementation for running Pine Script strategies on regional stock exchanges not available on TradingView (UZSE, MSE, DSE, and others). It downloads raw trade history, builds Japanese candlesticks, and feeds them into backtest-kit via a custom MongoDB exchange adapter.
1915
-
1916
- #### Key Features
1917
- - ๐ŸŒ **Off-TradingView Markets**: Works with any exchange that exposes trade history โ€” no TradingView dependency
1918
- - ๐Ÿ•ฏ๏ธ **Candle Builder**: Aggregates raw trades into 1m candles, fills intraday and non-trading day gaps, builds higher timeframes up to `1d`
1919
- - ๐Ÿ—„๏ธ **MongoDB Backend**: Idempotent import with unique index โ€” re-runs never create duplicates
1920
- - ๐Ÿ”Œ **Custom Exchange Adapter**: Connects MongoDB candles to backtest-kit via `addExchangeSchema`
1921
- - ๐Ÿ“œ **Pine Script Support**: Full `@backtest-kit/pinets` integration โ€” run any Pine Script v5/v6 indicator on local market data
1922
-
1923
- #### Use Case
1924
- Perfect for traders working with emerging or regional markets absent from TradingView. Download trade history, build candles once, then use the full backtest-kit + Pine Script toolchain for backtesting and live signal generation โ€” with no dependency on any third-party charting platform.
1925
-
1926
- #### Get Started
1927
- ```bash
1928
- git clone https://github.com/backtest-kit/uzse-backtest-app.git
1929
- ```
1930
-
1931
- ## ๐Ÿงฉ Strategy Examples
1932
-
1933
- #### ๐Ÿง  Neural Network Strategy (Oct 2021)
1934
-
1935
- > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/oct_2021.strategy)
1936
-
1937
- Trains a feed-forward `TensorFlow` neural network (8โ†’6โ†’4โ†’1 architecture) every 8 hours to predict where the next candle will close within its high-low range. When current price is below predicted price, opens a LONG with 1% trailing take-profit.
1938
-
1939
- #### ๐ŸŒฒ Pine Script Range Breakout (Dec 2025)
1940
-
1941
- > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/dec_2025.strategy)
1942
-
1943
- Runs `btc_dec2025_range.pine` on 1h candles via `@backtest-kit/pinets`, extracting Bollinger Bands, range boundaries, and volume spikes. Signals fire only on confirmed breakouts when price hasn't already moved past the signal close.
1944
-
1945
- #### ๐Ÿ”ช Signal Inversion Strategy (Jan 2026)
1946
-
1947
- > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/jan_2026.strategy)
1948
-
1949
- The strategy takes published signals from a real Telegram crypto channel (Crypto Yoda), enters at the same price zone and timestamp, but **inverts the direction** and uses the liquidity of the crowd that blindly follows the recommendation regardless of the contents of the order book.
1950
-
1951
- #### ๐Ÿ“ฐ AI News Sentiment (Feb 2026)
1952
-
1953
- > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/feb_2026.strategy)
1954
-
1955
- Every 4-8 hours, fetches live crypto/macro news via Tavily, passes headlines to Ollama (local LLM), and opens positions based on `bullish`/`bearish`/`wait` forecasts. Conflicting signals flip positions mid-trade. Achieved +16.99% during a -16.4% month.
1956
-
1957
- #### ๐Ÿช‚ SHORT DCA Ladder (Mar 2026)
1958
-
1959
- > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/mar_2026.strategy)
1960
-
1961
- Opens a SHORT on every pending signal, then adds rungs (up to 10) whenever price spikes upward outside a ยฑ1-5% band around last entry. Closes at 0.5% blended profit.
1962
-
1963
- #### ๐Ÿง— LONG DCA Ladder (Apr 2026)
1964
-
1965
- > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/apr_2026.strategy)
1966
-
1967
- Same mechanics as SHORT version but LONG-biased with 3% profit target. Deployed 2.4 entries per trade on average, achieved +67.85% PNL on deployed capital with improved percentage drawdown (-2.59% vs -3.99% without DCA).
1968
-
1969
- #### ๐Ÿ Python EMA Crossover (Feb 2021)
1970
-
1971
- > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/feb_2021.strategy)
1972
-
1973
- Python-based (WASI) strategy that uses EMA(9) and EMA(21) crossover signals executed via WebAssembly. Trades trigger when fast EMA crosses slow EMA, confirmed by 4h range midpoint.
1974
-
1975
- ## ๐Ÿ‘จโ€๐Ÿ’ผ Commercial Support
1976
-
1977
- > **[TheOneTrade](https://theonetrade.github.io)** ๐Ÿ’ผ
1978
-
1979
- **TheOneTrade** is the commercial vendor behind backtest-kit, providing paid support, custom strategy development, managed accounts, team training, and enterprise licensing. Contact for SLAs, private features, or quant team engagements that fall outside the MIT-licensed open-source scope.
1980
-
1981
- ## ๐Ÿค– Are you a robot?
1982
-
1983
- **For language models**: Read extended description in [./LLMs.md](./LLMs.md)
1984
-
1985
- ## โœ… Tested & Reliable
1986
-
1987
- 775+ tests cover validation, recovery, reports, and events.
1988
-
1989
- ## ๐Ÿค Contribute
1990
-
1991
- Fork/PR on [GitHub](https://github.com/tripolskypetr/backtest-kit).
1992
-
1993
- ## ๐Ÿ“œ License
1994
-
1995
- MIT ยฉ [tripolskypetr](https://github.com/tripolskypetr)
1996
-
1
+ <img src="https://github.com/tripolskypetr/backtest-kit/raw/refs/heads/master/assets/consciousness.svg" height="45px" align="right">
2
+
3
+ # ๐Ÿงฟ Backtest Kit
4
+
5
+ > A TypeScript framework for backtesting and live trading strategies on multi-asset, crypto, forex or [DEX (peer-to-peer marketplace)](https://en.wikipedia.org/wiki/Decentralized_finance#Decentralized_exchanges), spot, futures with crash-safe persistence, signal validation, and AI optimization.
6
+
7
+ ![screenshot](https://raw.githubusercontent.com/tripolskypetr/backtest-kit/HEAD/assets/screenshots/screenshot16.png)
8
+
9
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/tripolskypetr/backtest-kit)
10
+ [![npm](https://img.shields.io/npm/v/backtest-kit.svg?style=flat-square)](https://npmjs.org/package/backtest-kit)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue)]()
12
+ [![Build](https://github.com/tripolskypetr/backtest-kit/actions/workflows/webpack.yml/badge.svg)](https://github.com/tripolskypetr/backtest-kit/actions/workflows/webpack.yml)
13
+
14
+ Build reliable trading systems: backtest on historical data, deploy live bots with recovery, and optimize strategies using LLMs like Ollama.
15
+
16
+ ๐Ÿ“š **[API Reference](https://backtest-kit.github.io/documents/example_02_first_backtest.html)** | ๐ŸŒŸ **[Quick Start](https://github.com/tripolskypetr/backtest-kit/tree/master/example)** | **๐Ÿ“ฐ [Article](https://backtest-kit.github.io/documents/article_07_ai_news_trading_signals.html)**
17
+
18
+ ## ๐Ÿš€ Quick Start
19
+
20
+ > **New to backtest-kit?** The fastest way to get a real, production-ready setup is to clone the [reference implementation](https://github.com/tripolskypetr/backtest-kit/tree/master/example) โ€” a fully working news-sentiment AI trading system with LLM forecasting, multi-timeframe data, and a documented February 2026 backtest. Start there instead of from scratch.
21
+
22
+ ### ๐ŸŽฏ The Casual Way: CLI Init
23
+
24
+ > **Minimal scaffold โ€” all boilerplate stays inside `@backtest-kit/cli`:**
25
+
26
+ ```bash
27
+ npx @backtest-kit/cli --init --output backtest-kit-project
28
+ cd backtest-kit-project
29
+ npm install
30
+ npm start
31
+ ```
32
+
33
+ The generated project contains only your strategy files. There is no bootstrap, exchange registration, or runner code to maintain โ€” all of that lives inside `@backtest-kit/cli` and is invoked via `npm start`. Library documentation is fetched automatically into `docs/lib/` on init.
34
+
35
+ ### ๐Ÿ—๏ธ Alternative: Sidekick CLI
36
+
37
+ > **Full-control scaffold โ€” all wiring is in your project files:**
38
+
39
+ ```bash
40
+ npx -y @backtest-kit/sidekick my-trading-bot
41
+ cd my-trading-bot
42
+ npm start
43
+ ```
44
+
45
+ Sidekick generates a project where the exchange adapter, frame definitions, risk rules, strategy logic, and runner script all live as editable source files inside the project. Use it when you need full visibility and control over every part of the setup.
46
+
47
+ ### ๐Ÿณ Running in Docker
48
+
49
+ > **Automatic restarts โ€” Zero-downtime trading:**
50
+
51
+ ```bash
52
+ npx @backtest-kit/cli --docker
53
+ cd backtest-kit-docker
54
+ MODE=live SYMBOL=TRXUSDT STRATEGY_FILE=./content/feb_2026/feb_2026.strategy.ts docker-compose up -d
55
+ docker-compose logs -f
56
+ ```
57
+
58
+ CLI can create a ready-to-use Docker workspace: self-contained directory with `docker-compose.yaml` and a strategy entry point. CLI supports [Multiple Symbol in Parallel](https://www.npmjs.com/package/@backtest-kit/cli#-multiple-symbol-parallel) for powerusers.
59
+
60
+ ### ๐Ÿ“ฆ Manual Installation
61
+
62
+ > **Want to see the code?** ๐Ÿ‘‰ [Demo app](https://github.com/tripolskypetr/backtest-kit/tree/master/example) ๐Ÿ‘ˆ
63
+
64
+ ```bash
65
+ npm install backtest-kit ccxt ollama uuid
66
+ ```
67
+
68
+ Install the core library and peer dependencies manually. Use this approach when integrating backtest-kit into an existing project or when you need full control over your package setup.
69
+
70
+ ## โœจ Why Choose Backtest Kit?
71
+
72
+ - ๐Ÿš€ **Production-Ready**: Seamless switch between backtest/live modes; identical code across environments.
73
+ - ๐Ÿ’พ **Crash-Safe**: Atomic persistence recovers states after crashes, preventing duplicates or losses.
74
+ - โœ… **Validation**: Checks signals for TP/SL logic, risk/reward ratios, whipsaw protection and portfolio limits.
75
+ - ๐Ÿ”„ **Efficient Execution**: Streaming architecture for large datasets; VWAP pricing for realism.
76
+ - ๐Ÿค– **AI Integration**: LLM-powered strategy generation (Optimizer) with multi-timeframe analysis.
77
+ - ๐Ÿ“Š **Reports & Metrics**: Auto Markdown reports with PNL, Sharpe Ratio, win rate, and more.
78
+ - ๐Ÿ“ **Portfolio Heatmap**: Cross-symbol portfolio with Pooled Sharpe, Sortino & Calmar Ratio, Recovery Factor, Expectancy and other measures
79
+ - ๐Ÿ›ก๏ธ **Risk Management**: Custom rules for position limits, time windows, and multi-strategy coordination.
80
+ - ๐Ÿ”Œ **Pluggable**: Custom data sources (CCXT), persistence (file/Redis), and sizing calculators.
81
+ - ๐Ÿ—ƒ๏ธ **Transactional Live Orders**: Broker adapter intercepts every trade mutation before internal state changes โ€” exchange rejection rolls back the operation atomically.
82
+ - โฐ **Built-in Crontab**: Register periodic or fire-once jobs that fire on virtual-time boundaries with singleshot coordination across parallel backtests โ€” one handler invocation per boundary, no double-fires.
83
+ - ๐Ÿงช **Tested**: 775+ unit/integration tests for validation, recovery, and events.
84
+ - ๐Ÿ”“ **Self hosted**: Zero dependency on third-party node_modules or platforms; run entirely in your own environment.
85
+
86
+ ## ๐Ÿ“‹ Supported Order Types
87
+
88
+ > With the calculation of PnL, Peak Profit and Max Drawdown for each Entry
89
+
90
+ - Market/Limit entries
91
+ - TP/SL/OCO exits
92
+ - Grid with auto-cancel on unmet conditions
93
+ - Partial profit/loss levels
94
+ - Trailing stop-loss
95
+ - Breakeven protection
96
+ - Stop limit entries (before OCO)
97
+ - Dollar cost averaging
98
+ - Time attack / Infinite hold
99
+
100
+ ## ๐Ÿ“š Code Samples
101
+
102
+ ### โš™๏ธ Basic Configuration
103
+ ```typescript
104
+ import { setLogger, setConfig } from 'backtest-kit';
105
+
106
+ // Enable logging
107
+ setLogger({
108
+ log: console.log,
109
+ debug: console.debug,
110
+ info: console.info,
111
+ warn: console.warn,
112
+ });
113
+
114
+ // Global config (optional)
115
+ setConfig({
116
+ CC_PERCENT_SLIPPAGE: 0.1, // % slippage
117
+ CC_PERCENT_FEE: 0.1, // % fee
118
+ CC_SCHEDULE_AWAIT_MINUTES: 120, // Pending signal timeout
119
+ });
120
+ ```
121
+
122
+ ### ๐Ÿ”ง Register Components
123
+ ```typescript
124
+ import ccxt from 'ccxt';
125
+ import { addExchangeSchema, addStrategySchema, addFrameSchema, addRiskSchema } from 'backtest-kit';
126
+
127
+ // Exchange (data source)
128
+ addExchangeSchema({
129
+ exchangeName: 'binance',
130
+ getCandles: async (symbol, interval, since, limit) => {
131
+ const exchange = new ccxt.binance();
132
+ const ohlcv = await exchange.fetchOHLCV(symbol, interval, since.getTime(), limit);
133
+ return ohlcv.map(([timestamp, open, high, low, close, volume]) => ({ timestamp, open, high, low, close, volume }));
134
+ },
135
+ formatPrice: (symbol, price) => price.toFixed(2),
136
+ formatQuantity: (symbol, quantity) => quantity.toFixed(8),
137
+ });
138
+
139
+ // Risk profile
140
+ addRiskSchema({
141
+ riskName: 'demo',
142
+ validations: [
143
+ // TP at least 1%
144
+ ({ pendingSignal, currentPrice }) => {
145
+ const { priceOpen = currentPrice, priceTakeProfit, position } = pendingSignal;
146
+ const tpDistance = position === 'long' ? ((priceTakeProfit - priceOpen) / priceOpen) * 100 : ((priceOpen - priceTakeProfit) / priceOpen) * 100;
147
+ if (tpDistance < 1) throw new Error(`TP too close: ${tpDistance.toFixed(2)}%`);
148
+ },
149
+ // R/R at least 2:1
150
+ ({ pendingSignal, currentPrice }) => {
151
+ const { priceOpen = currentPrice, priceTakeProfit, priceStopLoss, position } = pendingSignal;
152
+ const reward = position === 'long' ? priceTakeProfit - priceOpen : priceOpen - priceTakeProfit;
153
+ const risk = position === 'long' ? priceOpen - priceStopLoss : priceStopLoss - priceOpen;
154
+ if (reward / risk < 2) throw new Error('Poor R/R ratio');
155
+ },
156
+ ],
157
+ });
158
+
159
+ // Time frame
160
+ addFrameSchema({
161
+ frameName: '1d-test',
162
+ interval: '1m',
163
+ startDate: new Date('2025-12-01'),
164
+ endDate: new Date('2025-12-02'),
165
+ });
166
+ ```
167
+
168
+ ### ๐Ÿ’ก Example Strategy (with LLM)
169
+ ```typescript
170
+ import { v4 as uuid } from 'uuid';
171
+ import { addStrategySchema, getCandles, dumpAgentAnswer, dumpRecord } from 'backtest-kit';
172
+ import { json } from './utils/json.mjs'; // LLM wrapper
173
+ import { getMessages } from './utils/messages.mjs'; // Market data prep
174
+
175
+ addStrategySchema({
176
+ strategyName: 'llm-strategy',
177
+ interval: '5m',
178
+ riskName: 'demo',
179
+ getSignal: async (symbol) => {
180
+
181
+ const candles1h = await getCandles(symbol, "1h", 24);
182
+ const candles15m = await getCandles(symbol, "15m", 48);
183
+ const candles5m = await getCandles(symbol, "5m", 60);
184
+ const candles1m = await getCandles(symbol, "1m", 60);
185
+
186
+ const messages = await getMessages(symbol, {
187
+ candles1h,
188
+ candles15m,
189
+ candles5m,
190
+ candles1m,
191
+ }); // Calculate indicators / Fetch news
192
+
193
+ const resultId = uuid();
194
+ const signal = await json(messages); // LLM generates signal
195
+
196
+ await dumpAgentAnswer({
197
+ dumpId: "position-context",
198
+ bucketName: "multi-timeframe-strategy",
199
+ messages: messages, // pass saved messages here
200
+ description: "agent reasoning for this signal",
201
+ });
202
+
203
+ await dumpRecord({
204
+ dumpId: "position-entry",
205
+ bucketName: "multi-timeframe-strategy",
206
+ record: signal, // pass saved signal record here
207
+ description: "signal entry parameters",
208
+ });
209
+
210
+ return { ...signal, id: resultId };
211
+ },
212
+ });
213
+ ```
214
+
215
+ ### ๐Ÿงช Run Backtest
216
+ ```typescript
217
+ import { Backtest, listenSignalBacktest, listenDoneBacktest } from 'backtest-kit';
218
+
219
+ Backtest.background('BTCUSDT', {
220
+ strategyName: 'llm-strategy',
221
+ exchangeName: 'binance',
222
+ frameName: '1d-test',
223
+ });
224
+
225
+ listenSignalBacktest((event) => console.log(event));
226
+ listenDoneBacktest(async (event) => {
227
+ await Backtest.dump(event.symbol, event.strategyName); // Generate report
228
+ });
229
+ ```
230
+
231
+ ### ๐Ÿ“ˆ Run Live Trading
232
+ ```typescript
233
+ import { Live, listenSignalLive } from 'backtest-kit';
234
+
235
+ Live.background('BTCUSDT', {
236
+ strategyName: 'llm-strategy',
237
+ exchangeName: 'binance', // Use API keys in .env
238
+ });
239
+
240
+ listenSignalLive((event) => console.log(event));
241
+ ```
242
+
243
+ ### ๐Ÿ“ก Monitoring & Events
244
+
245
+ - Use `listenRisk`, `listenError`, `listenPartialProfit/Loss` for alerts.
246
+ - Dump reports: `Backtest.dump()`, `Live.dump()`.
247
+
248
+ ## ๐ŸŒ Global Configuration
249
+
250
+ Customize via `setConfig()`:
251
+
252
+ - `CC_SCHEDULE_AWAIT_MINUTES`: Pending timeout (default: 120).
253
+ - `CC_AVG_PRICE_CANDLES_COUNT`: VWAP candles (default: 5).
254
+
255
+ ## ๐Ÿ’ป Developer Note
256
+
257
+ Backtest Kit is **not a data-processing library** - it is a **time execution engine**. Think of the engine as an **async stream of time**, where your strategy is evaluated step by step.
258
+
259
+ ### ๐Ÿ” How PNL Works
260
+
261
+ These three functions work together to dynamically manage the position. To reduce position linearity, by default, each DCA entry is formatted as a fixed **unit of $100**. This can be changed. No mathematical knowledge is required.
262
+
263
+ **Public API:**
264
+ - **`commitAverageBuy`** โ€” adds a new DCA entry. By default, **only accepted when current price is below a new low**. Silently rejected otherwise. This prevents averaging up. Can be overridden using `setConfig`
265
+ - **`commitPartialProfit`** โ€” closes X% of the position at a profit. Locks in gains while keeping exposure.
266
+ - **`commitPartialLoss`** โ€” closes X% of the position at a loss. Cuts exposure before the stop-loss is hit.
267
+
268
+ <details>
269
+ <summary>
270
+ The Math
271
+ </summary>
272
+
273
+ **Scenario:** LONG entry @ 1000, 4 DCA attempts (1 rejected), 3 partials, closed at TP.
274
+ `totalInvested = $400` (4 ร— $100, rejected attempt not counted).
275
+
276
+ **Entries**
277
+ ```
278
+ entry#1 @ 1000 โ†’ 0.10000 coins
279
+ commitPartialProfit(30%) @ 1150 โ† cnt=1
280
+ entry#2 @ 950 โ†’ 0.10526 coins
281
+ entry#3 @ 880 โ†’ 0.11364 coins
282
+ commitPartialLoss(20%) @ 860 โ† cnt=3
283
+ entry#4 @ 920 โ†’ 0.10870 coins
284
+ commitPartialProfit(40%) @ 1050 โ† cnt=4
285
+ entry#5 @ 980 โœ— REJECTED (980 > ep3โ‰ˆ929.92)
286
+ totalInvested = $400
287
+ ```
288
+
289
+ **Partial#1 โ€” commitPartialProfit @ 1150, 30%, cnt=1**
290
+ ```
291
+ effectivePrice = hm(1000) = 1000
292
+ costBasis = $100
293
+ partialDollarValue = 30% ร— 100 = $30 โ†’ weight = 30/400 = 0.075
294
+ pnl = (1150โˆ’1000)/1000 ร— 100 = +15.00%
295
+ costBasis โ†’ $70
296
+ coins sold: 0.03000 ร— 1150 = $34.50
297
+ remaining: 0.07000
298
+ ```
299
+
300
+ **DCA after Partial#1**
301
+ ```
302
+ entry#2 @ 950 (950 < ep1=1000 โœ“ accepted)
303
+ entry#3 @ 880 (880 < ep1=1000 โœ“ accepted)
304
+ coins: 0.07000 + 0.10526 + 0.11364 = 0.28890
305
+ ```
306
+
307
+ **Partial#2 โ€” commitPartialLoss @ 860, 20%, cnt=3**
308
+ ```
309
+ costBasis = 70 + 100 + 100 = $270
310
+ ep2 = 270 / 0.28890 โ‰ˆ 934.58
311
+ partialDollarValue = 20% ร— 270 = $54 โ†’ weight = 54/400 = 0.135
312
+ pnl = (860โˆ’934.58)/934.58 ร— 100 โ‰ˆ โˆ’7.98%
313
+ costBasis โ†’ $216
314
+ coins sold: 0.05778 ร— 860 = $49.69
315
+ remaining: 0.23112
316
+ ```
317
+
318
+ **DCA after Partial#2**
319
+ ```
320
+ entry#4 @ 920 (920 < ep2=934.58 โœ“ accepted)
321
+ coins: 0.23112 + 0.10870 = 0.33982
322
+ ```
323
+
324
+ **Partial#3 โ€” commitPartialProfit @ 1050, 40%, cnt=4**
325
+ ```
326
+ costBasis = 216 + 100 = $316
327
+ ep3 = 316 / 0.33982 โ‰ˆ 929.92
328
+ partialDollarValue = 40% ร— 316 = $126.4 โ†’ weight = 126.4/400 = 0.316
329
+ pnl = (1050โˆ’929.92)/929.92 ร— 100 โ‰ˆ +12.91%
330
+ costBasis โ†’ $189.6
331
+ coins sold: 0.13593 ร— 1050 = $142.72
332
+ remaining: 0.20389
333
+ ```
334
+
335
+ **DCA after Partial#3 โ€” rejected**
336
+ ```
337
+ entry#5 @ 980 (980 > ep3โ‰ˆ929.92 โœ— REJECTED)
338
+ ```
339
+
340
+ **Close at TP @ 1200**
341
+ ```
342
+ ep_final = ep3 โ‰ˆ 929.92 (no new entries)
343
+ coins: 0.20389
344
+
345
+ remainingDollarValue = 400 โˆ’ 30 โˆ’ 54 โˆ’ 126.4 = $189.6
346
+ weight = 189.6/400 = 0.474
347
+ pnl = (1200โˆ’929.92)/929.92 ร— 100 โ‰ˆ +29.04%
348
+ coins sold: 0.20389 ร— 1200 = $244.67
349
+ ```
350
+
351
+ **Result (toProfitLossDto)**
352
+ ```
353
+ 0.075 ร— (+15.00) = +1.125
354
+ 0.135 ร— (โˆ’7.98) = โˆ’1.077
355
+ 0.316 ร— (+12.91) = +4.080
356
+ 0.474 ร— (+29.04) = +13.765
357
+ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
358
+ โ‰ˆ +17.89%
359
+
360
+ Cross-check (coins):
361
+ 34.50 + 49.69 + 142.72 + 244.67 = $471.58
362
+ (471.58 โˆ’ 400) / 400 ร— 100 = +17.90% โœ“
363
+ ```
364
+ </details>
365
+
366
+ #### Internals
367
+
368
+ **`priceOpen`** is the harmonic mean of all accepted DCA entries. After each partial close (`commitPartialProfit` or `commitPartialLoss`), the remaining cost basis is carried forward into the harmonic mean calculation for subsequent entries โ€” so `priceOpen` shifts after every partial, which in turn changes whether the next `commitAverageBuy` call will be accepted.
369
+
370
+ ### ๐Ÿ” How Broker Transactional Integrity Works
371
+
372
+ `Broker.useBrokerAdapter` connects a live exchange (ccxt, Binance, etc.) to the framework with transaction safety. Every commit method fires **before** the internal position state mutates. If the exchange rejects the order, the fill times out, or the network fails, the adapter throws, the mutation is skipped, and backtest-kit retries automatically on the next tick.
373
+
374
+ <details>
375
+ <summary>
376
+ The code
377
+ </summary>
378
+
379
+ **Spot**
380
+
381
+ ```typescript
382
+ import ccxt from "ccxt";
383
+ import { singleshot, sleep } from "functools-kit";
384
+ import {
385
+ Broker,
386
+ IBroker,
387
+ BrokerSignalOpenPayload,
388
+ BrokerSignalClosePayload,
389
+ BrokerPartialProfitPayload,
390
+ BrokerPartialLossPayload,
391
+ BrokerTrailingStopPayload,
392
+ BrokerTrailingTakePayload,
393
+ BrokerBreakevenPayload,
394
+ BrokerAverageBuyPayload,
395
+ } from "backtest-kit";
396
+
397
+ const FILL_POLL_INTERVAL_MS = 10_000;
398
+ const FILL_POLL_ATTEMPTS = 10;
399
+
400
+ /**
401
+ * Sleep between cancelOrder and fetchBalance to allow Binance to settle the
402
+ * cancellation โ€” reads immediately after cancel may return stale data.
403
+ */
404
+ const CANCEL_SETTLE_MS = 2_000;
405
+
406
+ /**
407
+ * Slippage buffer for stop_loss_limit on Spot โ€” limit price is set slightly
408
+ * below stopPrice so the order fills even on a gap down instead of hanging.
409
+ */
410
+ const STOP_LIMIT_SLIPPAGE = 0.995;
411
+
412
+ const getSpotExchange = singleshot(async () => {
413
+ const exchange = new ccxt.binance({
414
+ apiKey: process.env.BINANCE_API_KEY,
415
+ secret: process.env.BINANCE_API_SECRET,
416
+ options: {
417
+ defaultType: "spot",
418
+ adjustForTimeDifference: true,
419
+ recvWindow: 60000,
420
+ },
421
+ enableRateLimit: true,
422
+ });
423
+ await exchange.loadMarkets();
424
+ return exchange;
425
+ });
426
+
427
+ /**
428
+ * Resolve base currency from market metadata โ€” safe for all quote currencies (USDT, USDC, FDUSD, etc.)
429
+ */
430
+ function getBase(exchange: ccxt.binance, symbol: string): string {
431
+ return exchange.markets[symbol].base;
432
+ }
433
+
434
+ /**
435
+ * Truncate qty to exchange precision, always rounding down.
436
+ * Prevents over-selling due to floating point drift from fetchBalance.
437
+ */
438
+ function truncateQty(exchange: ccxt.binance, symbol: string, qty: number): number {
439
+ return parseFloat(exchange.amountToPrecision(symbol, qty, exchange.TRUNCATE));
440
+ }
441
+
442
+ /**
443
+ * Fetch current free balance for base currency of symbol.
444
+ */
445
+ async function fetchFreeQty(exchange: ccxt.binance, symbol: string): Promise<number> {
446
+ const balance = await exchange.fetchBalance();
447
+ const base = getBase(exchange, symbol);
448
+ return parseFloat(String(balance?.free?.[base] ?? 0));
449
+ }
450
+
451
+ /**
452
+ * Cancel all orders in parallel โ€” allSettled so a single failure (already filled,
453
+ * network blip) does not leave remaining orders uncancelled.
454
+ */
455
+ async function cancelAllOrders(exchange: ccxt.binance, orders: ccxt.Order[], symbol: string): Promise<void> {
456
+ await Promise.allSettled(orders.map((o) => exchange.cancelOrder(o.id, symbol)));
457
+ }
458
+
459
+ /**
460
+ * Place a stop_loss_limit sell order with a slippage buffer on the limit price.
461
+ * stop_loss_limit requires both stopPrice (trigger) and price (limit fill).
462
+ * Setting them equal risks non-fill on gap down โ€” limit is offset by STOP_LIMIT_SLIPPAGE.
463
+ */
464
+ async function createStopLossOrder(
465
+ exchange: ccxt.binance,
466
+ symbol: string,
467
+ qty: number,
468
+ stopPrice: number
469
+ ): Promise<void> {
470
+ const limitPrice = parseFloat(exchange.priceToPrecision(symbol, stopPrice * STOP_LIMIT_SLIPPAGE));
471
+ await exchange.createOrder(symbol, "stop_loss_limit", "sell", qty, limitPrice, { stopPrice });
472
+ }
473
+
474
+ /**
475
+ * Place a limit order and poll until filled (status === "closed").
476
+ * On timeout: cancel the order, settle, check partial fill and sell it via market,
477
+ * restore SL/TP on remaining position so it is never left unprotected, then throw.
478
+ */
479
+ async function createLimitOrderAndWait(
480
+ exchange: ccxt.binance,
481
+ symbol: string,
482
+ side: "buy" | "sell",
483
+ qty: number,
484
+ price: number,
485
+ restore?: { tpPrice: number; slPrice: number }
486
+ ): Promise<void> {
487
+ const order = await exchange.createOrder(symbol, "limit", side, qty, price);
488
+
489
+ for (let i = 0; i < FILL_POLL_ATTEMPTS; i++) {
490
+ await sleep(FILL_POLL_INTERVAL_MS);
491
+ const status = await exchange.fetchOrder(order.id, symbol);
492
+ if (status.status === "closed") {
493
+ return;
494
+ }
495
+ }
496
+
497
+ await exchange.cancelOrder(order.id, symbol);
498
+
499
+ // Wait for Binance to settle the cancellation before reading filled qty
500
+ await sleep(CANCEL_SETTLE_MS);
501
+
502
+ const final = await exchange.fetchOrder(order.id, symbol);
503
+ const filledQty = final.filled ?? 0;
504
+
505
+ if (filledQty > 0) {
506
+ // Sell partial fill via market to restore clean exchange state before backtest-kit retries
507
+ const rollbackSide = side === "buy" ? "sell" : "buy";
508
+ await exchange.createOrder(symbol, "market", rollbackSide, filledQty);
509
+ }
510
+
511
+ // Restore SL/TP on remaining position so it is not left unprotected during retry
512
+ if (restore) {
513
+ const remainingQty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
514
+ if (remainingQty > 0) {
515
+ await exchange.createOrder(symbol, "limit", "sell", remainingQty, restore.tpPrice);
516
+ await createStopLossOrder(exchange, symbol, remainingQty, restore.slPrice);
517
+ }
518
+ }
519
+
520
+ throw new Error(`Limit order ${order.id} [${side} ${qty} ${symbol} @ ${price}] not filled in time โ€” partial fill rolled back, backtest-kit will retry`);
521
+ }
522
+
523
+ Broker.useBrokerAdapter(
524
+ class implements IBroker {
525
+
526
+ async waitForInit(): Promise<void> {
527
+ await getSpotExchange();
528
+ }
529
+
530
+ async onSignalOpenCommit(payload: BrokerSignalOpenPayload): Promise<void> {
531
+ const { symbol, cost, priceOpen, priceTakeProfit, priceStopLoss, position } = payload;
532
+
533
+ // Spot does not support short selling โ€” reject immediately so backtest-kit skips the mutation
534
+ if (position === "short") {
535
+ throw new Error(`SpotBrokerAdapter: short position is not supported on spot (symbol=${symbol})`);
536
+ }
537
+
538
+ const exchange = await getSpotExchange();
539
+
540
+ const qty = truncateQty(exchange, symbol, cost / priceOpen);
541
+
542
+ // Guard: truncation may produce 0 if cost/price is below lot size
543
+ if (qty <= 0) {
544
+ throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${priceOpen}`);
545
+ }
546
+
547
+ const openPrice = parseFloat(exchange.priceToPrecision(symbol, priceOpen));
548
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
549
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
550
+
551
+ // Entry: no restore needed โ€” position does not exist yet if entry times out
552
+ await createLimitOrderAndWait(exchange, symbol, "buy", qty, openPrice);
553
+
554
+ // Post-fill: if TP/SL placement fails, position is open and unprotected โ€” close via market
555
+ try {
556
+ await exchange.createOrder(symbol, "limit", "sell", qty, tpPrice);
557
+ await createStopLossOrder(exchange, symbol, qty, slPrice);
558
+ } catch (err) {
559
+ await exchange.createOrder(symbol, "market", "sell", qty);
560
+ throw err;
561
+ }
562
+ }
563
+
564
+ async onSignalCloseCommit(payload: BrokerSignalClosePayload): Promise<void> {
565
+ const { symbol, currentPrice, priceTakeProfit, priceStopLoss } = payload;
566
+ const exchange = await getSpotExchange();
567
+
568
+ const openOrders = await exchange.fetchOpenOrders(symbol);
569
+ await cancelAllOrders(exchange, openOrders, symbol);
570
+ await sleep(CANCEL_SETTLE_MS);
571
+
572
+ const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
573
+
574
+ // Position already closed by SL/TP on exchange โ€” nothing to do, commit succeeds
575
+ if (qty === 0) {
576
+ return;
577
+ }
578
+
579
+ const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
580
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
581
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
582
+
583
+ // Restore SL/TP if close times out so position is not left unprotected during retry
584
+ await createLimitOrderAndWait(exchange, symbol, "sell", qty, closePrice, { tpPrice, slPrice });
585
+ }
586
+
587
+ async onPartialProfitCommit(payload: BrokerPartialProfitPayload): Promise<void> {
588
+ const { symbol, percentToClose, currentPrice, priceTakeProfit, priceStopLoss } = payload;
589
+ const exchange = await getSpotExchange();
590
+
591
+ const openOrders = await exchange.fetchOpenOrders(symbol);
592
+ await cancelAllOrders(exchange, openOrders, symbol);
593
+ await sleep(CANCEL_SETTLE_MS);
594
+
595
+ const totalQty = await fetchFreeQty(exchange, symbol);
596
+
597
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
598
+ if (totalQty === 0) {
599
+ throw new Error(`PartialProfit skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
600
+ }
601
+
602
+ const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
603
+ const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
604
+ const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
605
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
606
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
607
+
608
+ // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
609
+ await createLimitOrderAndWait(exchange, symbol, "sell", qty, closePrice, { tpPrice, slPrice });
610
+
611
+ // Restore SL/TP on remaining qty after successful partial close
612
+ if (remainingQty > 0) {
613
+ try {
614
+ await exchange.createOrder(symbol, "limit", "sell", remainingQty, tpPrice);
615
+ await createStopLossOrder(exchange, symbol, remainingQty, slPrice);
616
+ } catch (err) {
617
+ // Remaining position is unprotected โ€” close via market
618
+ await exchange.createOrder(symbol, "market", "sell", remainingQty);
619
+ throw err;
620
+ }
621
+ }
622
+ }
623
+
624
+ async onPartialLossCommit(payload: BrokerPartialLossPayload): Promise<void> {
625
+ const { symbol, percentToClose, currentPrice, priceTakeProfit, priceStopLoss } = payload;
626
+ const exchange = await getSpotExchange();
627
+
628
+ const openOrders = await exchange.fetchOpenOrders(symbol);
629
+ await cancelAllOrders(exchange, openOrders, symbol);
630
+ await sleep(CANCEL_SETTLE_MS);
631
+
632
+ const totalQty = await fetchFreeQty(exchange, symbol);
633
+
634
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
635
+ if (totalQty === 0) {
636
+ throw new Error(`PartialLoss skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
637
+ }
638
+
639
+ const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
640
+ const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
641
+ const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
642
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
643
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
644
+
645
+ // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
646
+ await createLimitOrderAndWait(exchange, symbol, "sell", qty, closePrice, { tpPrice, slPrice });
647
+
648
+ // Restore SL/TP on remaining qty after successful partial close
649
+ if (remainingQty > 0) {
650
+ try {
651
+ await exchange.createOrder(symbol, "limit", "sell", remainingQty, tpPrice);
652
+ await createStopLossOrder(exchange, symbol, remainingQty, slPrice);
653
+ } catch (err) {
654
+ // Remaining position is unprotected โ€” close via market
655
+ await exchange.createOrder(symbol, "market", "sell", remainingQty);
656
+ throw err;
657
+ }
658
+ }
659
+ }
660
+
661
+ async onTrailingStopCommit(payload: BrokerTrailingStopPayload): Promise<void> {
662
+ const { symbol, newStopLossPrice } = payload;
663
+ const exchange = await getSpotExchange();
664
+
665
+ // Cancel existing SL order only โ€” Spot has no reduceOnly, filter by side + type
666
+ const orders = await exchange.fetchOpenOrders(symbol);
667
+ const slOrder = orders.find((o) =>
668
+ o.side === "sell" &&
669
+ ["stop_loss_limit", "stop", "STOP_LOSS_LIMIT"].includes(o.type ?? "")
670
+ ) ?? null;
671
+ if (slOrder) {
672
+ await exchange.cancelOrder(slOrder.id, symbol);
673
+ await sleep(CANCEL_SETTLE_MS);
674
+ }
675
+
676
+ const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
677
+
678
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
679
+ if (qty === 0) {
680
+ throw new Error(`TrailingStop skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
681
+ }
682
+
683
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
684
+
685
+ await createStopLossOrder(exchange, symbol, qty, slPrice);
686
+ }
687
+
688
+ async onTrailingTakeCommit(payload: BrokerTrailingTakePayload): Promise<void> {
689
+ const { symbol, newTakeProfitPrice } = payload;
690
+ const exchange = await getSpotExchange();
691
+
692
+ // Cancel existing TP order only โ€” Spot has no reduceOnly, filter by side + type
693
+ const orders = await exchange.fetchOpenOrders(symbol);
694
+ const tpOrder = orders.find((o) =>
695
+ o.side === "sell" &&
696
+ ["limit", "LIMIT"].includes(o.type ?? "")
697
+ ) ?? null;
698
+ if (tpOrder) {
699
+ await exchange.cancelOrder(tpOrder.id, symbol);
700
+ await sleep(CANCEL_SETTLE_MS);
701
+ }
702
+
703
+ const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
704
+
705
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
706
+ if (qty === 0) {
707
+ throw new Error(`TrailingTake skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
708
+ }
709
+
710
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, newTakeProfitPrice));
711
+
712
+ await exchange.createOrder(symbol, "limit", "sell", qty, tpPrice);
713
+ }
714
+
715
+ async onBreakevenCommit(payload: BrokerBreakevenPayload): Promise<void> {
716
+ const { symbol, newStopLossPrice } = payload;
717
+ const exchange = await getSpotExchange();
718
+
719
+ // Cancel existing SL order only โ€” Spot has no reduceOnly, filter by side + type
720
+ const orders = await exchange.fetchOpenOrders(symbol);
721
+ const slOrder = orders.find((o) =>
722
+ o.side === "sell" &&
723
+ ["stop_loss_limit", "stop", "STOP_LOSS_LIMIT"].includes(o.type ?? "")
724
+ ) ?? null;
725
+ if (slOrder) {
726
+ await exchange.cancelOrder(slOrder.id, symbol);
727
+ await sleep(CANCEL_SETTLE_MS);
728
+ }
729
+
730
+ const qty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
731
+
732
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
733
+ if (qty === 0) {
734
+ throw new Error(`Breakeven skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
735
+ }
736
+
737
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
738
+
739
+ await createStopLossOrder(exchange, symbol, qty, slPrice);
740
+ }
741
+
742
+ async onAverageBuyCommit(payload: BrokerAverageBuyPayload): Promise<void> {
743
+ const { symbol, currentPrice, cost, priceTakeProfit, priceStopLoss } = payload;
744
+ const exchange = await getSpotExchange();
745
+
746
+ // Cancel existing SL/TP first โ€” existing check must happen after cancel+settle
747
+ // to avoid race condition where SL/TP fills between the existence check and cancel
748
+ const openOrders = await exchange.fetchOpenOrders(symbol);
749
+ await cancelAllOrders(exchange, openOrders, symbol);
750
+ await sleep(CANCEL_SETTLE_MS);
751
+
752
+ // Guard against DCA into a ghost position โ€” checked after cancel so the snapshot is fresh
753
+ const existing = await fetchFreeQty(exchange, symbol);
754
+ const minNotional = exchange.markets[symbol].limits?.cost?.min ?? 1;
755
+
756
+ // Compare notional value rather than raw qty โ€” avoids float === 0 trap
757
+ // and correctly rejects dust balances left over from previous trades
758
+ if (existing * currentPrice < minNotional) {
759
+ throw new Error(`AverageBuy skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
760
+ }
761
+
762
+ const qty = truncateQty(exchange, symbol, cost / currentPrice);
763
+
764
+ // Guard: truncation may produce 0 if cost/price is below lot size
765
+ if (qty <= 0) {
766
+ throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${currentPrice}`);
767
+ }
768
+
769
+ const entryPrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
770
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
771
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
772
+
773
+ // DCA entry: restore SL/TP on existing qty if times out so position is not left unprotected
774
+ await createLimitOrderAndWait(exchange, symbol, "buy", qty, entryPrice, { tpPrice, slPrice });
775
+
776
+ // Refetch balance after fill โ€” existing snapshot is stale after cancel + fill
777
+ const totalQty = truncateQty(exchange, symbol, await fetchFreeQty(exchange, symbol));
778
+
779
+ // Recreate SL/TP on fresh total qty after successful fill
780
+ try {
781
+ await exchange.createOrder(symbol, "limit", "sell", totalQty, tpPrice);
782
+ await createStopLossOrder(exchange, symbol, totalQty, slPrice);
783
+ } catch (err) {
784
+ // Total position is unprotected โ€” close via market
785
+ await exchange.createOrder(symbol, "market", "sell", totalQty);
786
+ throw err;
787
+ }
788
+ }
789
+ }
790
+ );
791
+
792
+ Broker.enable();
793
+ ```
794
+
795
+ **Futures**
796
+
797
+ ```typescript
798
+ import ccxt from "ccxt";
799
+ import { singleshot, sleep } from "functools-kit";
800
+ import {
801
+ Broker,
802
+ IBroker,
803
+ BrokerSignalOpenPayload,
804
+ BrokerSignalClosePayload,
805
+ BrokerPartialProfitPayload,
806
+ BrokerPartialLossPayload,
807
+ BrokerTrailingStopPayload,
808
+ BrokerTrailingTakePayload,
809
+ BrokerBreakevenPayload,
810
+ BrokerAverageBuyPayload,
811
+ } from "backtest-kit";
812
+
813
+ const FILL_POLL_INTERVAL_MS = 10_000;
814
+ const FILL_POLL_ATTEMPTS = 10;
815
+
816
+ /**
817
+ * Sleep between cancelOrder and fetchPositions to allow Binance to settle the
818
+ * cancellation โ€” reads immediately after cancel may return stale data.
819
+ */
820
+ const CANCEL_SETTLE_MS = 2_000;
821
+
822
+ /**
823
+ * 3x leverage โ€” conservative choice for $1000 total fiat.
824
+ * Enough to matter, not enough to liquidate on normal volatility.
825
+ * Applied per-symbol on first open via setLeverage.
826
+ */
827
+ const FUTURES_LEVERAGE = 3;
828
+
829
+ const getFuturesExchange = singleshot(async () => {
830
+ const exchange = new ccxt.binance({
831
+ apiKey: process.env.BINANCE_API_KEY,
832
+ secret: process.env.BINANCE_API_SECRET,
833
+ options: {
834
+ defaultType: "future",
835
+ adjustForTimeDifference: true,
836
+ recvWindow: 60000,
837
+ },
838
+ enableRateLimit: true,
839
+ });
840
+ await exchange.loadMarkets();
841
+ return exchange;
842
+ });
843
+
844
+ /**
845
+ * Truncate qty to exchange precision, always rounding down.
846
+ * Prevents over-selling due to floating point drift from fetchPositions.
847
+ */
848
+ function truncateQty(exchange: ccxt.binance, symbol: string, qty: number): number {
849
+ return parseFloat(exchange.amountToPrecision(symbol, qty, exchange.TRUNCATE));
850
+ }
851
+
852
+ /**
853
+ * Resolve position for symbol filtered by side โ€” safe in both one-way and hedge mode.
854
+ */
855
+ function findPosition(positions: ccxt.Position[], symbol: string, side: "long" | "short") {
856
+ // Hedge mode: positions have explicit side field
857
+ const hedged = positions.find((p) => p.symbol === symbol && p.side === side);
858
+ if (hedged) {
859
+ return hedged;
860
+ }
861
+ // One-way mode: single position per symbol, side field may be undefined or mismatched
862
+ const pos = positions.find((p) => p.symbol === symbol) ?? null;
863
+ if (pos && pos.side && pos.side !== side) {
864
+ console.warn(`findPosition: expected side="${side}" but exchange returned side="${pos.side}" for ${symbol} โ€” possible one-way/hedge mode mismatch`);
865
+ }
866
+ return pos;
867
+ }
868
+
869
+ /**
870
+ * Fetch current contracts qty for symbol/side.
871
+ */
872
+ async function fetchContractsQty(
873
+ exchange: ccxt.binance,
874
+ symbol: string,
875
+ side: "long" | "short"
876
+ ): Promise<number> {
877
+ const positions = await exchange.fetchPositions([symbol]);
878
+ const pos = findPosition(positions, symbol, side);
879
+ return Math.abs(parseFloat(String(pos?.contracts ?? 0)));
880
+ }
881
+
882
+ /**
883
+ * Cancel all orders in parallel โ€” allSettled so a single failure (already filled,
884
+ * network blip) does not leave remaining orders uncancelled.
885
+ */
886
+ async function cancelAllOrders(exchange: ccxt.binance, orders: ccxt.Order[], symbol: string): Promise<void> {
887
+ await Promise.allSettled(orders.map((o) => exchange.cancelOrder(o.id, symbol)));
888
+ }
889
+
890
+ /**
891
+ * Resolve Binance positionSide string from position direction.
892
+ * Required in hedge mode to correctly route orders; ignored in one-way mode.
893
+ */
894
+ function toPositionSide(position: "long" | "short"): "LONG" | "SHORT" {
895
+ return position === "long" ? "LONG" : "SHORT";
896
+ }
897
+
898
+ /**
899
+ * Place a limit order and poll until filled (status === "closed").
900
+ * On timeout: cancel the order, settle, check partial fill and close it via market,
901
+ * restore SL/TP on remaining position so it is never left unprotected, then throw.
902
+ *
903
+ * positionSide is forwarded into rollback market order so hedge mode accounts
904
+ * correctly route the close without -4061 error.
905
+ */
906
+ async function createLimitOrderAndWait(
907
+ exchange: ccxt.binance,
908
+ symbol: string,
909
+ side: "buy" | "sell",
910
+ qty: number,
911
+ price: number,
912
+ params: Record<string, unknown> = {},
913
+ restore?: { exitSide: "buy" | "sell"; tpPrice: number; slPrice: number; positionSide: "long" | "short" }
914
+ ): Promise<void> {
915
+ const order = await exchange.createOrder(symbol, "limit", side, qty, price, params);
916
+
917
+ for (let i = 0; i < FILL_POLL_ATTEMPTS; i++) {
918
+ await sleep(FILL_POLL_INTERVAL_MS);
919
+ const status = await exchange.fetchOrder(order.id, symbol);
920
+ if (status.status === "closed") {
921
+ return;
922
+ }
923
+ }
924
+
925
+ await exchange.cancelOrder(order.id, symbol);
926
+
927
+ // Wait for Binance to settle the cancellation before reading filled qty
928
+ await sleep(CANCEL_SETTLE_MS);
929
+
930
+ const final = await exchange.fetchOrder(order.id, symbol);
931
+ const filledQty = final.filled ?? 0;
932
+
933
+ if (filledQty > 0) {
934
+ // Close partial fill via market โ€” positionSide required in hedge mode (-4061 without it)
935
+ const rollbackSide = side === "buy" ? "sell" : "buy";
936
+ const rollbackPositionSide = params.positionSide ?? (restore ? toPositionSide(restore.positionSide) : undefined);
937
+ await exchange.createOrder(symbol, "market", rollbackSide, filledQty, undefined, {
938
+ reduceOnly: true,
939
+ ...(rollbackPositionSide ? { positionSide: rollbackPositionSide } : {}),
940
+ });
941
+ }
942
+
943
+ // Restore SL/TP on remaining position so it is not left unprotected during retry
944
+ if (restore) {
945
+ const remainingQty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, restore.positionSide));
946
+ if (remainingQty > 0) {
947
+ await exchange.createOrder(symbol, "limit", restore.exitSide, remainingQty, restore.tpPrice, { reduceOnly: true });
948
+ await exchange.createOrder(symbol, "stop_market", restore.exitSide, remainingQty, undefined, { stopPrice: restore.slPrice, reduceOnly: true });
949
+ }
950
+ }
951
+
952
+ throw new Error(`Limit order ${order.id} [${side} ${qty} ${symbol} @ ${price}] not filled in time โ€” partial fill rolled back, backtest-kit will retry`);
953
+ }
954
+
955
+ Broker.useBrokerAdapter(
956
+ class implements IBroker {
957
+
958
+ async waitForInit(): Promise<void> {
959
+ await getFuturesExchange();
960
+ }
961
+
962
+ async onSignalOpenCommit(payload: BrokerSignalOpenPayload): Promise<void> {
963
+ const { symbol, cost, priceOpen, priceTakeProfit, priceStopLoss, position } = payload;
964
+ const exchange = await getFuturesExchange();
965
+
966
+ // Set leverage before entry โ€” ensures consistent leverage regardless of previous session state
967
+ await exchange.setLeverage(FUTURES_LEVERAGE, symbol);
968
+
969
+ const qty = truncateQty(exchange, symbol, cost / priceOpen);
970
+
971
+ // Guard: truncation may produce 0 if cost/price is below lot size
972
+ if (qty <= 0) {
973
+ throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${priceOpen}`);
974
+ }
975
+
976
+ const openPrice = parseFloat(exchange.priceToPrecision(symbol, priceOpen));
977
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
978
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
979
+ const entrySide = position === "long" ? "buy" : "sell";
980
+ const exitSide = position === "long" ? "sell" : "buy";
981
+ // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
982
+ const positionSide = toPositionSide(position);
983
+
984
+ // Entry: no restore needed โ€” position does not exist yet if entry times out
985
+ await createLimitOrderAndWait(exchange, symbol, entrySide, qty, openPrice, { positionSide });
986
+
987
+ // Post-fill: if TP/SL placement fails, position is open and unprotected โ€” close via market
988
+ try {
989
+ await exchange.createOrder(symbol, "limit", exitSide, qty, tpPrice, { reduceOnly: true, positionSide });
990
+ await exchange.createOrder(symbol, "stop_market", exitSide, qty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
991
+ } catch (err) {
992
+ await exchange.createOrder(symbol, "market", exitSide, qty, undefined, { reduceOnly: true, positionSide });
993
+ throw err;
994
+ }
995
+ }
996
+
997
+ async onSignalCloseCommit(payload: BrokerSignalClosePayload): Promise<void> {
998
+ const { symbol, position, currentPrice, priceTakeProfit, priceStopLoss } = payload;
999
+ const exchange = await getFuturesExchange();
1000
+
1001
+ const openOrders = await exchange.fetchOpenOrders(symbol);
1002
+ await cancelAllOrders(exchange, openOrders, symbol);
1003
+ await sleep(CANCEL_SETTLE_MS);
1004
+
1005
+ const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1006
+ const exitSide = position === "long" ? "sell" : "buy";
1007
+
1008
+ // Position already closed by SL/TP on exchange โ€” throw so backtest-kit can reconcile
1009
+ // the close price via its own mechanism rather than assuming a successful manual close
1010
+ if (qty === 0) {
1011
+ throw new Error(`SignalClose skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1012
+ }
1013
+
1014
+ const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1015
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1016
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1017
+
1018
+ // reduceOnly: prevents accidental reversal if qty has drift vs real position
1019
+ // Restore SL/TP if close times out so position is not left unprotected during retry
1020
+ await createLimitOrderAndWait(
1021
+ exchange, symbol, exitSide, qty, closePrice,
1022
+ { reduceOnly: true },
1023
+ { exitSide, tpPrice, slPrice, positionSide: position }
1024
+ );
1025
+ }
1026
+
1027
+ async onPartialProfitCommit(payload: BrokerPartialProfitPayload): Promise<void> {
1028
+ const { symbol, percentToClose, currentPrice, position, priceTakeProfit, priceStopLoss } = payload;
1029
+ const exchange = await getFuturesExchange();
1030
+
1031
+ const openOrders = await exchange.fetchOpenOrders(symbol);
1032
+ await cancelAllOrders(exchange, openOrders, symbol);
1033
+ await sleep(CANCEL_SETTLE_MS);
1034
+
1035
+ const totalQty = await fetchContractsQty(exchange, symbol, position);
1036
+
1037
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1038
+ if (totalQty === 0) {
1039
+ throw new Error(`PartialProfit skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1040
+ }
1041
+
1042
+ const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
1043
+ const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
1044
+ const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1045
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1046
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1047
+ const exitSide = position === "long" ? "sell" : "buy";
1048
+ const positionSide = toPositionSide(position);
1049
+
1050
+ // reduceOnly: prevents accidental reversal if qty has drift vs real position
1051
+ // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
1052
+ await createLimitOrderAndWait(
1053
+ exchange, symbol, exitSide, qty, closePrice,
1054
+ { reduceOnly: true },
1055
+ { exitSide, tpPrice, slPrice, positionSide: position }
1056
+ );
1057
+
1058
+ // Restore SL/TP on remaining qty after successful partial close
1059
+ if (remainingQty > 0) {
1060
+ try {
1061
+ await exchange.createOrder(symbol, "limit", exitSide, remainingQty, tpPrice, { reduceOnly: true, positionSide });
1062
+ await exchange.createOrder(symbol, "stop_market", exitSide, remainingQty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1063
+ } catch (err) {
1064
+ // Remaining position is unprotected โ€” close via market
1065
+ await exchange.createOrder(symbol, "market", exitSide, remainingQty, undefined, { reduceOnly: true, positionSide });
1066
+ throw err;
1067
+ }
1068
+ }
1069
+ }
1070
+
1071
+ async onPartialLossCommit(payload: BrokerPartialLossPayload): Promise<void> {
1072
+ const { symbol, percentToClose, currentPrice, position, priceTakeProfit, priceStopLoss } = payload;
1073
+ const exchange = await getFuturesExchange();
1074
+
1075
+ const openOrders = await exchange.fetchOpenOrders(symbol);
1076
+ await cancelAllOrders(exchange, openOrders, symbol);
1077
+ await sleep(CANCEL_SETTLE_MS);
1078
+
1079
+ const totalQty = await fetchContractsQty(exchange, symbol, position);
1080
+
1081
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1082
+ if (totalQty === 0) {
1083
+ throw new Error(`PartialLoss skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1084
+ }
1085
+
1086
+ const qty = truncateQty(exchange, symbol, totalQty * (percentToClose / 100));
1087
+ const remainingQty = truncateQty(exchange, symbol, totalQty - qty);
1088
+ const closePrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1089
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1090
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1091
+ const exitSide = position === "long" ? "sell" : "buy";
1092
+ const positionSide = toPositionSide(position);
1093
+
1094
+ // reduceOnly: prevents accidental reversal if qty has drift vs real position
1095
+ // Restore SL/TP on remaining qty if partial close times out so position is not left unprotected
1096
+ await createLimitOrderAndWait(
1097
+ exchange, symbol, exitSide, qty, closePrice,
1098
+ { reduceOnly: true },
1099
+ { exitSide, tpPrice, slPrice, positionSide: position }
1100
+ );
1101
+
1102
+ // Restore SL/TP on remaining qty after successful partial close
1103
+ if (remainingQty > 0) {
1104
+ try {
1105
+ await exchange.createOrder(symbol, "limit", exitSide, remainingQty, tpPrice, { reduceOnly: true, positionSide });
1106
+ await exchange.createOrder(symbol, "stop_market", exitSide, remainingQty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1107
+ } catch (err) {
1108
+ // Remaining position is unprotected โ€” close via market
1109
+ await exchange.createOrder(symbol, "market", exitSide, remainingQty, undefined, { reduceOnly: true, positionSide });
1110
+ throw err;
1111
+ }
1112
+ }
1113
+ }
1114
+
1115
+ async onTrailingStopCommit(payload: BrokerTrailingStopPayload): Promise<void> {
1116
+ const { symbol, newStopLossPrice, position } = payload;
1117
+ const exchange = await getFuturesExchange();
1118
+
1119
+ // Cancel existing SL order only โ€” filter by reduceOnly to avoid cancelling unrelated orders
1120
+ const orders = await exchange.fetchOpenOrders(symbol);
1121
+ const slOrder = orders.find((o) =>
1122
+ !!o.reduceOnly &&
1123
+ ["stop_market", "stop", "STOP_MARKET"].includes(o.type ?? "")
1124
+ ) ?? null;
1125
+ if (slOrder) {
1126
+ await exchange.cancelOrder(slOrder.id, symbol);
1127
+ await sleep(CANCEL_SETTLE_MS);
1128
+ }
1129
+
1130
+ const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1131
+ const exitSide = position === "long" ? "sell" : "buy";
1132
+
1133
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1134
+ if (qty === 0) {
1135
+ throw new Error(`TrailingStop skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1136
+ }
1137
+
1138
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
1139
+ const positionSide = toPositionSide(position);
1140
+
1141
+ // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
1142
+ await exchange.createOrder(symbol, "stop_market", exitSide, qty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1143
+ }
1144
+
1145
+ async onTrailingTakeCommit(payload: BrokerTrailingTakePayload): Promise<void> {
1146
+ const { symbol, newTakeProfitPrice, position } = payload;
1147
+ const exchange = await getFuturesExchange();
1148
+
1149
+ // Cancel existing TP order only โ€” filter by reduceOnly to avoid cancelling unrelated orders
1150
+ const orders = await exchange.fetchOpenOrders(symbol);
1151
+ const tpOrder = orders.find((o) =>
1152
+ !!o.reduceOnly &&
1153
+ ["limit", "LIMIT"].includes(o.type ?? "")
1154
+ ) ?? null;
1155
+ if (tpOrder) {
1156
+ await exchange.cancelOrder(tpOrder.id, symbol);
1157
+ await sleep(CANCEL_SETTLE_MS);
1158
+ }
1159
+
1160
+ const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1161
+ const exitSide = position === "long" ? "sell" : "buy";
1162
+
1163
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1164
+ if (qty === 0) {
1165
+ throw new Error(`TrailingTake skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1166
+ }
1167
+
1168
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, newTakeProfitPrice));
1169
+ const positionSide = toPositionSide(position);
1170
+
1171
+ // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
1172
+ await exchange.createOrder(symbol, "limit", exitSide, qty, tpPrice, { reduceOnly: true, positionSide });
1173
+ }
1174
+
1175
+ async onBreakevenCommit(payload: BrokerBreakevenPayload): Promise<void> {
1176
+ const { symbol, newStopLossPrice, position } = payload;
1177
+ const exchange = await getFuturesExchange();
1178
+
1179
+ // Cancel existing SL order only โ€” filter by reduceOnly to avoid cancelling unrelated orders
1180
+ const orders = await exchange.fetchOpenOrders(symbol);
1181
+ const slOrder = orders.find((o) =>
1182
+ !!o.reduceOnly &&
1183
+ ["stop_market", "stop", "STOP_MARKET"].includes(o.type ?? "")
1184
+ ) ?? null;
1185
+ if (slOrder) {
1186
+ await exchange.cancelOrder(slOrder.id, symbol);
1187
+ await sleep(CANCEL_SETTLE_MS);
1188
+ }
1189
+
1190
+ const qty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1191
+ const exitSide = position === "long" ? "sell" : "buy";
1192
+
1193
+ // Position may have already been closed by SL/TP on exchange โ€” skip gracefully
1194
+ if (qty === 0) {
1195
+ throw new Error(`Breakeven skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1196
+ }
1197
+
1198
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, newStopLossPrice));
1199
+ const positionSide = toPositionSide(position);
1200
+
1201
+ // positionSide required in hedge mode (-4061 without it); ignored in one-way mode
1202
+ await exchange.createOrder(symbol, "stop_market", exitSide, qty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1203
+ }
1204
+
1205
+ async onAverageBuyCommit(payload: BrokerAverageBuyPayload): Promise<void> {
1206
+ const { symbol, currentPrice, cost, position, priceTakeProfit, priceStopLoss } = payload;
1207
+ const exchange = await getFuturesExchange();
1208
+
1209
+ // Cancel existing SL/TP first โ€” existing check must happen after cancel+settle
1210
+ // to avoid race condition where SL/TP fills between the existence check and cancel
1211
+ const openOrders = await exchange.fetchOpenOrders(symbol);
1212
+ await cancelAllOrders(exchange, openOrders, symbol);
1213
+ await sleep(CANCEL_SETTLE_MS);
1214
+
1215
+ // Guard against DCA into a ghost position โ€” checked after cancel so the snapshot is fresh
1216
+ const existing = await fetchContractsQty(exchange, symbol, position);
1217
+ const minNotional = exchange.markets[symbol].limits?.cost?.min ?? 1;
1218
+
1219
+ // Compare notional value rather than raw contracts โ€” avoids float === 0 trap
1220
+ // and correctly rejects dust positions left over from previous trades
1221
+ if (existing * currentPrice < minNotional) {
1222
+ throw new Error(`AverageBuy skipped: no open position for ${symbol} on exchange โ€” SL/TP may have already been filled`);
1223
+ }
1224
+
1225
+ const qty = truncateQty(exchange, symbol, cost / currentPrice);
1226
+
1227
+ // Guard: truncation may produce 0 if cost/price is below lot size
1228
+ if (qty <= 0) {
1229
+ throw new Error(`Computed qty is zero for ${symbol} โ€” cost=${cost}, price=${currentPrice}`);
1230
+ }
1231
+
1232
+ const entryPrice = parseFloat(exchange.priceToPrecision(symbol, currentPrice));
1233
+ const tpPrice = parseFloat(exchange.priceToPrecision(symbol, priceTakeProfit));
1234
+ const slPrice = parseFloat(exchange.priceToPrecision(symbol, priceStopLoss));
1235
+ // positionSide required in hedge mode to add to correct side; ignored in one-way mode
1236
+ const positionSide = toPositionSide(position);
1237
+ const entrySide = position === "long" ? "buy" : "sell";
1238
+ const exitSide = position === "long" ? "sell" : "buy";
1239
+
1240
+ // DCA entry: restore SL/TP on existing qty if times out so position is not left unprotected
1241
+ await createLimitOrderAndWait(
1242
+ exchange, symbol, entrySide, qty, entryPrice,
1243
+ { positionSide },
1244
+ { exitSide, tpPrice, slPrice, positionSide: position }
1245
+ );
1246
+
1247
+ // Refetch contracts after fill โ€” existing snapshot is stale after cancel + fill
1248
+ const totalQty = truncateQty(exchange, symbol, await fetchContractsQty(exchange, symbol, position));
1249
+
1250
+ // Recreate SL/TP on fresh total qty after successful fill
1251
+ try {
1252
+ await exchange.createOrder(symbol, "limit", exitSide, totalQty, tpPrice, { reduceOnly: true, positionSide });
1253
+ await exchange.createOrder(symbol, "stop_market", exitSide, totalQty, undefined, { stopPrice: slPrice, reduceOnly: true, positionSide });
1254
+ } catch (err) {
1255
+ // Total position is unprotected โ€” close via market
1256
+ await exchange.createOrder(symbol, "market", exitSide, totalQty, undefined, { reduceOnly: true, positionSide });
1257
+ throw err;
1258
+ }
1259
+ }
1260
+ }
1261
+ );
1262
+
1263
+ Broker.enable();
1264
+ ```
1265
+
1266
+ </details>
1267
+
1268
+ #### Internals
1269
+
1270
+ Signal open/close events are routed automatically via an internal event bus once `Broker.enable()` is called. **No manual wiring needed.** All other operations (`partialProfit`, `trailingStop`, `breakeven`, `averageBuy`) are intercepted explicitly before the corresponding state mutation.
1271
+
1272
+ ### ๐Ÿ” How Cron Works
1273
+
1274
+ `Cron` is a periodic / fire-once scheduler that runs in **virtual time** โ€” the same time stream your strategies see in backtest mode. Handlers fire on candle-interval boundaries (`1m`, `5m`, `1h`, `1d`, โ€ฆ) and are coordinated across parallel `Backtest.background(symbol, ...)` runs so the same boundary never produces two concurrent invocations.
1275
+
1276
+ **Public API:**
1277
+ - **`Cron.register({ name, interval?, symbols?, handler })`** โ€” register a job. Returns a disposer. Re-registering the same `name` replaces the previous entry and bumps an internal generation counter (late writes from old handlers are ignored).
1278
+ - **`Cron.enable()`** โ€” subscribe `Cron` to the engine's lifecycle subjects (`beforeStart`, `idlePing`, `activePing`, `schedulePing`). Wrapped in `singleshot`; call once at startup.
1279
+ - **`Cron.disable()`** โ€” tear down the subscriptions installed by `enable()`. Safe to call multiple times and before `enable()`.
1280
+ - **`Cron.unregister(name)`** โ€” remove a registered job.
1281
+ - **`Cron.clear(symbol?)`** โ€” clear fire-once marks. `symbol` provided โ†’ fan-out marks for that symbol only; no argument โ†’ all marks. Does **not** touch in-flight handlers.
1282
+
1283
+ **Two modes per `interval`:**
1284
+ - **Periodic** (`interval: "1h"`) โ€” handler fires once per boundary of that interval.
1285
+ - **Fire-once** (`interval` omitted) โ€” handler fires on the first matching tick and never again until `clear()` / `unregister` / re-`register`.
1286
+
1287
+ **Two scopes per `symbols`:**
1288
+ - **Global** (`symbols` omitted) โ€” handler fires once per boundary across all parallel backtests. First symbol to reach the boundary opens the slot; others await the same promise.
1289
+ - **Fan-out** (`symbols: ["BTC", "ETH"]`) โ€” handler fires once per boundary **per whitelisted symbol**. Each symbol has its own slot.
1290
+
1291
+ <details>
1292
+ <summary>
1293
+ The code
1294
+ </summary>
1295
+
1296
+ ```typescript
1297
+ import { Cron, Backtest } from "backtest-kit";
1298
+
1299
+ // Global hourly job โ€” fires once per virtual hour across all parallel backtests.
1300
+ Cron.register({
1301
+ name: "tg-signal-parser",
1302
+ interval: "1h",
1303
+ handler: async ({ symbol, when, backtest }) => {
1304
+ await parseTelegramSignalsToMongo(when);
1305
+ },
1306
+ });
1307
+
1308
+ // Per-symbol fan-out โ€” fires once per hour per whitelisted symbol.
1309
+ Cron.register({
1310
+ name: "fetch-funding",
1311
+ interval: "1h",
1312
+ symbols: ["BTCUSDT", "ETHUSDT"],
1313
+ handler: async ({ symbol, when, backtest }) => {
1314
+ await fetchFundingRate(symbol, when);
1315
+ },
1316
+ });
1317
+
1318
+ // Fire-once warm-up โ€” runs once globally on the very first tick.
1319
+ Cron.register({
1320
+ name: "warm-cache",
1321
+ handler: async ({ symbol, when, backtest }) => {
1322
+ await warmupCache();
1323
+ },
1324
+ });
1325
+
1326
+ // Wire Cron to the engine once at startup. After this every strategy tick is
1327
+ // forwarded into Cron automatically โ€” no manual listener wiring needed.
1328
+ Cron.enable();
1329
+
1330
+ for (const symbol of ["BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT", "TRXUSDT"]) {
1331
+ Backtest.background(symbol, { strategyName, exchangeName, frameName });
1332
+ }
1333
+
1334
+ // On shutdown:
1335
+ // Cron.disable();
1336
+ ```
1337
+
1338
+ </details>
1339
+
1340
+ #### Internals
1341
+
1342
+ `Cron.enable()` subscribes a single `singlerun`-wrapped handler to four lifecycle subjects (`beforeStart`, `idlePing`, `activePing`, `schedulePing`). `singlerun` merges all four streams into one serial queue, so concurrent ticks on the same `(symbol, virtual-minute)` cannot race to open the same slot. Each incoming tick is **base-aligned to the 1-minute boundary** before any further processing โ€” lifecycle pings may carry sub-second jitter, but Cron always reasons in whole minutes.
1343
+
1344
+ Coordination keys are built as `${name}:${alignedMs}:${symbol?}:g${generation}`. Parallel backtests that hit the same key share a single in-flight promise (mutex semantics): the first opens the slot and runs the handler, others `await` the same promise and release together. After `.finally()` the slot is removed and the next boundary creates a fresh promise. Fire-once entries additionally record a `_firedOnce` mark on success so subsequent ticks skip them โ€” a failed handler is **not** marked, so it retries on the next tick. The generation suffix isolates re-registrations: a late write from a still-in-flight handler of a previous `register()` carries the old generation and never collides with the new entry.
1345
+
1346
+ ### ๐Ÿ” How getCandles Works
1347
+
1348
+ backtest-kit uses Node.js `AsyncLocalStorage` to automatically provide
1349
+ temporal time context to your strategies.
1350
+
1351
+ <details>
1352
+ <summary>
1353
+ The Math
1354
+ </summary>
1355
+
1356
+ For a candle with:
1357
+ - `timestamp` = candle open time (openTime)
1358
+ - `stepMs` = interval duration (e.g., 60000ms for "1m")
1359
+ - Candle close time = `timestamp + stepMs`
1360
+
1361
+ **Alignment:** All timestamps are aligned down to interval boundary.
1362
+ For example, for 15m interval: 00:17 โ†’ 00:15, 00:44 โ†’ 00:30
1363
+
1364
+ **Adapter contract:**
1365
+ - First candle.timestamp must equal aligned `since`
1366
+ - Adapter must return exactly `limit` candles
1367
+ - Sequential timestamps: `since + i * stepMs` for i = 0..limit-1
1368
+
1369
+ **How `since` is calculated from `when`:**
1370
+ - `when` = current execution context time (from AsyncLocalStorage)
1371
+ - `alignedWhen` = `Math.floor(when / stepMs) * stepMs` (aligned down to interval boundary)
1372
+ - `since` = `alignedWhen - limit * stepMs` (go back `limit` candles from aligned when)
1373
+
1374
+ **Boundary semantics (inclusive/exclusive):**
1375
+ - `since` is always **inclusive** โ€” first candle has `timestamp === since`
1376
+ - Exactly `limit` candles are returned
1377
+ - Last candle has `timestamp === since + (limit - 1) * stepMs` โ€” **inclusive**
1378
+ - For `getCandles`: `alignedWhen` is **exclusive** โ€” candle at that timestamp is NOT included (it's a pending/incomplete candle)
1379
+ - For `getRawCandles`: `eDate` is **exclusive** โ€” candle at that timestamp is NOT included (it's a pending/incomplete candle)
1380
+ - For `getNextCandles`: `alignedWhen` is **inclusive** โ€” first candle starts at `alignedWhen` (it's the current candle for backtest, already closed in historical data)
1381
+
1382
+ - `getCandles(symbol, interval, limit)` - Returns exactly `limit` candles
1383
+ - Aligns `when` down to interval boundary
1384
+ - Calculates `since = alignedWhen - limit * stepMs`
1385
+ - **since โ€” inclusive**, first candle.timestamp === since
1386
+ - **alignedWhen โ€” exclusive**, candle at alignedWhen is NOT returned
1387
+ - Range: `[since, alignedWhen)` โ€” half-open interval
1388
+ - Example: `getCandles("BTCUSDT", "1m", 100)` returns 100 candles ending before aligned when
1389
+
1390
+ - `getNextCandles(symbol, interval, limit)` - Returns exactly `limit` candles (backtest only)
1391
+ - Aligns `when` down to interval boundary
1392
+ - `since = alignedWhen` (starts from aligned when, going forward)
1393
+ - **since โ€” inclusive**, first candle.timestamp === since
1394
+ - Range: `[alignedWhen, alignedWhen + limit * stepMs)` โ€” half-open interval
1395
+ - Throws error in live mode to prevent look-ahead bias
1396
+ - Example: `getNextCandles("BTCUSDT", "1m", 10)` returns next 10 candles starting from aligned when
1397
+
1398
+ - `getRawCandles(symbol, interval, limit?, sDate?, eDate?)` - Flexible parameter combinations:
1399
+ - `(limit)` - since = alignedWhen - limit * stepMs, range `[since, alignedWhen)`
1400
+ - `(limit, sDate)` - since = align(sDate), returns `limit` candles forward, range `[since, since + limit * stepMs)`
1401
+ - `(limit, undefined, eDate)` - since = align(eDate) - limit * stepMs, **eDate โ€” exclusive**, range `[since, eDate)`
1402
+ - `(undefined, sDate, eDate)` - since = align(sDate), limit calculated from range, **sDate โ€” inclusive, eDate โ€” exclusive**, range `[sDate, eDate)`
1403
+ - `(limit, sDate, eDate)` - since = align(sDate), returns `limit` candles, **sDate โ€” inclusive**
1404
+ - All combinations respect look-ahead bias protection (eDate/endTime <= when)
1405
+
1406
+ **Persistent Cache:**
1407
+ - Cache lookup calculates expected timestamps: `since + i * stepMs` for i = 0..limit-1
1408
+ - Returns all candles if found, null if any missing (cache miss)
1409
+ - Cache and runtime use identical timestamp calculation logic
1410
+
1411
+ </details>
1412
+
1413
+ #### Candle Timestamp Convention:
1414
+
1415
+ According to this `timestamp` of a candle in backtest-kit is exactly the `openTime`, not ~~`closeTime`~~
1416
+
1417
+ **Key principles:**
1418
+ - All timestamps are aligned down to interval boundary
1419
+ - First candle.timestamp must equal aligned `since`
1420
+ - Adapter must return exactly `limit` candles
1421
+ - Sequential timestamps: `since + i * stepMs`
1422
+
1423
+
1424
+ ### ๐Ÿ” How getOrderBook Works
1425
+
1426
+ Order book fetching uses the same temporal alignment as candles, but with a configurable time offset window instead of candle intervals.
1427
+
1428
+ <details>
1429
+ <summary>
1430
+ The Math
1431
+ </summary>
1432
+
1433
+ **Time range calculation:**
1434
+ - `when` = current execution context time (from AsyncLocalStorage)
1435
+ - `offsetMinutes` = `CC_ORDER_BOOK_TIME_OFFSET_MINUTES` (configurable)
1436
+ - `alignedTo` = `Math.floor(when / (offsetMinutes * 60000)) * (offsetMinutes * 60000)`
1437
+ - `to` = `alignedTo` (aligned down to offset boundary)
1438
+ - `from` = `alignedTo - offsetMinutes * 60000`
1439
+
1440
+ **Adapter contract:**
1441
+ - `getOrderBook(symbol, depth, from, to, backtest)` is called on the exchange schema
1442
+ - `depth` defaults to `CC_ORDER_BOOK_MAX_DEPTH_LEVELS`
1443
+ - The `from`/`to` range represents a time window of exactly `offsetMinutes` duration
1444
+ - Schema implementation may use the time range (backtest) or ignore it (live trading)
1445
+
1446
+ **Example with CC_ORDER_BOOK_TIME_OFFSET_MINUTES = 10:**
1447
+ ```
1448
+ when = 1704067920000 // 2024-01-01 00:12:00 UTC
1449
+ offsetMinutes = 10
1450
+ offsetMs = 10 * 60000 // 600000ms
1451
+
1452
+ alignedTo = Math.floor(1704067920000 / 600000) * 600000
1453
+ = 1704067800000 // 2024-01-01 00:10:00 UTC
1454
+
1455
+ to = 1704067800000 // 00:10:00 UTC
1456
+ from = 1704067200000 // 00:00:00 UTC
1457
+ ```
1458
+ </details>
1459
+
1460
+ #### Order Book Timestamp Convention:
1461
+
1462
+ Unlike candles, most exchanges (e.g. Binance `GET /api/v3/depth`) only expose the **current** order book with no historical query support โ€” for backtest you must provide your own snapshot storage.
1463
+
1464
+ **Key principles:**
1465
+ - Time range is aligned down to `CC_ORDER_BOOK_TIME_OFFSET_MINUTES` boundary
1466
+ - `to` = aligned timestamp, `from` = `to - offsetMinutes * 60000`
1467
+ - `depth` defaults to `CC_ORDER_BOOK_MAX_DEPTH_LEVELS`
1468
+ - Adapter receives `(symbol, depth, from, to, backtest)` โ€” may ignore `from`/`to` in live mode
1469
+
1470
+ ### ๐Ÿ” How getAggregatedTrades Works
1471
+
1472
+ Aggregated trades fetching uses the same look-ahead bias protection as candles - `to` is always aligned down to the nearest minute boundary so future trades are never visible to the strategy.
1473
+
1474
+ **Key principles:**
1475
+ - `to` is always aligned down to the 1-minute boundary โ€” prevents look-ahead bias
1476
+ - Without `limit`: returns one full window (`CC_AGGREGATED_TRADES_MAX_MINUTES`)
1477
+ - With `limit`: paginates backwards until collected, then slices to most recent `limit`
1478
+ - Adapter receives `(symbol, from, to, backtest)` โ€” may ignore `from`/`to` in live mode
1479
+
1480
+ <details>
1481
+ <summary>
1482
+ The Math
1483
+ </summary>
1484
+
1485
+ **Time range calculation:**
1486
+ - `when` = current execution context time (from AsyncLocalStorage)
1487
+ - `alignedTo` = `Math.floor(when / 60000) * 60000` (aligned down to 1-minute boundary)
1488
+ - `windowMs` = `CC_AGGREGATED_TRADES_MAX_MINUTES * 60000 โˆ’ 60000`
1489
+ - `to` = `alignedTo`, `from` = `alignedTo โˆ’ windowMs`
1490
+
1491
+ **Without `limit`:** fetches a single window and returns it as-is.
1492
+
1493
+ **With `limit`:** paginates backwards in `CC_AGGREGATED_TRADES_MAX_MINUTES` chunks until at least `limit` trades are collected, then slices to the most recent `limit` trades.
1494
+
1495
+ **Example with CC_AGGREGATED_TRADES_MAX_MINUTES = 60, limit = 200:**
1496
+ ```
1497
+ when = 1704067920000 // 2024-01-01 00:12:00 UTC
1498
+ alignedTo = 1704067800000 // 2024-01-01 00:12:00 โ†’ aligned to 00:12:00
1499
+ windowMs = 59 * 60000 // 3540000ms = 59 minutes
1500
+
1501
+ Window 1: from = 00:12:00 โˆ’ 59m = 23:13:00
1502
+ to = 00:12:00
1503
+ โ†’ got 120 trades โ€” not enough
1504
+
1505
+ Window 2: from = 23:13:00 โˆ’ 59m = 22:14:00
1506
+ to = 23:13:00
1507
+ โ†’ got 100 more โ†’ total 220 trades
1508
+
1509
+ result = last 200 of 220 (most recent)
1510
+ ```
1511
+
1512
+ **Adapter contract:**
1513
+ - `getAggregatedTrades(symbol, from, to, backtest)` is called on the exchange schema
1514
+ - `from`/`to` are `Date` objects
1515
+ - Schema implementation may use the time range (backtest) or ignore it (live trading)
1516
+
1517
+ </details>
1518
+
1519
+ #### Aggregated Trades Timestamp Convention:
1520
+
1521
+ **Compatible with:** [garch](https://www.npmjs.com/package/garch) for volatility modelling and [volume-anomaly](https://www.npmjs.com/package/volume-anomaly) for detecting abnormal trade volume โ€” both accept the same `from`/`to` time range format that `getAggregatedTrades` produces.
1522
+
1523
+ ### ๐Ÿ”ฌ Technical Details: Timestamp Alignment
1524
+
1525
+ **Why align timestamps to interval boundaries?**
1526
+
1527
+ Because candle APIs return data starting from exact interval boundaries:
1528
+
1529
+ ```typescript
1530
+ // 15-minute interval example:
1531
+ when = 1704067920000 // 00:12:00
1532
+ step = 15 // 15 minutes
1533
+ stepMs = 15 * 60000 // 900000ms
1534
+
1535
+ // Alignment: round down to nearest interval boundary
1536
+ alignedWhen = Math.floor(when / stepMs) * stepMs
1537
+ // = Math.floor(1704067920000 / 900000) * 900000
1538
+ // = 1704067200000 (00:00:00)
1539
+
1540
+ // Calculate since for 4 candles backwards:
1541
+ since = alignedWhen - 4 * stepMs
1542
+ // = 1704067200000 - 4 * 900000
1543
+ // = 1704063600000 (23:00:00 previous day)
1544
+
1545
+ // Expected candles:
1546
+ // [0] timestamp = 1704063600000 (23:00)
1547
+ // [1] timestamp = 1704064500000 (23:15)
1548
+ // [2] timestamp = 1704065400000 (23:30)
1549
+ // [3] timestamp = 1704066300000 (23:45)
1550
+ ```
1551
+
1552
+ **Pending candle exclusion:** The candle at `00:00:00` (alignedWhen) is NOT included in the result. At `when=00:12:00`, this candle covers the period `[00:00, 00:15)` and is still open (pending). Pending candles have incomplete OHLCV data that would distort technical indicators. Only fully closed candles are returned.
1553
+
1554
+ **Validation is applied consistently across:**
1555
+ - โœ… `getCandles()` - validates first timestamp and count
1556
+ - โœ… `getNextCandles()` - validates first timestamp and count
1557
+ - โœ… `getRawCandles()` - validates first timestamp and count
1558
+ - โœ… Cache read - calculates exact expected timestamps
1559
+ - โœ… Cache write - stores validated candles
1560
+
1561
+ **Result:** Deterministic candle retrieval with exact timestamp matching.
1562
+
1563
+ ### ๐Ÿ• Timezone Warning: Candle Boundaries Are UTC-Based
1564
+
1565
+ All candle timestamp alignment uses UTC (Unix epoch). For intervals like `4h`, boundaries are `00:00, 04:00, 08:00, 12:00, 16:00, 20:00 UTC`. If your local timezone offset is not a multiple of the interval, the `since` timestamps will look "uneven" in local time.
1566
+
1567
+ For example, in UTC+5 the same 4h candle request logs as:
1568
+
1569
+ ```
1570
+ since: Sat Sep 20 2025 13:00:00 GMT+0500 โ† looks uneven (13:00)
1571
+ since: Sat Sep 20 2025 17:00:00 GMT+0500 โ† looks uneven (17:00)
1572
+ since: Sat Sep 20 2025 21:00:00 GMT+0500 โ† looks uneven (21:00)
1573
+ since: Sun Sep 21 2025 05:00:00 GMT+0500 โ† looks uneven (05:00)
1574
+ ```
1575
+
1576
+ But in UTC these are perfectly aligned 4h boundaries:
1577
+
1578
+ ```
1579
+ since: Sat, 20 Sep 2025 08:00:00 GMT โ† 08:00 UTC โœ“
1580
+ since: Sat, 20 Sep 2025 12:00:00 GMT โ† 12:00 UTC โœ“
1581
+ since: Sat, 20 Sep 2025 16:00:00 GMT โ† 16:00 UTC โœ“
1582
+ since: Sun, 21 Sep 2025 00:00:00 GMT โ† 00:00 UTC โœ“
1583
+ ```
1584
+
1585
+ Use `toUTCString()` or `toISOString()` in callbacks to see the actual aligned UTC times.
1586
+
1587
+ ### ๐Ÿ’ญ What this means:
1588
+ - `getCandles()` always returns data UP TO the current backtest timestamp using `async_hooks`
1589
+ - Multi-timeframe data is automatically synchronized
1590
+ - **Impossible to introduce look-ahead bias** - all time boundaries are enforced
1591
+ - Same code works in both backtest and live modes
1592
+ - Boundary semantics prevent edge cases in signal generation
1593
+
1594
+
1595
+ ## ๐Ÿง  Two Ways to Run the Engine
1596
+
1597
+ Backtest Kit exposes the same runtime in two equivalent forms. Both approaches use **the same engine and guarantees** - only the consumption model differs.
1598
+
1599
+ ### 1๏ธโƒฃ Event-driven (background execution)
1600
+
1601
+ Suitable for production bots, monitoring, and long-running processes.
1602
+
1603
+ ```typescript
1604
+ Backtest.background('BTCUSDT', config);
1605
+
1606
+ listenSignalBacktest(event => { /* handle signals */ });
1607
+ listenDoneBacktest(event => { /* finalize / dump report */ });
1608
+ ```
1609
+
1610
+ ### 2๏ธโƒฃ Async Iterator (pull-based execution)
1611
+
1612
+ Suitable for research, scripting, testing, and LLM agents.
1613
+
1614
+ ```typescript
1615
+ for await (const event of Backtest.run('BTCUSDT', config)) {
1616
+ // signal | trade | progress | done
1617
+ }
1618
+ ```
1619
+
1620
+ ## โš”๏ธ Think of it as...
1621
+
1622
+ **Open-source QuantConnect/MetaTrader without the vendor lock-in**
1623
+
1624
+ Unlike cloud-based platforms, backtest-kit runs entirely in your environment. You own the entire stack from data ingestion to live execution. In addition to Ollama, you can use [neural-trader](https://www.npmjs.com/package/neural-trader) in `getSignal` function or any other third party library
1625
+
1626
+ - No C#/C++ required - pure TypeScript/JavaScript
1627
+ - Self-hosted - your code, your data, your infrastructure
1628
+ - No platform fees or hidden costs
1629
+ - Full control over execution and data sources
1630
+ - [GUI](https://npmjs.com/package/@backtest-kit/ui) for visualization and monitoring
1631
+
1632
+ ## ๐ŸŒ Ecosystem
1633
+
1634
+ The `backtest-kit` ecosystem extends beyond the core library, offering complementary packages and tools to enhance your trading system development experience:
1635
+
1636
+
1637
+ ### @backtest-kit/cli
1638
+
1639
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/cli)** ๐Ÿ“Ÿ
1640
+
1641
+ The **@backtest-kit/cli** package is a zero-boilerplate CLI runner for backtest-kit strategies. Point it at your strategy file and run backtests, paper trading, or live bots โ€” no infrastructure code required.
1642
+
1643
+ #### Key Features
1644
+ - ๐Ÿš€ **Zero Config**: Run a backtest with one command โ€” no setup code needed
1645
+ - ๐Ÿ”„ **Three Modes**: `--backtest`, `--paper`, `--live` with graceful SIGINT shutdown
1646
+ - ๐Ÿ’พ **Auto Cache**: Warms OHLCV candle cache for all intervals before the backtest starts
1647
+ - ๐ŸŒ **Web Dashboard**: Launch `@backtest-kit/ui` with a single `--ui` flag
1648
+ - ๐Ÿ“ฌ **Telegram Alerts**: Formatted trade notifications with price charts via `--telegram`
1649
+ - ๐Ÿ—‚๏ธ **Monorepo Ready**: Each strategy's `dump/`, `modules/`, and `template/` are automatically isolated by entry point directory
1650
+
1651
+ #### Use Case
1652
+ The fastest way to run any backtest-kit strategy from the command line. Instead of writing boilerplate for storage, notifications, candle caching, and signal logging, add one dependency and wire up your `package.json` scripts. Works equally well for a single-strategy project or a monorepo with dozens of strategies in separate subdirectories.
1653
+
1654
+ #### Get Started
1655
+ ```bash
1656
+ npx -y @backtest-kit/cli --init
1657
+ ```
1658
+
1659
+
1660
+ ### @backtest-kit/pinets
1661
+
1662
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/pinets)** ๐Ÿ“œ
1663
+
1664
+ The **@backtest-kit/pinets** package lets you run TradingView Pine Script strategies directly in Node.js. Port your existing Pine Script indicators to backtest-kit with zero rewrite using the [PineTS](https://github.com/QuantForgeOrg/PineTS) runtime.
1665
+
1666
+ #### Key Features
1667
+ - ๐Ÿ“œ **Pine Script v5/v6**: Native TradingView syntax with 1:1 compatibility
1668
+ - ๐ŸŽฏ **60+ Indicators**: SMA, EMA, RSI, MACD, Bollinger Bands, ATR, Stochastic built-in
1669
+ - ๐Ÿ“ **File or Code**: Load `.pine` files or pass code strings directly
1670
+ - ๐Ÿ—บ๏ธ **Plot Extraction**: Flexible mapping from Pine `plot()` outputs to structured signals
1671
+ - โšก **Cached Execution**: Memoized file reads for repeated strategy runs
1672
+
1673
+ #### Use Case
1674
+ Perfect for traders who already have working TradingView strategies. Instead of rewriting your Pine Script logic in JavaScript, simply copy your `.pine` file and use `getSignal()` to extract trading signals. Works seamlessly with backtest-kit's temporal context - no look-ahead bias possible.
1675
+
1676
+ #### Get Started
1677
+ ```bash
1678
+ npm install @backtest-kit/pinets pinets backtest-kit
1679
+ ```
1680
+
1681
+
1682
+ ### @backtest-kit/graph
1683
+
1684
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/graph)** ๐Ÿ”—
1685
+
1686
+ The **@backtest-kit/graph** package lets you compose backtest-kit computations as a typed directed acyclic graph (DAG). Define source nodes that fetch market data and output nodes that compute derived values โ€” then resolve the whole graph in topological order with automatic parallelism.
1687
+
1688
+ #### Key Features
1689
+ - ๐Ÿ”Œ **DAG Execution**: Nodes are resolved bottom-up in topological order with `Promise.all` parallelism
1690
+ - ๐Ÿ”’ **Type-Safe Values**: TypeScript infers the return type of every node through the graph via generics
1691
+ - ๐Ÿงฑ **Two APIs**: Low-level `INode` for runtime/storage, high-level `sourceNode` + `outputNode` builders for authoring
1692
+ - ๐Ÿ’พ **DB-Ready Serialization**: `serialize` / `deserialize` convert the graph to a flat `IFlatNode[]` list with `id` / `nodeIds`
1693
+ - ๐ŸŒ **Context-Aware Fetch**: `sourceNode` receives `(symbol, when, exchangeName)` from the execution context automatically
1694
+
1695
+ #### Use Case
1696
+ Perfect for multi-timeframe strategies where multiple Pine Script or indicator computations must be combined. Instead of manually chaining async calls, define each computation as a node and let the graph resolve dependencies in parallel. Adding a new filter or timeframe requires no changes to the existing wiring.
1697
+
1698
+ #### Get Started
1699
+ ```bash
1700
+ npm install @backtest-kit/graph backtest-kit
1701
+ ```
1702
+
1703
+
1704
+ ### @backtest-kit/ui
1705
+
1706
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/ui)** ๐Ÿ“Š
1707
+
1708
+ The **@backtest-kit/ui** package is a full-stack UI framework for visualizing cryptocurrency trading signals, backtests, and real-time market data. Combines a Node.js backend server with a React dashboard - all in one package.
1709
+
1710
+ #### Key Features
1711
+ - ๐Ÿ“ˆ **Interactive Charts**: Candlestick visualization with Lightweight Charts (1m, 15m, 1h timeframes)
1712
+ - ๐ŸŽฏ **Signal Tracking**: View opened, closed, scheduled, and cancelled signals with full details
1713
+ - ๐Ÿ“Š **Risk Analysis**: Monitor risk rejections and position management
1714
+ - ๐Ÿ”” **Notifications**: Real-time notification system for all trading events
1715
+ - ๐Ÿ’น **Trailing & Breakeven**: Visualize trailing stop/take and breakeven events
1716
+ - ๐ŸŽจ **Material Design**: Beautiful UI with MUI 5 and Mantine components
1717
+
1718
+ #### Use Case
1719
+ Perfect for monitoring your trading bots in production. Instead of building custom dashboards, `@backtest-kit/ui` provides a complete visualization layer out of the box. Each signal view includes detailed information forms, multi-timeframe candlestick charts, and JSON export for all data.
1720
+
1721
+ #### Get Started
1722
+ ```bash
1723
+ npm install @backtest-kit/ui backtest-kit ccxt
1724
+ ```
1725
+
1726
+
1727
+ ### @backtest-kit/mongo
1728
+
1729
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/mongo)** ๐Ÿ’พ
1730
+
1731
+ The **@backtest-kit/mongo** package replaces the default file-based `./dump/` storage with MongoDB as the source of truth and Redis as an O(1) lookup cache. All 15 `IPersist*Instance` contracts from backtest-kit are implemented โ€” strategy code stays unchanged.
1732
+
1733
+ #### Key Features
1734
+ - ๐Ÿ—„๏ธ **MongoDB Backend**: All 15 persistence adapters implemented with Mongoose and unique compound indexes
1735
+ - โšก **O(1) Reads via Redis**: Every context-key lookup goes through ioredis โ€” one `GET` + one `findById`, no B-tree scans
1736
+ - ๐Ÿ”’ **Atomic Writes**: `findOneAndUpdate` with `upsert: true` guarantees read-after-write correctness with no race conditions
1737
+ - ๐Ÿ›ก๏ธ **Look-Ahead Bias Protection**: Adapters that affect signal logic store the simulation timestamp so backtest-kit can enforce temporal correctness
1738
+ - ๐Ÿชฆ **Soft Delete**: Measure, Interval, and Memory records carry a `removed` flag instead of being physically deleted
1739
+ - ๐Ÿ”Œ **Zero Strategy Changes**: Drop `setup()` into your entry point, everything else stays the same
1740
+
1741
+ #### Use Case
1742
+ Perfect for production deployments where the default file-based storage is a bottleneck or a reliability concern. During backtests, backtest-kit performs thousands of context-keyed reads per second โ€” Redis eliminates the per-request B-tree traversal and makes repeated reads effectively free. MongoDB provides durability, atomic upserts, and a queryable signal history that survives process restarts.
1743
+
1744
+ #### Get Started
1745
+ ```bash
1746
+ npm install @backtest-kit/mongo backtest-kit mongoose ioredis
1747
+ ```
1748
+
1749
+
1750
+ ### @backtest-kit/ollama
1751
+
1752
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/ollama)** ๐Ÿค–
1753
+
1754
+ The **@backtest-kit/ollama** package is a multi-provider LLM inference library that supports 10+ providers including OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, and Ollama with unified API and automatic token rotation.
1755
+
1756
+ #### Key Features
1757
+ - ๐Ÿ”Œ **10+ LLM Providers**: OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, Ollama
1758
+ - ๐Ÿ”„ **Token Rotation**: Automatic API key rotation for Ollama (others throw clear errors)
1759
+ - ๐ŸŽฏ **Structured Output**: Enforced JSON schema for trading signals (position, price levels, risk notes)
1760
+ - ๐Ÿ”‘ **Flexible Auth**: Context-based API keys or environment variables
1761
+ - โšก **Unified API**: Single interface across all providers
1762
+ - ๐Ÿ“Š **Trading-First**: Built for backtest-kit with position sizing and risk management
1763
+
1764
+ #### Use Case
1765
+ Ideal for building multi-provider LLM strategies with fallback chains and ensemble predictions. The package returns structured trading signals with validated TP/SL levels, making it perfect for use in `getSignal` functions. Supports both backtest and live trading modes.
1766
+
1767
+ #### Get Started
1768
+ ```bash
1769
+ npm install @backtest-kit/ollama agent-swarm-kit backtest-kit
1770
+ ```
1771
+
1772
+
1773
+ ### @backtest-kit/signals
1774
+
1775
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/signals)** ๐Ÿ“Š
1776
+
1777
+ The **@backtest-kit/signals** package is a technical analysis and trading signal generation library designed for AI-powered trading systems. It computes 50+ indicators across 4 timeframes and generates markdown reports optimized for LLM consumption.
1778
+
1779
+ #### Key Features
1780
+ - ๐Ÿ“ˆ **Multi-Timeframe Analysis**: 1m, 15m, 30m, 1h with synchronized indicator computation
1781
+ - ๐ŸŽฏ **50+ Technical Indicators**: RSI, MACD, Bollinger Bands, Stochastic, ADX, ATR, CCI, Fibonacci, Support/Resistance
1782
+ - ๐Ÿ“Š **Order Book Analysis**: Bid/ask depth, spread, liquidity imbalance, top 20 levels
1783
+ - ๐Ÿค– **AI-Ready Output**: Markdown reports formatted for LLM context injection
1784
+ - โšก **Performance Optimized**: Intelligent caching with configurable TTL per timeframe
1785
+
1786
+ #### Use Case
1787
+ Perfect for injecting comprehensive market context into your LLM-powered strategies. Instead of manually calculating indicators, `@backtest-kit/signals` provides a single function call that adds all technical analysis to your message context. Works seamlessly with `getSignal` function in backtest-kit strategies.
1788
+
1789
+ #### Get Started
1790
+ ```bash
1791
+ npm install @backtest-kit/signals backtest-kit
1792
+ ```
1793
+
1794
+
1795
+ ### @backtest-kit/sidekick
1796
+
1797
+ > **[Explore on NPM](https://www.npmjs.com/package/@backtest-kit/sidekick)** ๐Ÿš€
1798
+
1799
+ The **@backtest-kit/sidekick** package scaffolds a project where **all wiring is visible and editable** in your project files โ€” exchange adapter, frame definitions, risk rules, strategy logic, and the runner script. Think of it as the **eject** of `@backtest-kit/cli --init`: instead of the boilerplate being hidden inside the CLI package, it lives directly in your project.
1800
+
1801
+ #### Key Features
1802
+ - ๐Ÿš€ **Zero Config**: Get started with one command - no setup required
1803
+ - ๐Ÿ“ฆ **Complete Template**: Includes backtest strategy, risk management, and LLM integration
1804
+ - ๐Ÿค– **AI-Powered**: Pre-configured with DeepSeek, Claude, and GPT-5 fallback chain
1805
+ - ๐Ÿ“Š **Technical Analysis**: Built-in 50+ indicators via @backtest-kit/signals
1806
+ - ๐Ÿ”‘ **Environment Setup**: Auto-generated .env with all API key placeholders
1807
+ - ๐Ÿ“ **Best Practices**: Production-ready code structure with examples
1808
+
1809
+ #### Use Case
1810
+ The fastest way to bootstrap a new trading bot project. Instead of manually setting up dependencies, configurations, and boilerplate code, simply run one command and get a working project with LLM-powered strategy, multi-timeframe technical analysis, and risk management validation.
1811
+
1812
+ #### Get Started
1813
+ ```bash
1814
+ npx -y @backtest-kit/sidekick my-trading-bot
1815
+ cd my-trading-bot
1816
+ npm start
1817
+ ```
1818
+
1819
+
1820
+ ## ๐Ÿ‘ช Community
1821
+
1822
+ ### backtest-monorepo-parallel
1823
+
1824
+ > **[Explore on GitHub](https://github.com/backtest-kit/backtest-monorepo-parallel)** ๐ŸŽ๏ธ
1825
+
1826
+ The **backtest-monorepo-parallel** repository is a TypeScript monorepo template that runs **9 symbols in parallel** in a single Node process on top of shared Mongo + Redis infrastructure, with a self-enforcement runtime that exposes the workspace DI container to `./content/` strategy files. No wiring, no bundler hooks, no strategy-author changes.
1827
+
1828
+ #### Key Features
1829
+ - โšก **~6 300ร— Real-Time Aggregate**: 9 symbols ร— ~703ร— per-symbol replay speed, ~103 events/sec in the hot `listenActivePing โ†’ commitAverageBuy` loop on a commodity i5-13420H laptop
1830
+ - ๐Ÿงต **Single-Process Concurrency**: All 9 `Backtest.background(...)` contexts share one event loop, one Mongo pool, one Redis pool โ€” no IPC, no fork overhead
1831
+ - ๐Ÿ’‰ **DI Surface**: Workspace services typed via rolled-up `types.d.ts` and reachable from strategy files at evaluation time
1832
+ - ๐Ÿ—‚๏ธ **Mode A / Mode B**: `--entry` flag toggles between parallel runner (`CC_SYMBOL_LIST` fan-out) and single-strategy CLI mode
1833
+ - ๐Ÿงฉ **Linear Scaling Recipe**: Adding a service = +1 file, +1 symbol, +1 provider, +1 ioc entry โ€” no churn under `./content/`
1834
+
1835
+ #### Use Case
1836
+ Use when you need to backtest many symbols concurrently against the same strategy without spawning subprocesses, and want a scaffold where new services, collections, and Redis caches drop in alongside existing ones without restructuring. Ideal as the starting point for a production parallel-symbol backtesting setup.
1837
+
1838
+ #### Get Started
1839
+ ```bash
1840
+ git clone https://github.com/backtest-kit/backtest-monorepo-parallel.git
1841
+ ```
1842
+
1843
+
1844
+ ### backtest-ollama-crontab
1845
+
1846
+ > **[Explore on GitHub](https://github.com/backtest-kit/backtest-ollama-crontab)** ๐Ÿ 
1847
+
1848
+ The **backtest-ollama-crontab** repository is a TypeScript monorepo template that wires a cloud/local **Ollama** into a trading-signal pipeline as a risk filter, with a **15-minute crontab** ingesting signals from any public Telegram channel. The **same code runs in both live and backtest modes** โ€” the crontab re-polls live and pulls the entire frame at startup in backtest.
1849
+
1850
+ #### Key Features
1851
+ - ๐Ÿค– **Local/Cloud LLM Risk Filter**: Per-signal verdict from local Ollama (`gpt-oss` quantized) returning `riskAction: "skip" | "follow"`, with empirical rules embedded in the system prompt and tunable without recompiling packages
1852
+ - โฐ **Crontab-Driven Ingestion**: `Cron.register(..., interval: "15m")` for live re-polling of the Telegram channel, plus a fire-once `Cron.register(...)` (no `interval`) for backtest-time bulk prepare โ€” same code path in both modes
1853
+ - ๐Ÿ“ก **Telegram MTProto Crawler**: QR-code session auth, `iterMessages` pull from any public channel into a `parser-items` Mongo collection, regex extraction of `direction / entry / targets / stoploss` into `screen-items`
1854
+ - ๐Ÿง  **Outline-Based Risk Logic**: Risk outline ingests 1m/15m candles + a pre-computed metrics packet (`avgRangePct`, `momentum24hPct`) and produces a zod-validated verdict consumed by the strategy
1855
+ - ๐Ÿ“ˆ **Reproducible Backtest Comparison**: same parsed-signal set, two backtests side-by-side โ€” **+52.22% โ†’ +68.90%** total PNL, Sharpe **+0.309 โ†’ +0.512**, winrate **68% โ†’ 82%**, profit factor **2.73 โ†’ 6.37** with the LLM gate enabled
1856
+
1857
+ #### Use Case
1858
+ Reference for integrating any local LLM into a backtest-kit pipeline as a signal filter, and for combining periodic crontab pulls (live) with one-shot bulk prepare (backtest) via the same `Cron.register` API.
1859
+
1860
+ #### Get Started
1861
+ ```bash
1862
+ git clone https://github.com/backtest-kit/backtest-ollama-crontab.git
1863
+ ```
1864
+
1865
+
1866
+ ### backtest-kit-redis-mongo-docker
1867
+
1868
+ > **[Explore on GitHub](https://github.com/backtest-kit/backtest-kit-redis-mongo-docker)** ๐Ÿณ
1869
+
1870
+ The **backtest-kit-redis-mongo-docker** repository is a production-grade integration that replaces the default file-based `./dump/` persistence with **MongoDB** as the source of truth and **Redis** as an O(1) lookup cache, packaged with `docker-compose` for one-command deploys.
1871
+
1872
+ #### Key Features
1873
+ - ๐Ÿ—‚๏ธ **15 Persist Adapters**: Full implementation of every `IPersist*Instance` contract (Candle, Signal, Schedule, Risk, Partial, Breakeven, Storage, Notification, Log, Measure, Interval, Memory, Recent, State, Session) on top of MongoDB + Redis
1874
+ - โš›๏ธ **Atomic Read-After-Write**: Single-round-trip `findOneAndUpdate` with unique compound indexes โ€” no E11000 leaks under concurrent writes
1875
+ - โšก **Redis O(1) Cache**: Per-domain `*CacheService` over `ioredis` for context-key โ†’ id lookups; cache miss falls back to Mongo and backfills automatically
1876
+ - ๐Ÿ›ก๏ธ **Look-Ahead Bias Protection**: Indexed `when: Number` column on every signal-affecting schema, fed by backtest-kit 9.0+'s `when: Date` adapter argument
1877
+ - ๐Ÿณ **Docker Compose Stack**: Separate compose files for Mongo and Redis plus a main container with networks; configurable via `CC_MONGO_CONNECTION_STRING` / `CC_REDIS_*` env vars
1878
+
1879
+ #### Use Case
1880
+ Drop-in persistence upgrade for any backtest-kit project that outgrows the default file-based `./dump/` layout โ€” strategy code, runners, and the CLI entry point stay unchanged. Use it when you need durable storage, concurrent-safe writes, fast restart recovery, or a containerized deployment for live and paper trading.
1881
+
1882
+ #### Get Started
1883
+ ```bash
1884
+ git clone https://github.com/backtest-kit/backtest-kit-redis-mongo-docker.git
1885
+ ```
1886
+
1887
+
1888
+ ### backtest-kit-skills
1889
+
1890
+ > **[Explore on GitHub](https://github.com/backtest-kit/backtest-kit-skills)** ๐Ÿค–
1891
+
1892
+ The **backtest-kit-skills** repository is a Claude Code agent skill and Mintlify documentation source for the backtest-kit framework โ€” AI-assisted strategy writing, debugging help, and full API reference in one place.
1893
+
1894
+ #### Key Features
1895
+ - ๐Ÿค– **Claude Code Skill**: Installed under `~/.claude/skills/backtest-kit/` โ€” strategy generation, debugging, and API reference
1896
+ - ๐Ÿ“– **Mintlify Docs**: Full documentation site runnable locally
1897
+ - ๐ŸŽฏ **Strategy Generation**: Complete TypeScript files with all schema registrations and runner setup
1898
+ - ๐Ÿ› **Debugging Help**: Catches common mistakes (missing `await`, wrong TP/SL direction, top-level commit calls)
1899
+ - ๐Ÿ“š **API Reference**: All schemas, commit functions, event listeners, LLM integration, graph pipelines, and persistence adapters
1900
+
1901
+ #### Use Case
1902
+ Install the skill once and get AI-assisted backtest-kit development inside Claude Code. The skill knows the full API surface โ€” schemas, commit functions, event listeners, broker adapters โ€” so you can describe what you want in plain language and get working TypeScript strategy code.
1903
+
1904
+ #### Get Started
1905
+ ```bash
1906
+ npx skills add https://github.com/backtest-kit/backtest-kit-skills
1907
+ ```
1908
+
1909
+
1910
+ ### uzse-backtest-app
1911
+
1912
+ > **[Explore on GitHub](https://github.com/backtest-kit/uzse-backtest-app)** ๐Ÿ“ˆ
1913
+
1914
+ The **uzse-backtest-app** repository is a reference implementation for running Pine Script strategies on regional stock exchanges not available on TradingView (UZSE, MSE, DSE, and others). It downloads raw trade history, builds Japanese candlesticks, and feeds them into backtest-kit via a custom MongoDB exchange adapter.
1915
+
1916
+ #### Key Features
1917
+ - ๐ŸŒ **Off-TradingView Markets**: Works with any exchange that exposes trade history โ€” no TradingView dependency
1918
+ - ๐Ÿ•ฏ๏ธ **Candle Builder**: Aggregates raw trades into 1m candles, fills intraday and non-trading day gaps, builds higher timeframes up to `1d`
1919
+ - ๐Ÿ—„๏ธ **MongoDB Backend**: Idempotent import with unique index โ€” re-runs never create duplicates
1920
+ - ๐Ÿ”Œ **Custom Exchange Adapter**: Connects MongoDB candles to backtest-kit via `addExchangeSchema`
1921
+ - ๐Ÿ“œ **Pine Script Support**: Full `@backtest-kit/pinets` integration โ€” run any Pine Script v5/v6 indicator on local market data
1922
+
1923
+ #### Use Case
1924
+ Perfect for traders working with emerging or regional markets absent from TradingView. Download trade history, build candles once, then use the full backtest-kit + Pine Script toolchain for backtesting and live signal generation โ€” with no dependency on any third-party charting platform.
1925
+
1926
+ #### Get Started
1927
+ ```bash
1928
+ git clone https://github.com/backtest-kit/uzse-backtest-app.git
1929
+ ```
1930
+
1931
+ ## ๐Ÿงฉ Strategy Examples
1932
+
1933
+ #### ๐Ÿง  Neural Network Strategy (Oct 2021)
1934
+
1935
+ > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/oct_2021.strategy)
1936
+
1937
+ Trains a feed-forward `TensorFlow` neural network (8โ†’6โ†’4โ†’1 architecture) every 8 hours to predict where the next candle will close within its high-low range. When current price is below predicted price, opens a LONG with 1% trailing take-profit.
1938
+
1939
+ #### ๐ŸŒฒ Pine Script Range Breakout (Dec 2025)
1940
+
1941
+ > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/dec_2025.strategy)
1942
+
1943
+ Runs `btc_dec2025_range.pine` on 1h candles via `@backtest-kit/pinets`, extracting Bollinger Bands, range boundaries, and volume spikes. Signals fire only on confirmed breakouts when price hasn't already moved past the signal close.
1944
+
1945
+ #### ๐Ÿ”ช Signal Inversion Strategy (Jan 2026)
1946
+
1947
+ > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/jan_2026.strategy)
1948
+
1949
+ The strategy takes published signals from a real Telegram crypto channel (Crypto Yoda), enters at the same price zone and timestamp, but **inverts the direction** and uses the liquidity of the crowd that blindly follows the recommendation regardless of the contents of the order book.
1950
+
1951
+ #### ๐Ÿ“ฐ AI News Sentiment (Feb 2026)
1952
+
1953
+ > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/feb_2026.strategy)
1954
+
1955
+ Every 4-8 hours, fetches live crypto/macro news via Tavily, passes headlines to Ollama (local LLM), and opens positions based on `bullish`/`bearish`/`wait` forecasts. Conflicting signals flip positions mid-trade. Achieved +16.99% during a -16.4% month.
1956
+
1957
+ #### ๐Ÿช‚ SHORT DCA Ladder (Mar 2026)
1958
+
1959
+ > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/mar_2026.strategy)
1960
+
1961
+ Opens a SHORT on every pending signal, then adds rungs (up to 10) whenever price spikes upward outside a ยฑ1-5% band around last entry. Closes at 0.5% blended profit.
1962
+
1963
+ #### ๐Ÿง— LONG DCA Ladder (Apr 2026)
1964
+
1965
+ > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/apr_2026.strategy)
1966
+
1967
+ Same mechanics as SHORT version but LONG-biased with 3% profit target. Deployed 2.4 entries per trade on average, achieved +67.85% PNL on deployed capital with improved percentage drawdown (-2.59% vs -3.99% without DCA).
1968
+
1969
+ #### ๐Ÿ Python EMA Crossover (Feb 2021)
1970
+
1971
+ > Link to [the source code](https://github.com/tripolskypetr/backtest-kit/tree/master/example/content/feb_2021.strategy)
1972
+
1973
+ Python-based (WASI) strategy that uses EMA(9) and EMA(21) crossover signals executed via WebAssembly. Trades trigger when fast EMA crosses slow EMA, confirmed by 4h range midpoint.
1974
+
1975
+ ## ๐Ÿ‘จโ€๐Ÿ’ผ Commercial Support
1976
+
1977
+ > **[TheOneTrade](https://theonetrade.github.io)** ๐Ÿ’ผ
1978
+
1979
+ **TheOneTrade** is the commercial vendor behind backtest-kit, providing paid support, custom strategy development, managed accounts, team training, and enterprise licensing. Contact for SLAs, private features, or quant team engagements that fall outside the MIT-licensed open-source scope.
1980
+
1981
+ ## ๐Ÿค– Are you a robot?
1982
+
1983
+ **For language models**: Read extended description in [./LLMs.md](./LLMs.md)
1984
+
1985
+ ## โœ… Tested & Reliable
1986
+
1987
+ 775+ tests cover validation, recovery, reports, and events.
1988
+
1989
+ ## ๐Ÿค Contribute
1990
+
1991
+ Fork/PR on [GitHub](https://github.com/tripolskypetr/backtest-kit).
1992
+
1993
+ ## ๐Ÿ“œ License
1994
+
1995
+ MIT ยฉ [tripolskypetr](https://github.com/tripolskypetr)
1996
+