backtest-kit 1.8.1 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/build/index.cjs +3985 -1305
- package/build/index.mjs +3981 -1307
- package/package.json +2 -2
- package/types.d.ts +1928 -514
package/types.d.ts
CHANGED
|
@@ -205,154 +205,100 @@ declare function partialProfit(symbol: string, percentToClose: number): Promise<
|
|
|
205
205
|
* ```
|
|
206
206
|
*/
|
|
207
207
|
declare function partialLoss(symbol: string, percentToClose: number): Promise<void>;
|
|
208
|
-
|
|
209
|
-
declare const GLOBAL_CONFIG: {
|
|
210
|
-
/**
|
|
211
|
-
* Time to wait for scheduled signal to activate (in minutes)
|
|
212
|
-
* If signal does not activate within this time, it will be cancelled.
|
|
213
|
-
*/
|
|
214
|
-
CC_SCHEDULE_AWAIT_MINUTES: number;
|
|
215
|
-
/**
|
|
216
|
-
* Number of candles to use for average price calculation (VWAP)
|
|
217
|
-
* Default: 5 candles (last 5 minutes when using 1m interval)
|
|
218
|
-
*/
|
|
219
|
-
CC_AVG_PRICE_CANDLES_COUNT: number;
|
|
220
|
-
/**
|
|
221
|
-
* Slippage percentage applied to entry and exit prices.
|
|
222
|
-
* Simulates market impact and order book depth.
|
|
223
|
-
* Applied twice (entry and exit) for realistic execution simulation.
|
|
224
|
-
* Default: 0.1% per transaction
|
|
225
|
-
*/
|
|
226
|
-
CC_PERCENT_SLIPPAGE: number;
|
|
227
|
-
/**
|
|
228
|
-
* Fee percentage charged per transaction.
|
|
229
|
-
* Applied twice (entry and exit) for total fee calculation.
|
|
230
|
-
* Default: 0.1% per transaction (total 0.2%)
|
|
231
|
-
*/
|
|
232
|
-
CC_PERCENT_FEE: number;
|
|
233
|
-
/**
|
|
234
|
-
* Minimum TakeProfit distance from priceOpen (percentage)
|
|
235
|
-
* Must be greater than (slippage + fees) to ensure profitable trades
|
|
236
|
-
*
|
|
237
|
-
* Calculation:
|
|
238
|
-
* - Slippage effect: ~0.2% (0.1% × 2 transactions)
|
|
239
|
-
* - Fees: 0.2% (0.1% × 2 transactions)
|
|
240
|
-
* - Minimum profit buffer: 0.1%
|
|
241
|
-
* - Total: 0.5%
|
|
242
|
-
*
|
|
243
|
-
* Default: 0.5% (covers all costs + minimum profit margin)
|
|
244
|
-
*/
|
|
245
|
-
CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
|
|
246
|
-
/**
|
|
247
|
-
* Minimum StopLoss distance from priceOpen (percentage)
|
|
248
|
-
* Prevents signals from being immediately stopped out due to price volatility
|
|
249
|
-
* Default: 0.5% (buffer to avoid instant stop loss on normal market fluctuations)
|
|
250
|
-
*/
|
|
251
|
-
CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
|
|
252
|
-
/**
|
|
253
|
-
* Maximum StopLoss distance from priceOpen (percentage)
|
|
254
|
-
* Prevents catastrophic losses from extreme StopLoss values
|
|
255
|
-
* Default: 20% (one signal cannot lose more than 20% of position)
|
|
256
|
-
*/
|
|
257
|
-
CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
|
|
258
|
-
/**
|
|
259
|
-
* Maximum signal lifetime in minutes
|
|
260
|
-
* Prevents eternal signals that block risk limits for weeks/months
|
|
261
|
-
* Default: 1440 minutes (1 day)
|
|
262
|
-
*/
|
|
263
|
-
CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
|
|
264
|
-
/**
|
|
265
|
-
* Maximum time allowed for signal generation (in seconds).
|
|
266
|
-
* Prevents long-running or stuck signal generation routines from blocking
|
|
267
|
-
* execution or consuming resources indefinitely. If generation exceeds this
|
|
268
|
-
* threshold the attempt should be aborted, logged and optionally retried.
|
|
269
|
-
*
|
|
270
|
-
* Default: 180 seconds (3 minutes)
|
|
271
|
-
*/
|
|
272
|
-
CC_MAX_SIGNAL_GENERATION_SECONDS: number;
|
|
273
|
-
/**
|
|
274
|
-
* Number of retries for getCandles function
|
|
275
|
-
* Default: 3 retries
|
|
276
|
-
*/
|
|
277
|
-
CC_GET_CANDLES_RETRY_COUNT: number;
|
|
278
|
-
/**
|
|
279
|
-
* Delay between retries for getCandles function (in milliseconds)
|
|
280
|
-
* Default: 5000 ms (5 seconds)
|
|
281
|
-
*/
|
|
282
|
-
CC_GET_CANDLES_RETRY_DELAY_MS: number;
|
|
283
|
-
/**
|
|
284
|
-
* Maximum allowed deviation factor for price anomaly detection.
|
|
285
|
-
* Price should not be more than this factor lower than reference price.
|
|
286
|
-
*
|
|
287
|
-
* Reasoning:
|
|
288
|
-
* - Incomplete candles from Binance API typically have prices near 0 (e.g., $0.01-1)
|
|
289
|
-
* - Normal BTC price ranges: $20,000-100,000
|
|
290
|
-
* - Factor 1000 catches prices below $20-100 when median is $20,000-100,000
|
|
291
|
-
* - Factor 100 would be too permissive (allows $200 when median is $20,000)
|
|
292
|
-
* - Factor 10000 might be too strict for low-cap altcoins
|
|
293
|
-
*
|
|
294
|
-
* Example: BTC at $50,000 median → threshold $50 (catches $0.01-1 anomalies)
|
|
295
|
-
*/
|
|
296
|
-
CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
|
|
297
|
-
/**
|
|
298
|
-
* Minimum number of candles required for reliable median calculation.
|
|
299
|
-
* Below this threshold, use simple average instead of median.
|
|
300
|
-
*
|
|
301
|
-
* Reasoning:
|
|
302
|
-
* - Each candle provides 4 price points (OHLC)
|
|
303
|
-
* - 5 candles = 20 price points, sufficient for robust median calculation
|
|
304
|
-
* - Below 5 candles, single anomaly can heavily skew median
|
|
305
|
-
* - Statistical rule of thumb: minimum 7-10 data points for median stability
|
|
306
|
-
* - Average is more stable than median for small datasets (n < 20)
|
|
307
|
-
*
|
|
308
|
-
* Example: 3 candles = 12 points (use average), 5 candles = 20 points (use median)
|
|
309
|
-
*/
|
|
310
|
-
CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
|
|
311
|
-
/**
|
|
312
|
-
* Controls visibility of signal notes in markdown report tables.
|
|
313
|
-
* When enabled, the "Note" column will be displayed in all markdown reports
|
|
314
|
-
* (backtest, live, schedule, risk, etc.)
|
|
315
|
-
*
|
|
316
|
-
* Default: false (notes are hidden to reduce table width and improve readability)
|
|
317
|
-
*/
|
|
318
|
-
CC_REPORT_SHOW_SIGNAL_NOTE: boolean;
|
|
319
|
-
};
|
|
320
208
|
/**
|
|
321
|
-
*
|
|
209
|
+
* Adjusts the trailing stop-loss distance for an active pending signal.
|
|
210
|
+
*
|
|
211
|
+
* Updates the stop-loss distance by a percentage adjustment relative to the original SL distance.
|
|
212
|
+
* Positive percentShift tightens the SL (reduces distance), negative percentShift loosens it.
|
|
213
|
+
*
|
|
214
|
+
* Automatically detects backtest/live mode from execution context.
|
|
215
|
+
*
|
|
216
|
+
* @param symbol - Trading pair symbol
|
|
217
|
+
* @param percentShift - Percentage adjustment to SL distance (-100 to 100)
|
|
218
|
+
* @returns Promise that resolves when trailing SL is updated
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* ```typescript
|
|
222
|
+
* import { trailingStop } from "backtest-kit";
|
|
223
|
+
*
|
|
224
|
+
* // LONG: entry=100, originalSL=90, distance=10
|
|
225
|
+
* // Tighten stop by 50%: newSL = 100 - 10*(1-0.5) = 95
|
|
226
|
+
* await trailingStop("BTCUSDT", -50);
|
|
227
|
+
* ```
|
|
322
228
|
*/
|
|
323
|
-
|
|
229
|
+
declare function trailingStop(symbol: string, percentShift: number): Promise<void>;
|
|
230
|
+
/**
|
|
231
|
+
* Moves stop-loss to breakeven when price reaches threshold.
|
|
232
|
+
*
|
|
233
|
+
* Moves SL to entry price (zero-risk position) when current price has moved
|
|
234
|
+
* far enough in profit direction to cover transaction costs.
|
|
235
|
+
* Threshold is calculated as: (CC_PERCENT_SLIPPAGE + CC_PERCENT_FEE) * 2
|
|
236
|
+
*
|
|
237
|
+
* Automatically detects backtest/live mode from execution context.
|
|
238
|
+
* Automatically fetches current price via getAveragePrice.
|
|
239
|
+
*
|
|
240
|
+
* @param symbol - Trading pair symbol
|
|
241
|
+
* @returns Promise<boolean> - true if breakeven was set, false if conditions not met
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* ```typescript
|
|
245
|
+
* import { breakeven } from "backtest-kit";
|
|
246
|
+
*
|
|
247
|
+
* // LONG: entry=100, slippage=0.1%, fee=0.1%, threshold=0.4%
|
|
248
|
+
* // Try to move SL to breakeven (activates when price >= 100.4)
|
|
249
|
+
* const moved = await breakeven("BTCUSDT");
|
|
250
|
+
* if (moved) {
|
|
251
|
+
* console.log("Position moved to breakeven!");
|
|
252
|
+
* }
|
|
253
|
+
* ```
|
|
254
|
+
*/
|
|
255
|
+
declare function breakeven(symbol: string): Promise<boolean>;
|
|
324
256
|
|
|
325
257
|
/**
|
|
326
|
-
*
|
|
258
|
+
* Execution context containing runtime parameters for strategy/exchange operations.
|
|
327
259
|
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
* (backtest, live, schedule, risk, heat, performance, partial, walker).
|
|
260
|
+
* Propagated through ExecutionContextService to provide implicit context
|
|
261
|
+
* for getCandles(), tick(), backtest() and other operations.
|
|
331
262
|
*/
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
|
|
335
|
-
/**
|
|
336
|
-
|
|
337
|
-
/**
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
partial_columns: ColumnModel<PartialEvent>[];
|
|
341
|
-
/** Columns for performance summary reports */
|
|
342
|
-
performance_columns: ColumnModel<MetricStats>[];
|
|
343
|
-
/** Columns for risk-related reports */
|
|
344
|
-
risk_columns: ColumnModel<RiskEvent>[];
|
|
345
|
-
/** Columns for scheduled report output */
|
|
346
|
-
schedule_columns: ColumnModel<ScheduledEvent>[];
|
|
347
|
-
/** Walker: PnL summary columns */
|
|
348
|
-
walker_pnl_columns: ColumnModel<SignalData$1>[];
|
|
349
|
-
/** Walker: strategy-level summary columns */
|
|
350
|
-
walker_strategy_columns: ColumnModel<IStrategyResult>[];
|
|
351
|
-
};
|
|
263
|
+
interface IExecutionContext {
|
|
264
|
+
/** Trading pair symbol (e.g., "BTCUSDT") */
|
|
265
|
+
symbol: string;
|
|
266
|
+
/** Current timestamp for operation */
|
|
267
|
+
when: Date;
|
|
268
|
+
/** Whether running in backtest mode (true) or live mode (false) */
|
|
269
|
+
backtest: boolean;
|
|
270
|
+
}
|
|
352
271
|
/**
|
|
353
|
-
*
|
|
272
|
+
* Scoped service for execution context propagation.
|
|
273
|
+
*
|
|
274
|
+
* Uses di-scoped for implicit context passing without explicit parameters.
|
|
275
|
+
* Context includes symbol, when (timestamp), and backtest flag.
|
|
276
|
+
*
|
|
277
|
+
* Used by GlobalServices to inject context into operations.
|
|
278
|
+
*
|
|
279
|
+
* @example
|
|
280
|
+
* ```typescript
|
|
281
|
+
* ExecutionContextService.runInContext(
|
|
282
|
+
* async () => {
|
|
283
|
+
* // Inside this callback, context is automatically available
|
|
284
|
+
* return await someOperation();
|
|
285
|
+
* },
|
|
286
|
+
* { symbol: "BTCUSDT", when: new Date(), backtest: true }
|
|
287
|
+
* );
|
|
288
|
+
* ```
|
|
354
289
|
*/
|
|
355
|
-
|
|
290
|
+
declare const ExecutionContextService: (new () => {
|
|
291
|
+
readonly context: IExecutionContext;
|
|
292
|
+
}) & Omit<{
|
|
293
|
+
new (context: IExecutionContext): {
|
|
294
|
+
readonly context: IExecutionContext;
|
|
295
|
+
};
|
|
296
|
+
}, "prototype"> & di_scoped.IScopedClassRun<[context: IExecutionContext]>;
|
|
297
|
+
/**
|
|
298
|
+
* Type helper for ExecutionContextService instance.
|
|
299
|
+
* Used for dependency injection type annotations.
|
|
300
|
+
*/
|
|
301
|
+
type TExecutionContextService = InstanceType<typeof ExecutionContextService>;
|
|
356
302
|
|
|
357
303
|
/**
|
|
358
304
|
* Interface representing a logging mechanism for the swarm system.
|
|
@@ -383,241 +329,27 @@ interface ILogger {
|
|
|
383
329
|
}
|
|
384
330
|
|
|
385
331
|
/**
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
* All log messages from internal services will be forwarded to the provided logger
|
|
389
|
-
* with automatic context injection (strategyName, exchangeName, symbol, etc.).
|
|
390
|
-
*
|
|
391
|
-
* @param logger - Custom logger implementing ILogger interface
|
|
392
|
-
*
|
|
393
|
-
* @example
|
|
394
|
-
* ```typescript
|
|
395
|
-
* setLogger({
|
|
396
|
-
* log: (topic, ...args) => console.log(topic, args),
|
|
397
|
-
* debug: (topic, ...args) => console.debug(topic, args),
|
|
398
|
-
* info: (topic, ...args) => console.info(topic, args),
|
|
399
|
-
* });
|
|
400
|
-
* ```
|
|
332
|
+
* Candle time interval for fetching historical data.
|
|
401
333
|
*/
|
|
402
|
-
|
|
334
|
+
type CandleInterval = "1m" | "3m" | "5m" | "15m" | "30m" | "1h" | "2h" | "4h" | "6h" | "8h";
|
|
403
335
|
/**
|
|
404
|
-
*
|
|
405
|
-
*
|
|
406
|
-
* @param _unsafe - Skip config validations - required for testbed
|
|
407
|
-
*
|
|
408
|
-
* @example
|
|
409
|
-
* ```typescript
|
|
410
|
-
* setConfig({
|
|
411
|
-
* CC_SCHEDULE_AWAIT_MINUTES: 90,
|
|
412
|
-
* });
|
|
413
|
-
* ```
|
|
336
|
+
* Single OHLCV candle data point.
|
|
337
|
+
* Used for VWAP calculation and backtesting.
|
|
414
338
|
*/
|
|
415
|
-
|
|
416
|
-
/**
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
*/
|
|
430
|
-
declare function getConfig(): {
|
|
431
|
-
CC_SCHEDULE_AWAIT_MINUTES: number;
|
|
432
|
-
CC_AVG_PRICE_CANDLES_COUNT: number;
|
|
433
|
-
CC_PERCENT_SLIPPAGE: number;
|
|
434
|
-
CC_PERCENT_FEE: number;
|
|
435
|
-
CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
|
|
436
|
-
CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
|
|
437
|
-
CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
|
|
438
|
-
CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
|
|
439
|
-
CC_MAX_SIGNAL_GENERATION_SECONDS: number;
|
|
440
|
-
CC_GET_CANDLES_RETRY_COUNT: number;
|
|
441
|
-
CC_GET_CANDLES_RETRY_DELAY_MS: number;
|
|
442
|
-
CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
|
|
443
|
-
CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
|
|
444
|
-
CC_REPORT_SHOW_SIGNAL_NOTE: boolean;
|
|
445
|
-
};
|
|
446
|
-
/**
|
|
447
|
-
* Retrieves the default configuration object for the framework.
|
|
448
|
-
*
|
|
449
|
-
* Returns a reference to the default configuration with all preset values.
|
|
450
|
-
* Use this to see what configuration options are available and their default values.
|
|
451
|
-
*
|
|
452
|
-
* @returns {GlobalConfig} The default configuration object
|
|
453
|
-
*
|
|
454
|
-
* @example
|
|
455
|
-
* ```typescript
|
|
456
|
-
* const defaultConfig = getDefaultConfig();
|
|
457
|
-
* console.log(defaultConfig.CC_SCHEDULE_AWAIT_MINUTES);
|
|
458
|
-
* ```
|
|
459
|
-
*/
|
|
460
|
-
declare function getDefaultConfig(): Readonly<{
|
|
461
|
-
CC_SCHEDULE_AWAIT_MINUTES: number;
|
|
462
|
-
CC_AVG_PRICE_CANDLES_COUNT: number;
|
|
463
|
-
CC_PERCENT_SLIPPAGE: number;
|
|
464
|
-
CC_PERCENT_FEE: number;
|
|
465
|
-
CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
|
|
466
|
-
CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
|
|
467
|
-
CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
|
|
468
|
-
CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
|
|
469
|
-
CC_MAX_SIGNAL_GENERATION_SECONDS: number;
|
|
470
|
-
CC_GET_CANDLES_RETRY_COUNT: number;
|
|
471
|
-
CC_GET_CANDLES_RETRY_DELAY_MS: number;
|
|
472
|
-
CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
|
|
473
|
-
CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
|
|
474
|
-
CC_REPORT_SHOW_SIGNAL_NOTE: boolean;
|
|
475
|
-
}>;
|
|
476
|
-
/**
|
|
477
|
-
* Sets custom column configurations for markdown report generation.
|
|
478
|
-
*
|
|
479
|
-
* Allows overriding default column definitions for any report type.
|
|
480
|
-
* All columns are validated before assignment to ensure structural correctness.
|
|
481
|
-
*
|
|
482
|
-
* @param columns - Partial column configuration object to override default column settings
|
|
483
|
-
* @param _unsafe - Skip column validations - required for testbed
|
|
484
|
-
*
|
|
485
|
-
* @example
|
|
486
|
-
* ```typescript
|
|
487
|
-
* setColumns({
|
|
488
|
-
* backtest_columns: [
|
|
489
|
-
* {
|
|
490
|
-
* key: "customId",
|
|
491
|
-
* label: "Custom ID",
|
|
492
|
-
* format: (data) => data.signal.id,
|
|
493
|
-
* isVisible: () => true
|
|
494
|
-
* }
|
|
495
|
-
* ],
|
|
496
|
-
* });
|
|
497
|
-
* ```
|
|
498
|
-
*
|
|
499
|
-
* @throws {Error} If column configuration is invalid
|
|
500
|
-
*/
|
|
501
|
-
declare function setColumns(columns: Partial<ColumnConfig>, _unsafe?: boolean): void;
|
|
502
|
-
/**
|
|
503
|
-
* Retrieves a copy of the current column configuration for markdown report generation.
|
|
504
|
-
*
|
|
505
|
-
* Returns a shallow copy of the current COLUMN_CONFIG to prevent accidental mutations.
|
|
506
|
-
* Use this to inspect the current column definitions without modifying them.
|
|
507
|
-
*
|
|
508
|
-
* @returns {ColumnConfig} A copy of the current column configuration object
|
|
509
|
-
*
|
|
510
|
-
* @example
|
|
511
|
-
* ```typescript
|
|
512
|
-
* const currentColumns = getColumns();
|
|
513
|
-
* console.log(currentColumns.backtest_columns.length);
|
|
514
|
-
* ```
|
|
515
|
-
*/
|
|
516
|
-
declare function getColumns(): {
|
|
517
|
-
backtest_columns: ColumnModel<IStrategyTickResultClosed>[];
|
|
518
|
-
heat_columns: ColumnModel<IHeatmapRow>[];
|
|
519
|
-
live_columns: ColumnModel<TickEvent>[];
|
|
520
|
-
partial_columns: ColumnModel<PartialEvent>[];
|
|
521
|
-
performance_columns: ColumnModel<MetricStats>[];
|
|
522
|
-
risk_columns: ColumnModel<RiskEvent>[];
|
|
523
|
-
schedule_columns: ColumnModel<ScheduledEvent>[];
|
|
524
|
-
walker_pnl_columns: ColumnModel<SignalData$1>[];
|
|
525
|
-
walker_strategy_columns: ColumnModel<IStrategyResult>[];
|
|
526
|
-
};
|
|
527
|
-
/**
|
|
528
|
-
* Retrieves the default column configuration object for markdown report generation.
|
|
529
|
-
*
|
|
530
|
-
* Returns a reference to the default column definitions with all preset values.
|
|
531
|
-
* Use this to see what column options are available and their default definitions.
|
|
532
|
-
*
|
|
533
|
-
* @returns {ColumnConfig} The default column configuration object
|
|
534
|
-
*
|
|
535
|
-
* @example
|
|
536
|
-
* ```typescript
|
|
537
|
-
* const defaultColumns = getDefaultColumns();
|
|
538
|
-
* console.log(defaultColumns.backtest_columns);
|
|
539
|
-
* ```
|
|
540
|
-
*/
|
|
541
|
-
declare function getDefaultColumns(): Readonly<{
|
|
542
|
-
backtest_columns: ColumnModel<IStrategyTickResultClosed>[];
|
|
543
|
-
heat_columns: ColumnModel<IHeatmapRow>[];
|
|
544
|
-
live_columns: ColumnModel<TickEvent>[];
|
|
545
|
-
partial_columns: ColumnModel<PartialEvent>[];
|
|
546
|
-
performance_columns: ColumnModel<MetricStats>[];
|
|
547
|
-
risk_columns: ColumnModel<RiskEvent>[];
|
|
548
|
-
schedule_columns: ColumnModel<ScheduledEvent>[];
|
|
549
|
-
walker_pnl_columns: ColumnModel<SignalData$1>[];
|
|
550
|
-
walker_strategy_columns: ColumnModel<IStrategyResult>[];
|
|
551
|
-
}>;
|
|
552
|
-
|
|
553
|
-
/**
|
|
554
|
-
* Execution context containing runtime parameters for strategy/exchange operations.
|
|
555
|
-
*
|
|
556
|
-
* Propagated through ExecutionContextService to provide implicit context
|
|
557
|
-
* for getCandles(), tick(), backtest() and other operations.
|
|
558
|
-
*/
|
|
559
|
-
interface IExecutionContext {
|
|
560
|
-
/** Trading pair symbol (e.g., "BTCUSDT") */
|
|
561
|
-
symbol: string;
|
|
562
|
-
/** Current timestamp for operation */
|
|
563
|
-
when: Date;
|
|
564
|
-
/** Whether running in backtest mode (true) or live mode (false) */
|
|
565
|
-
backtest: boolean;
|
|
566
|
-
}
|
|
567
|
-
/**
|
|
568
|
-
* Scoped service for execution context propagation.
|
|
569
|
-
*
|
|
570
|
-
* Uses di-scoped for implicit context passing without explicit parameters.
|
|
571
|
-
* Context includes symbol, when (timestamp), and backtest flag.
|
|
572
|
-
*
|
|
573
|
-
* Used by GlobalServices to inject context into operations.
|
|
574
|
-
*
|
|
575
|
-
* @example
|
|
576
|
-
* ```typescript
|
|
577
|
-
* ExecutionContextService.runInContext(
|
|
578
|
-
* async () => {
|
|
579
|
-
* // Inside this callback, context is automatically available
|
|
580
|
-
* return await someOperation();
|
|
581
|
-
* },
|
|
582
|
-
* { symbol: "BTCUSDT", when: new Date(), backtest: true }
|
|
583
|
-
* );
|
|
584
|
-
* ```
|
|
585
|
-
*/
|
|
586
|
-
declare const ExecutionContextService: (new () => {
|
|
587
|
-
readonly context: IExecutionContext;
|
|
588
|
-
}) & Omit<{
|
|
589
|
-
new (context: IExecutionContext): {
|
|
590
|
-
readonly context: IExecutionContext;
|
|
591
|
-
};
|
|
592
|
-
}, "prototype"> & di_scoped.IScopedClassRun<[context: IExecutionContext]>;
|
|
593
|
-
/**
|
|
594
|
-
* Type helper for ExecutionContextService instance.
|
|
595
|
-
* Used for dependency injection type annotations.
|
|
596
|
-
*/
|
|
597
|
-
type TExecutionContextService = InstanceType<typeof ExecutionContextService>;
|
|
598
|
-
|
|
599
|
-
/**
|
|
600
|
-
* Candle time interval for fetching historical data.
|
|
601
|
-
*/
|
|
602
|
-
type CandleInterval = "1m" | "3m" | "5m" | "15m" | "30m" | "1h" | "2h" | "4h" | "6h" | "8h";
|
|
603
|
-
/**
|
|
604
|
-
* Single OHLCV candle data point.
|
|
605
|
-
* Used for VWAP calculation and backtesting.
|
|
606
|
-
*/
|
|
607
|
-
interface ICandleData {
|
|
608
|
-
/** Unix timestamp in milliseconds when candle opened */
|
|
609
|
-
timestamp: number;
|
|
610
|
-
/** Opening price at candle start */
|
|
611
|
-
open: number;
|
|
612
|
-
/** Highest price during candle period */
|
|
613
|
-
high: number;
|
|
614
|
-
/** Lowest price during candle period */
|
|
615
|
-
low: number;
|
|
616
|
-
/** Closing price at candle end */
|
|
617
|
-
close: number;
|
|
618
|
-
/** Trading volume during candle period */
|
|
619
|
-
volume: number;
|
|
620
|
-
}
|
|
339
|
+
interface ICandleData {
|
|
340
|
+
/** Unix timestamp in milliseconds when candle opened */
|
|
341
|
+
timestamp: number;
|
|
342
|
+
/** Opening price at candle start */
|
|
343
|
+
open: number;
|
|
344
|
+
/** Highest price during candle period */
|
|
345
|
+
high: number;
|
|
346
|
+
/** Lowest price during candle period */
|
|
347
|
+
low: number;
|
|
348
|
+
/** Closing price at candle end */
|
|
349
|
+
close: number;
|
|
350
|
+
/** Trading volume during candle period */
|
|
351
|
+
volume: number;
|
|
352
|
+
}
|
|
621
353
|
/**
|
|
622
354
|
* Exchange parameters passed to ClientExchange constructor.
|
|
623
355
|
* Combines schema with runtime dependencies.
|
|
@@ -633,7 +365,7 @@ interface IExchangeParams extends IExchangeSchema {
|
|
|
633
365
|
*/
|
|
634
366
|
interface IExchangeCallbacks {
|
|
635
367
|
/** Called when candle data is fetched */
|
|
636
|
-
onCandleData: (symbol: string, interval: CandleInterval, since: Date, limit: number, data: ICandleData[]) => void
|
|
368
|
+
onCandleData: (symbol: string, interval: CandleInterval, since: Date, limit: number, data: ICandleData[]) => void | Promise<void>;
|
|
637
369
|
}
|
|
638
370
|
/**
|
|
639
371
|
* Exchange schema registered via addExchange().
|
|
@@ -758,7 +490,7 @@ interface IFrameCallbacks {
|
|
|
758
490
|
* @param endDate - End of the backtest period
|
|
759
491
|
* @param interval - Interval used for generation
|
|
760
492
|
*/
|
|
761
|
-
onTimeframe: (timeframe: Date[], startDate: Date, endDate: Date, interval: FrameInterval) => void
|
|
493
|
+
onTimeframe: (timeframe: Date[], startDate: Date, endDate: Date, interval: FrameInterval) => void | Promise<void>;
|
|
762
494
|
}
|
|
763
495
|
/**
|
|
764
496
|
* Frame schema registered via addFrame().
|
|
@@ -869,7 +601,7 @@ interface IRiskCheckArgs {
|
|
|
869
601
|
/** Trading pair symbol (e.g., "BTCUSDT") */
|
|
870
602
|
symbol: string;
|
|
871
603
|
/** Pending signal to apply */
|
|
872
|
-
pendingSignal: ISignalDto;
|
|
604
|
+
pendingSignal: ISignalDto | ISignalRow;
|
|
873
605
|
/** Strategy name requesting to open a position */
|
|
874
606
|
strategyName: StrategyName;
|
|
875
607
|
/** Exchange name */
|
|
@@ -897,17 +629,17 @@ interface IRiskActivePosition {
|
|
|
897
629
|
*/
|
|
898
630
|
interface IRiskCallbacks {
|
|
899
631
|
/** Called when a signal is rejected due to risk limits */
|
|
900
|
-
onRejected: (symbol: string, params: IRiskCheckArgs) => void
|
|
632
|
+
onRejected: (symbol: string, params: IRiskCheckArgs) => void | Promise<void>;
|
|
901
633
|
/** Called when a signal passes risk checks */
|
|
902
|
-
onAllowed: (symbol: string, params: IRiskCheckArgs) => void
|
|
634
|
+
onAllowed: (symbol: string, params: IRiskCheckArgs) => void | Promise<void>;
|
|
903
635
|
}
|
|
904
636
|
/**
|
|
905
637
|
* Payload passed to risk validation functions.
|
|
906
638
|
* Extends IRiskCheckArgs with portfolio state data.
|
|
907
639
|
*/
|
|
908
640
|
interface IRiskValidationPayload extends IRiskCheckArgs {
|
|
909
|
-
/** Pending signal to apply */
|
|
910
|
-
pendingSignal:
|
|
641
|
+
/** Pending signal to apply (IRiskSignalRow is calculated internally so priceOpen always exist) */
|
|
642
|
+
pendingSignal: IRiskSignalRow;
|
|
911
643
|
/** Number of currently active positions across all strategies */
|
|
912
644
|
activePositionCount: number;
|
|
913
645
|
/** List of currently active positions across all strategies */
|
|
@@ -965,6 +697,8 @@ interface IRiskSchema {
|
|
|
965
697
|
* Combines schema with runtime dependencies and emission callbacks.
|
|
966
698
|
*/
|
|
967
699
|
interface IRiskParams extends IRiskSchema {
|
|
700
|
+
/** Exchange name (e.g., "binance") */
|
|
701
|
+
exchangeName: ExchangeName;
|
|
968
702
|
/** Logger service for debug output */
|
|
969
703
|
logger: ILogger;
|
|
970
704
|
/** True if backtest mode, false if live mode */
|
|
@@ -1122,7 +856,7 @@ interface IPartial {
|
|
|
1122
856
|
* // Emits events for 20% level only (10% already emitted)
|
|
1123
857
|
* ```
|
|
1124
858
|
*/
|
|
1125
|
-
profit(symbol: string, data:
|
|
859
|
+
profit(symbol: string, data: IPublicSignalRow, currentPrice: number, revenuePercent: number, backtest: boolean, when: Date): Promise<void>;
|
|
1126
860
|
/**
|
|
1127
861
|
* Processes loss state and emits events for new loss levels reached.
|
|
1128
862
|
*
|
|
@@ -1156,7 +890,7 @@ interface IPartial {
|
|
|
1156
890
|
* // Emits events for 20% level only (10% already emitted)
|
|
1157
891
|
* ```
|
|
1158
892
|
*/
|
|
1159
|
-
loss(symbol: string, data:
|
|
893
|
+
loss(symbol: string, data: IPublicSignalRow, currentPrice: number, lossPercent: number, backtest: boolean, when: Date): Promise<void>;
|
|
1160
894
|
/**
|
|
1161
895
|
* Clears partial profit/loss state when signal closes.
|
|
1162
896
|
*
|
|
@@ -1178,52 +912,158 @@ interface IPartial {
|
|
|
1178
912
|
* // Memoized instance cleared from getPartial cache
|
|
1179
913
|
* ```
|
|
1180
914
|
*/
|
|
1181
|
-
clear(symbol: string, data:
|
|
915
|
+
clear(symbol: string, data: IPublicSignalRow, priceClose: number, backtest: boolean): Promise<void>;
|
|
1182
916
|
}
|
|
1183
917
|
|
|
1184
918
|
/**
|
|
1185
|
-
*
|
|
1186
|
-
*
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
* Signal data transfer object returned by getSignal.
|
|
1191
|
-
* Will be validated and augmented with auto-generated id.
|
|
919
|
+
* Serializable breakeven data for persistence layer.
|
|
920
|
+
* Converts state to simple boolean for JSON serialization.
|
|
921
|
+
*
|
|
922
|
+
* Stored in PersistBreakevenAdapter as Record<signalId, IBreakevenData>.
|
|
923
|
+
* Loaded on initialization and converted back to IBreakevenState.
|
|
1192
924
|
*/
|
|
1193
|
-
interface
|
|
1194
|
-
/**
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
note?: string;
|
|
1200
|
-
/** Entry price for the position */
|
|
1201
|
-
priceOpen?: number;
|
|
1202
|
-
/** Take profit target price (must be > priceOpen for long, < priceOpen for short) */
|
|
1203
|
-
priceTakeProfit: number;
|
|
1204
|
-
/** Stop loss exit price (must be < priceOpen for long, > priceOpen for short) */
|
|
1205
|
-
priceStopLoss: number;
|
|
1206
|
-
/** Expected duration in minutes before time_expired */
|
|
1207
|
-
minuteEstimatedTime: number;
|
|
925
|
+
interface IBreakevenData {
|
|
926
|
+
/**
|
|
927
|
+
* Whether breakeven has been reached for this signal.
|
|
928
|
+
* Serialized form of IBreakevenState.reached.
|
|
929
|
+
*/
|
|
930
|
+
reached: boolean;
|
|
1208
931
|
}
|
|
1209
932
|
/**
|
|
1210
|
-
*
|
|
1211
|
-
*
|
|
933
|
+
* Breakeven tracking interface.
|
|
934
|
+
* Implemented by ClientBreakeven and BreakevenConnectionService.
|
|
935
|
+
*
|
|
936
|
+
* Tracks when a signal's stop-loss is moved to breakeven (entry price).
|
|
937
|
+
* Emits events when threshold is reached (price moves far enough to cover transaction costs).
|
|
938
|
+
*
|
|
939
|
+
* @example
|
|
940
|
+
* ```typescript
|
|
941
|
+
* import { ClientBreakeven } from "./client/ClientBreakeven";
|
|
942
|
+
*
|
|
943
|
+
* const breakeven = new ClientBreakeven({
|
|
944
|
+
* logger: loggerService,
|
|
945
|
+
* onBreakeven: (symbol, data, price, backtest, timestamp) => {
|
|
946
|
+
* console.log(`Signal ${data.id} reached breakeven at ${price}`);
|
|
947
|
+
* }
|
|
948
|
+
* });
|
|
949
|
+
*
|
|
950
|
+
* await breakeven.waitForInit("BTCUSDT");
|
|
951
|
+
*
|
|
952
|
+
* // During signal monitoring
|
|
953
|
+
* await breakeven.check("BTCUSDT", signal, 100.5, false, new Date());
|
|
954
|
+
* // Emits event when threshold reached and SL moved to entry
|
|
955
|
+
*
|
|
956
|
+
* // When signal closes
|
|
957
|
+
* await breakeven.clear("BTCUSDT", signal, 101, false);
|
|
958
|
+
* ```
|
|
1212
959
|
*/
|
|
1213
|
-
interface
|
|
1214
|
-
/**
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
960
|
+
interface IBreakeven {
|
|
961
|
+
/**
|
|
962
|
+
* Checks if breakeven should be triggered and emits event if conditions met.
|
|
963
|
+
*
|
|
964
|
+
* Called by ClientStrategy during signal monitoring.
|
|
965
|
+
* Checks if:
|
|
966
|
+
* 1. Breakeven not already reached
|
|
967
|
+
* 2. Price has moved far enough to cover transaction costs
|
|
968
|
+
* 3. Stop-loss can be moved to entry price
|
|
969
|
+
*
|
|
970
|
+
* If all conditions met:
|
|
971
|
+
* - Marks breakeven as reached
|
|
972
|
+
* - Calls onBreakeven callback (emits to breakevenSubject)
|
|
973
|
+
* - Persists state to disk
|
|
974
|
+
*
|
|
975
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
976
|
+
* @param data - Signal row data
|
|
977
|
+
* @param currentPrice - Current market price
|
|
978
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
979
|
+
* @param when - Event timestamp (current time for live, candle time for backtest)
|
|
980
|
+
* @returns Promise that resolves when breakeven check is complete
|
|
981
|
+
*
|
|
982
|
+
* @example
|
|
983
|
+
* ```typescript
|
|
984
|
+
* // LONG: entry=100, slippage=0.1%, fee=0.1%, threshold=0.4%
|
|
985
|
+
* // Price at 100.3 - threshold not reached
|
|
986
|
+
* await breakeven.check("BTCUSDT", signal, 100.3, false, new Date());
|
|
987
|
+
* // No event emitted (price < 100.4)
|
|
988
|
+
*
|
|
989
|
+
* // Price at 100.5 - threshold reached!
|
|
990
|
+
* await breakeven.check("BTCUSDT", signal, 100.5, false, new Date());
|
|
991
|
+
* // Emits breakevenSubject event
|
|
992
|
+
*
|
|
993
|
+
* // Price at 101 - already at breakeven
|
|
994
|
+
* await breakeven.check("BTCUSDT", signal, 101, false, new Date());
|
|
995
|
+
* // No event emitted (already reached)
|
|
996
|
+
* ```
|
|
997
|
+
*/
|
|
998
|
+
check(symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean, when: Date): Promise<boolean>;
|
|
999
|
+
/**
|
|
1000
|
+
* Clears breakeven state when signal closes.
|
|
1001
|
+
*
|
|
1002
|
+
* Called by ClientStrategy when signal completes (TP/SL/time_expired).
|
|
1003
|
+
* Removes signal state from memory and persists changes to disk.
|
|
1004
|
+
* Cleans up memoized ClientBreakeven instance in BreakevenConnectionService.
|
|
1005
|
+
*
|
|
1006
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
1007
|
+
* @param data - Signal row data
|
|
1008
|
+
* @param priceClose - Final closing price
|
|
1009
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
1010
|
+
* @returns Promise that resolves when clear is complete
|
|
1011
|
+
*
|
|
1012
|
+
* @example
|
|
1013
|
+
* ```typescript
|
|
1014
|
+
* // Signal closes at take profit
|
|
1015
|
+
* await breakeven.clear("BTCUSDT", signal, 101);
|
|
1016
|
+
* // State removed from _states Map
|
|
1017
|
+
* // Persisted to disk without this signal's data
|
|
1018
|
+
* // Memoized instance cleared from getBreakeven cache
|
|
1019
|
+
* ```
|
|
1020
|
+
*/
|
|
1021
|
+
clear(symbol: string, data: IPublicSignalRow, priceClose: number, backtest: boolean): Promise<void>;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/**
|
|
1025
|
+
* Signal generation interval for throttling.
|
|
1026
|
+
* Enforces minimum time between getSignal calls.
|
|
1027
|
+
*/
|
|
1028
|
+
type SignalInterval = "1m" | "3m" | "5m" | "15m" | "30m" | "1h";
|
|
1029
|
+
/**
|
|
1030
|
+
* Signal data transfer object returned by getSignal.
|
|
1031
|
+
* Will be validated and augmented with auto-generated id.
|
|
1032
|
+
*/
|
|
1033
|
+
interface ISignalDto {
|
|
1034
|
+
/** Optional signal ID (auto-generated if not provided) */
|
|
1035
|
+
id?: string;
|
|
1036
|
+
/** Trade direction: "long" (buy) or "short" (sell) */
|
|
1037
|
+
position: "long" | "short";
|
|
1038
|
+
/** Human-readable description of signal reason */
|
|
1039
|
+
note?: string;
|
|
1040
|
+
/** Entry price for the position */
|
|
1041
|
+
priceOpen?: number;
|
|
1042
|
+
/** Take profit target price (must be > priceOpen for long, < priceOpen for short) */
|
|
1043
|
+
priceTakeProfit: number;
|
|
1044
|
+
/** Stop loss exit price (must be < priceOpen for long, > priceOpen for short) */
|
|
1045
|
+
priceStopLoss: number;
|
|
1046
|
+
/** Expected duration in minutes before time_expired */
|
|
1047
|
+
minuteEstimatedTime: number;
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Complete signal with auto-generated id.
|
|
1051
|
+
* Used throughout the system after validation.
|
|
1052
|
+
*/
|
|
1053
|
+
interface ISignalRow extends ISignalDto {
|
|
1054
|
+
/** Unique signal identifier (UUID v4 auto-generated) */
|
|
1055
|
+
id: string;
|
|
1056
|
+
/** Entry price for the position */
|
|
1057
|
+
priceOpen: number;
|
|
1058
|
+
/** Unique exchange identifier for execution */
|
|
1059
|
+
exchangeName: ExchangeName;
|
|
1060
|
+
/** Unique strategy identifier for execution */
|
|
1061
|
+
strategyName: StrategyName;
|
|
1062
|
+
/** Unique frame identifier for execution (empty string for live mode) */
|
|
1063
|
+
frameName: FrameName;
|
|
1064
|
+
/** Signal creation timestamp in milliseconds (when signal was first created/scheduled) */
|
|
1065
|
+
scheduledAt: number;
|
|
1066
|
+
/** Pending timestamp in milliseconds (when position became pending/active at priceOpen) */
|
|
1227
1067
|
pendingAt: number;
|
|
1228
1068
|
/** Trading pair symbol (e.g., "BTCUSDT") */
|
|
1229
1069
|
symbol: string;
|
|
@@ -1247,6 +1087,15 @@ interface ISignalRow extends ISignalDto {
|
|
|
1247
1087
|
/** Price at which this partial was executed */
|
|
1248
1088
|
price: number;
|
|
1249
1089
|
}>;
|
|
1090
|
+
/**
|
|
1091
|
+
* Trailing stop-loss price that overrides priceStopLoss when set.
|
|
1092
|
+
* Updated by trailing() method based on position type and percentage distance.
|
|
1093
|
+
* - For LONG: moves upward as price moves toward TP (never moves down)
|
|
1094
|
+
* - For SHORT: moves downward as price moves toward TP (never moves up)
|
|
1095
|
+
* When _trailingPriceStopLoss is set, it replaces priceStopLoss for TP/SL checks.
|
|
1096
|
+
* Original priceStopLoss is preserved in persistence but ignored during execution.
|
|
1097
|
+
*/
|
|
1098
|
+
_trailingPriceStopLoss?: number;
|
|
1250
1099
|
}
|
|
1251
1100
|
/**
|
|
1252
1101
|
* Scheduled signal row for delayed entry at specific price.
|
|
@@ -1258,6 +1107,38 @@ interface IScheduledSignalRow extends ISignalRow {
|
|
|
1258
1107
|
/** Entry price for the position */
|
|
1259
1108
|
priceOpen: number;
|
|
1260
1109
|
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Public signal row with original stop-loss price.
|
|
1112
|
+
* Extends ISignalRow to include originalPriceStopLoss for external visibility.
|
|
1113
|
+
* Used in public APIs to show user the original SL even if trailing SL is active.
|
|
1114
|
+
* This allows users to see both the current effective SL and the original SL set at signal creation.
|
|
1115
|
+
* The originalPriceStopLoss remains unchanged even if _trailingPriceStopLoss modifies the effective SL.
|
|
1116
|
+
* Useful for transparency in reporting and user interfaces.
|
|
1117
|
+
* Note: originalPriceStopLoss is identical to priceStopLoss at signal creation time.
|
|
1118
|
+
*/
|
|
1119
|
+
interface IPublicSignalRow extends ISignalRow {
|
|
1120
|
+
/**
|
|
1121
|
+
* Original stop-loss price set at signal creation.
|
|
1122
|
+
* Remains unchanged even if trailing stop-loss modifies effective SL.
|
|
1123
|
+
* Used for user visibility of initial SL parameters.
|
|
1124
|
+
*/
|
|
1125
|
+
originalPriceStopLoss: number;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Risk signal row for internal risk management.
|
|
1129
|
+
* Extends ISignalDto to include priceOpen and originalPriceStopLoss.
|
|
1130
|
+
* Used in risk validation to access entry price and original SL.
|
|
1131
|
+
*/
|
|
1132
|
+
interface IRiskSignalRow extends ISignalDto {
|
|
1133
|
+
/**
|
|
1134
|
+
* Entry price for the position.
|
|
1135
|
+
*/
|
|
1136
|
+
priceOpen: number;
|
|
1137
|
+
/**
|
|
1138
|
+
* Original stop-loss price set at signal creation.
|
|
1139
|
+
*/
|
|
1140
|
+
originalPriceStopLoss: number;
|
|
1141
|
+
}
|
|
1261
1142
|
/**
|
|
1262
1143
|
* Scheduled signal row with cancellation ID.
|
|
1263
1144
|
* Extends IScheduledSignalRow to include optional cancelId for user-initiated cancellations.
|
|
@@ -1272,27 +1153,29 @@ interface IScheduledSignalCancelRow extends IScheduledSignalRow {
|
|
|
1272
1153
|
*/
|
|
1273
1154
|
interface IStrategyCallbacks {
|
|
1274
1155
|
/** Called on every tick with the result */
|
|
1275
|
-
onTick: (symbol: string, result: IStrategyTickResult, backtest: boolean) => void
|
|
1156
|
+
onTick: (symbol: string, result: IStrategyTickResult, backtest: boolean) => void | Promise<void>;
|
|
1276
1157
|
/** Called when new signal is opened (after validation) */
|
|
1277
|
-
onOpen: (symbol: string, data:
|
|
1158
|
+
onOpen: (symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean) => void | Promise<void>;
|
|
1278
1159
|
/** Called when signal is being monitored (active state) */
|
|
1279
|
-
onActive: (symbol: string, data:
|
|
1160
|
+
onActive: (symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean) => void | Promise<void>;
|
|
1280
1161
|
/** Called when no active signal exists (idle state) */
|
|
1281
|
-
onIdle: (symbol: string, currentPrice: number, backtest: boolean) => void
|
|
1162
|
+
onIdle: (symbol: string, currentPrice: number, backtest: boolean) => void | Promise<void>;
|
|
1282
1163
|
/** Called when signal is closed with final price */
|
|
1283
|
-
onClose: (symbol: string, data:
|
|
1164
|
+
onClose: (symbol: string, data: IPublicSignalRow, priceClose: number, backtest: boolean) => void | Promise<void>;
|
|
1284
1165
|
/** Called when scheduled signal is created (delayed entry) */
|
|
1285
|
-
onSchedule: (symbol: string, data:
|
|
1166
|
+
onSchedule: (symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean) => void | Promise<void>;
|
|
1286
1167
|
/** Called when scheduled signal is cancelled without opening position */
|
|
1287
|
-
onCancel: (symbol: string, data:
|
|
1168
|
+
onCancel: (symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean) => void | Promise<void>;
|
|
1288
1169
|
/** Called when signal is written to persist storage (for testing) */
|
|
1289
|
-
onWrite: (symbol: string, data:
|
|
1170
|
+
onWrite: (symbol: string, data: IPublicSignalRow | null, backtest: boolean) => void;
|
|
1290
1171
|
/** Called when signal is in partial profit state (price moved favorably but not reached TP yet) */
|
|
1291
|
-
onPartialProfit: (symbol: string, data:
|
|
1172
|
+
onPartialProfit: (symbol: string, data: IPublicSignalRow, currentPrice: number, revenuePercent: number, backtest: boolean) => void | Promise<void>;
|
|
1292
1173
|
/** Called when signal is in partial loss state (price moved against position but not hit SL yet) */
|
|
1293
|
-
onPartialLoss: (symbol: string, data:
|
|
1174
|
+
onPartialLoss: (symbol: string, data: IPublicSignalRow, currentPrice: number, lossPercent: number, backtest: boolean) => void | Promise<void>;
|
|
1175
|
+
/** Called when signal reaches breakeven (stop-loss moved to entry price to protect capital) */
|
|
1176
|
+
onBreakeven: (symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean) => void | Promise<void>;
|
|
1294
1177
|
/** Called every minute regardless of strategy interval (for custom monitoring like checking if signal should be cancelled) */
|
|
1295
|
-
onPing: (symbol: string, data:
|
|
1178
|
+
onPing: (symbol: string, data: IPublicSignalRow, when: Date, backtest: boolean) => void | Promise<void>;
|
|
1296
1179
|
}
|
|
1297
1180
|
/**
|
|
1298
1181
|
* Strategy schema registered via addStrategy().
|
|
@@ -1369,7 +1252,7 @@ interface IStrategyTickResultScheduled {
|
|
|
1369
1252
|
/** Discriminator for type-safe union */
|
|
1370
1253
|
action: "scheduled";
|
|
1371
1254
|
/** Scheduled signal waiting for activation */
|
|
1372
|
-
signal:
|
|
1255
|
+
signal: IPublicSignalRow;
|
|
1373
1256
|
/** Strategy name for tracking */
|
|
1374
1257
|
strategyName: StrategyName;
|
|
1375
1258
|
/** Exchange name for tracking */
|
|
@@ -1391,7 +1274,7 @@ interface IStrategyTickResultOpened {
|
|
|
1391
1274
|
/** Discriminator for type-safe union */
|
|
1392
1275
|
action: "opened";
|
|
1393
1276
|
/** Newly created and validated signal with generated ID */
|
|
1394
|
-
signal:
|
|
1277
|
+
signal: IPublicSignalRow;
|
|
1395
1278
|
/** Strategy name for tracking */
|
|
1396
1279
|
strategyName: StrategyName;
|
|
1397
1280
|
/** Exchange name for tracking */
|
|
@@ -1413,7 +1296,7 @@ interface IStrategyTickResultActive {
|
|
|
1413
1296
|
/** Discriminator for type-safe union */
|
|
1414
1297
|
action: "active";
|
|
1415
1298
|
/** Currently monitored signal */
|
|
1416
|
-
signal:
|
|
1299
|
+
signal: IPublicSignalRow;
|
|
1417
1300
|
/** Current VWAP price for monitoring */
|
|
1418
1301
|
currentPrice: number;
|
|
1419
1302
|
/** Strategy name for tracking */
|
|
@@ -1439,7 +1322,7 @@ interface IStrategyTickResultClosed {
|
|
|
1439
1322
|
/** Discriminator for type-safe union */
|
|
1440
1323
|
action: "closed";
|
|
1441
1324
|
/** Completed signal with original parameters */
|
|
1442
|
-
signal:
|
|
1325
|
+
signal: IPublicSignalRow;
|
|
1443
1326
|
/** Final VWAP price at close */
|
|
1444
1327
|
currentPrice: number;
|
|
1445
1328
|
/** Why signal closed (time_expired | take_profit | stop_loss) */
|
|
@@ -1467,7 +1350,7 @@ interface IStrategyTickResultCancelled {
|
|
|
1467
1350
|
/** Discriminator for type-safe union */
|
|
1468
1351
|
action: "cancelled";
|
|
1469
1352
|
/** Cancelled scheduled signal */
|
|
1470
|
-
signal:
|
|
1353
|
+
signal: IPublicSignalRow;
|
|
1471
1354
|
/** Final VWAP price at cancellation */
|
|
1472
1355
|
currentPrice: number;
|
|
1473
1356
|
/** Unix timestamp in milliseconds when signal cancelled */
|
|
@@ -1518,7 +1401,7 @@ interface IStrategy {
|
|
|
1518
1401
|
* @param symbol - Trading pair symbol
|
|
1519
1402
|
* @returns Promise resolving to pending signal or null
|
|
1520
1403
|
*/
|
|
1521
|
-
getPendingSignal: (symbol: string) => Promise<
|
|
1404
|
+
getPendingSignal: (symbol: string) => Promise<IPublicSignalRow | null>;
|
|
1522
1405
|
/**
|
|
1523
1406
|
* Retrieves the currently active scheduled signal for the symbol.
|
|
1524
1407
|
* If no scheduled signal exists, returns null.
|
|
@@ -1527,7 +1410,7 @@ interface IStrategy {
|
|
|
1527
1410
|
* @param symbol - Trading pair symbol
|
|
1528
1411
|
* @returns Promise resolving to scheduled signal or null
|
|
1529
1412
|
*/
|
|
1530
|
-
getScheduledSignal: (symbol: string) => Promise<
|
|
1413
|
+
getScheduledSignal: (symbol: string) => Promise<IPublicSignalRow | null>;
|
|
1531
1414
|
/**
|
|
1532
1415
|
* Checks if the strategy has been stopped.
|
|
1533
1416
|
*
|
|
@@ -1659,12 +1542,489 @@ interface IStrategy {
|
|
|
1659
1542
|
* ```
|
|
1660
1543
|
*/
|
|
1661
1544
|
partialLoss: (symbol: string, percentToClose: number, currentPrice: number, backtest: boolean) => Promise<void>;
|
|
1545
|
+
/**
|
|
1546
|
+
* Adjusts trailing stop-loss by shifting distance between entry and original SL.
|
|
1547
|
+
*
|
|
1548
|
+
* Calculates new SL based on percentage shift of the distance (entry - originalSL):
|
|
1549
|
+
* - Negative %: tightens stop (moves SL closer to entry, reduces risk)
|
|
1550
|
+
* - Positive %: loosens stop (moves SL away from entry, allows more drawdown)
|
|
1551
|
+
*
|
|
1552
|
+
* For LONG position (entry=100, originalSL=90, distance=10):
|
|
1553
|
+
* - percentShift = -50: newSL = 100 - 10*(1-0.5) = 95 (tighter, closer to entry)
|
|
1554
|
+
* - percentShift = +20: newSL = 100 - 10*(1+0.2) = 88 (looser, away from entry)
|
|
1555
|
+
*
|
|
1556
|
+
* For SHORT position (entry=100, originalSL=110, distance=10):
|
|
1557
|
+
* - percentShift = -50: newSL = 100 + 10*(1-0.5) = 105 (tighter, closer to entry)
|
|
1558
|
+
* - percentShift = +20: newSL = 100 + 10*(1+0.2) = 112 (looser, away from entry)
|
|
1559
|
+
*
|
|
1560
|
+
* Trailing behavior:
|
|
1561
|
+
* - Only updates if new SL is BETTER (protects more profit)
|
|
1562
|
+
* - For LONG: only accepts higher SL (never moves down)
|
|
1563
|
+
* - For SHORT: only accepts lower SL (never moves up)
|
|
1564
|
+
* - Validates that SL never crosses entry price
|
|
1565
|
+
* - Stores in _trailingPriceStopLoss, original priceStopLoss preserved
|
|
1566
|
+
*
|
|
1567
|
+
* Validations:
|
|
1568
|
+
* - Throws if no pending signal exists
|
|
1569
|
+
* - Throws if percentShift< -100 or > 100
|
|
1570
|
+
* - Throws if percentShift=== 0
|
|
1571
|
+
* - Skips if new SL would cross entry price
|
|
1572
|
+
*
|
|
1573
|
+
* Use case: User-controlled trailing stop triggered from onPartialProfit callback.
|
|
1574
|
+
*
|
|
1575
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
1576
|
+
* @param percentShift- Percentage shift of SL distance [-100, 100], excluding 0
|
|
1577
|
+
* @param backtest - Whether running in backtest mode
|
|
1578
|
+
* @returns Promise that resolves when trailing SL is updated
|
|
1579
|
+
*
|
|
1580
|
+
* @example
|
|
1581
|
+
* ```typescript
|
|
1582
|
+
* callbacks: {
|
|
1583
|
+
* onPartialProfit: async (symbol, signal, currentPrice, percentTp, backtest) => {
|
|
1584
|
+
* if (percentTp >= 50) {
|
|
1585
|
+
* // LONG: entry=100, originalSL=90, distance=10
|
|
1586
|
+
* // Tighten stop by 50%: newSL = 100 - 10*(1-0.5) = 95
|
|
1587
|
+
* await strategy.trailingStop(symbol, -50, backtest);
|
|
1588
|
+
* }
|
|
1589
|
+
* }
|
|
1590
|
+
* }
|
|
1591
|
+
* ```
|
|
1592
|
+
*/
|
|
1593
|
+
trailingStop: (symbol: string, percentShift: number, backtest: boolean) => Promise<void>;
|
|
1594
|
+
/**
|
|
1595
|
+
* Moves stop-loss to breakeven (entry price) when price reaches threshold.
|
|
1596
|
+
*
|
|
1597
|
+
* Moves SL to entry price (zero-risk position) when current price has moved
|
|
1598
|
+
* far enough in profit direction to cover transaction costs (slippage + fees).
|
|
1599
|
+
* Threshold is calculated as: (CC_PERCENT_SLIPPAGE + CC_PERCENT_FEE) * 2
|
|
1600
|
+
*
|
|
1601
|
+
* Behavior:
|
|
1602
|
+
* - Returns true if SL was moved to breakeven
|
|
1603
|
+
* - Returns false if conditions not met (threshold not reached or already at breakeven)
|
|
1604
|
+
* - Uses _trailingPriceStopLoss to store breakeven SL (preserves original priceStopLoss)
|
|
1605
|
+
* - Only moves SL once per position (idempotent - safe to call multiple times)
|
|
1606
|
+
*
|
|
1607
|
+
* For LONG position (entry=100, slippage=0.1%, fee=0.1%):
|
|
1608
|
+
* - Threshold: (0.1 + 0.1) * 2 = 0.4%
|
|
1609
|
+
* - Breakeven available when price >= 100.4 (entry + 0.4%)
|
|
1610
|
+
* - Moves SL from original (e.g. 95) to 100 (breakeven)
|
|
1611
|
+
* - Returns true on first successful move, false on subsequent calls
|
|
1612
|
+
*
|
|
1613
|
+
* For SHORT position (entry=100, slippage=0.1%, fee=0.1%):
|
|
1614
|
+
* - Threshold: (0.1 + 0.1) * 2 = 0.4%
|
|
1615
|
+
* - Breakeven available when price <= 99.6 (entry - 0.4%)
|
|
1616
|
+
* - Moves SL from original (e.g. 105) to 100 (breakeven)
|
|
1617
|
+
* - Returns true on first successful move, false on subsequent calls
|
|
1618
|
+
*
|
|
1619
|
+
* Validations:
|
|
1620
|
+
* - Throws if no pending signal exists
|
|
1621
|
+
* - Throws if currentPrice is not a positive finite number
|
|
1622
|
+
*
|
|
1623
|
+
* Use case: User-controlled breakeven protection triggered from onPartialProfit callback.
|
|
1624
|
+
*
|
|
1625
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
1626
|
+
* @param currentPrice - Current market price to check threshold
|
|
1627
|
+
* @param backtest - Whether running in backtest mode
|
|
1628
|
+
* @returns Promise<boolean> - true if breakeven was set, false if conditions not met
|
|
1629
|
+
*
|
|
1630
|
+
* @example
|
|
1631
|
+
* ```typescript
|
|
1632
|
+
* callbacks: {
|
|
1633
|
+
* onPartialProfit: async (symbol, signal, currentPrice, percentTp, backtest) => {
|
|
1634
|
+
* // Try to move SL to breakeven when threshold reached
|
|
1635
|
+
* const movedToBreakeven = await strategy.breakeven(symbol, currentPrice, backtest);
|
|
1636
|
+
* if (movedToBreakeven) {
|
|
1637
|
+
* console.log(`Position moved to breakeven at ${currentPrice}`);
|
|
1638
|
+
* }
|
|
1639
|
+
* }
|
|
1640
|
+
* }
|
|
1641
|
+
* ```
|
|
1642
|
+
*/
|
|
1643
|
+
breakeven: (symbol: string, currentPrice: number, backtest: boolean) => Promise<boolean>;
|
|
1662
1644
|
}
|
|
1663
1645
|
/**
|
|
1664
1646
|
* Unique strategy identifier.
|
|
1665
1647
|
*/
|
|
1666
1648
|
type StrategyName = string;
|
|
1667
1649
|
|
|
1650
|
+
/**
|
|
1651
|
+
* Unified breakeven event data for report generation.
|
|
1652
|
+
* Contains all information about when signals reached breakeven.
|
|
1653
|
+
*/
|
|
1654
|
+
interface BreakevenEvent {
|
|
1655
|
+
/** Event timestamp in milliseconds */
|
|
1656
|
+
timestamp: number;
|
|
1657
|
+
/** Trading pair symbol */
|
|
1658
|
+
symbol: string;
|
|
1659
|
+
/** Strategy name */
|
|
1660
|
+
strategyName: StrategyName;
|
|
1661
|
+
/** Signal ID */
|
|
1662
|
+
signalId: string;
|
|
1663
|
+
/** Position type */
|
|
1664
|
+
position: string;
|
|
1665
|
+
/** Current market price when breakeven was reached */
|
|
1666
|
+
currentPrice: number;
|
|
1667
|
+
/** Entry price (breakeven level) */
|
|
1668
|
+
priceOpen: number;
|
|
1669
|
+
/** True if backtest mode, false if live mode */
|
|
1670
|
+
backtest: boolean;
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* Statistical data calculated from breakeven events.
|
|
1674
|
+
*
|
|
1675
|
+
* Provides metrics for breakeven milestone tracking.
|
|
1676
|
+
*
|
|
1677
|
+
* @example
|
|
1678
|
+
* ```typescript
|
|
1679
|
+
* const stats = await Breakeven.getData("BTCUSDT", "my-strategy");
|
|
1680
|
+
*
|
|
1681
|
+
* console.log(`Total breakeven events: ${stats.totalEvents}`);
|
|
1682
|
+
* console.log(`Average threshold: ${stats.averageThreshold}%`);
|
|
1683
|
+
* ```
|
|
1684
|
+
*/
|
|
1685
|
+
interface BreakevenStatisticsModel {
|
|
1686
|
+
/** Array of all breakeven events with full details */
|
|
1687
|
+
eventList: BreakevenEvent[];
|
|
1688
|
+
/** Total number of breakeven events */
|
|
1689
|
+
totalEvents: number;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
declare const GLOBAL_CONFIG: {
|
|
1693
|
+
/**
|
|
1694
|
+
* Time to wait for scheduled signal to activate (in minutes)
|
|
1695
|
+
* If signal does not activate within this time, it will be cancelled.
|
|
1696
|
+
*/
|
|
1697
|
+
CC_SCHEDULE_AWAIT_MINUTES: number;
|
|
1698
|
+
/**
|
|
1699
|
+
* Number of candles to use for average price calculation (VWAP)
|
|
1700
|
+
* Default: 5 candles (last 5 minutes when using 1m interval)
|
|
1701
|
+
*/
|
|
1702
|
+
CC_AVG_PRICE_CANDLES_COUNT: number;
|
|
1703
|
+
/**
|
|
1704
|
+
* Slippage percentage applied to entry and exit prices.
|
|
1705
|
+
* Simulates market impact and order book depth.
|
|
1706
|
+
* Applied twice (entry and exit) for realistic execution simulation.
|
|
1707
|
+
* Default: 0.1% per transaction
|
|
1708
|
+
*/
|
|
1709
|
+
CC_PERCENT_SLIPPAGE: number;
|
|
1710
|
+
/**
|
|
1711
|
+
* Fee percentage charged per transaction.
|
|
1712
|
+
* Applied twice (entry and exit) for total fee calculation.
|
|
1713
|
+
* Default: 0.1% per transaction (total 0.2%)
|
|
1714
|
+
*/
|
|
1715
|
+
CC_PERCENT_FEE: number;
|
|
1716
|
+
/**
|
|
1717
|
+
* Minimum TakeProfit distance from priceOpen (percentage)
|
|
1718
|
+
* Must be greater than (slippage + fees) to ensure profitable trades
|
|
1719
|
+
*
|
|
1720
|
+
* Calculation:
|
|
1721
|
+
* - Slippage effect: ~0.2% (0.1% × 2 transactions)
|
|
1722
|
+
* - Fees: 0.2% (0.1% × 2 transactions)
|
|
1723
|
+
* - Minimum profit buffer: 0.1%
|
|
1724
|
+
* - Total: 0.5%
|
|
1725
|
+
*
|
|
1726
|
+
* Default: 0.5% (covers all costs + minimum profit margin)
|
|
1727
|
+
*/
|
|
1728
|
+
CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
|
|
1729
|
+
/**
|
|
1730
|
+
* Minimum StopLoss distance from priceOpen (percentage)
|
|
1731
|
+
* Prevents signals from being immediately stopped out due to price volatility
|
|
1732
|
+
* Default: 0.5% (buffer to avoid instant stop loss on normal market fluctuations)
|
|
1733
|
+
*/
|
|
1734
|
+
CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
|
|
1735
|
+
/**
|
|
1736
|
+
* Maximum StopLoss distance from priceOpen (percentage)
|
|
1737
|
+
* Prevents catastrophic losses from extreme StopLoss values
|
|
1738
|
+
* Default: 20% (one signal cannot lose more than 20% of position)
|
|
1739
|
+
*/
|
|
1740
|
+
CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
|
|
1741
|
+
/**
|
|
1742
|
+
* Maximum signal lifetime in minutes
|
|
1743
|
+
* Prevents eternal signals that block risk limits for weeks/months
|
|
1744
|
+
* Default: 1440 minutes (1 day)
|
|
1745
|
+
*/
|
|
1746
|
+
CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
|
|
1747
|
+
/**
|
|
1748
|
+
* Maximum time allowed for signal generation (in seconds).
|
|
1749
|
+
* Prevents long-running or stuck signal generation routines from blocking
|
|
1750
|
+
* execution or consuming resources indefinitely. If generation exceeds this
|
|
1751
|
+
* threshold the attempt should be aborted, logged and optionally retried.
|
|
1752
|
+
*
|
|
1753
|
+
* Default: 180 seconds (3 minutes)
|
|
1754
|
+
*/
|
|
1755
|
+
CC_MAX_SIGNAL_GENERATION_SECONDS: number;
|
|
1756
|
+
/**
|
|
1757
|
+
* Number of retries for getCandles function
|
|
1758
|
+
* Default: 3 retries
|
|
1759
|
+
*/
|
|
1760
|
+
CC_GET_CANDLES_RETRY_COUNT: number;
|
|
1761
|
+
/**
|
|
1762
|
+
* Delay between retries for getCandles function (in milliseconds)
|
|
1763
|
+
* Default: 5000 ms (5 seconds)
|
|
1764
|
+
*/
|
|
1765
|
+
CC_GET_CANDLES_RETRY_DELAY_MS: number;
|
|
1766
|
+
/**
|
|
1767
|
+
* Maximum allowed deviation factor for price anomaly detection.
|
|
1768
|
+
* Price should not be more than this factor lower than reference price.
|
|
1769
|
+
*
|
|
1770
|
+
* Reasoning:
|
|
1771
|
+
* - Incomplete candles from Binance API typically have prices near 0 (e.g., $0.01-1)
|
|
1772
|
+
* - Normal BTC price ranges: $20,000-100,000
|
|
1773
|
+
* - Factor 1000 catches prices below $20-100 when median is $20,000-100,000
|
|
1774
|
+
* - Factor 100 would be too permissive (allows $200 when median is $20,000)
|
|
1775
|
+
* - Factor 10000 might be too strict for low-cap altcoins
|
|
1776
|
+
*
|
|
1777
|
+
* Example: BTC at $50,000 median → threshold $50 (catches $0.01-1 anomalies)
|
|
1778
|
+
*/
|
|
1779
|
+
CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
|
|
1780
|
+
/**
|
|
1781
|
+
* Minimum number of candles required for reliable median calculation.
|
|
1782
|
+
* Below this threshold, use simple average instead of median.
|
|
1783
|
+
*
|
|
1784
|
+
* Reasoning:
|
|
1785
|
+
* - Each candle provides 4 price points (OHLC)
|
|
1786
|
+
* - 5 candles = 20 price points, sufficient for robust median calculation
|
|
1787
|
+
* - Below 5 candles, single anomaly can heavily skew median
|
|
1788
|
+
* - Statistical rule of thumb: minimum 7-10 data points for median stability
|
|
1789
|
+
* - Average is more stable than median for small datasets (n < 20)
|
|
1790
|
+
*
|
|
1791
|
+
* Example: 3 candles = 12 points (use average), 5 candles = 20 points (use median)
|
|
1792
|
+
*/
|
|
1793
|
+
CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
|
|
1794
|
+
/**
|
|
1795
|
+
* Controls visibility of signal notes in markdown report tables.
|
|
1796
|
+
* When enabled, the "Note" column will be displayed in all markdown reports
|
|
1797
|
+
* (backtest, live, schedule, risk, etc.)
|
|
1798
|
+
*
|
|
1799
|
+
* Default: false (notes are hidden to reduce table width and improve readability)
|
|
1800
|
+
*/
|
|
1801
|
+
CC_REPORT_SHOW_SIGNAL_NOTE: boolean;
|
|
1802
|
+
/**
|
|
1803
|
+
* Breakeven threshold percentage - minimum profit distance from entry to enable breakeven.
|
|
1804
|
+
* When price moves this percentage in profit direction, stop-loss can be moved to entry (breakeven).
|
|
1805
|
+
*
|
|
1806
|
+
* Calculation:
|
|
1807
|
+
* - Slippage effect: ~0.2% (0.1% × 2 transactions)
|
|
1808
|
+
* - Fees: 0.2% (0.1% × 2 transactions)
|
|
1809
|
+
* - Total: 0.4%
|
|
1810
|
+
* - Added buffer: 0.2%
|
|
1811
|
+
* - Overall: 0.6%
|
|
1812
|
+
*
|
|
1813
|
+
* Default: 0.2% (additional buffer above costs to ensure no loss when moving to breakeven)
|
|
1814
|
+
*/
|
|
1815
|
+
CC_BREAKEVEN_THRESHOLD: number;
|
|
1816
|
+
};
|
|
1817
|
+
/**
|
|
1818
|
+
* Type for global configuration object.
|
|
1819
|
+
*/
|
|
1820
|
+
type GlobalConfig = typeof GLOBAL_CONFIG;
|
|
1821
|
+
|
|
1822
|
+
/**
|
|
1823
|
+
* Mapping of available table/markdown reports to their column definitions.
|
|
1824
|
+
*
|
|
1825
|
+
* Each property references a column definition object imported from
|
|
1826
|
+
* `src/assets/*.columns`. These are used by markdown/report generators
|
|
1827
|
+
* (backtest, live, schedule, risk, heat, performance, partial, walker).
|
|
1828
|
+
*/
|
|
1829
|
+
declare const COLUMN_CONFIG: {
|
|
1830
|
+
/** Columns used in backtest markdown tables and reports */
|
|
1831
|
+
backtest_columns: ColumnModel<IStrategyTickResultClosed>[];
|
|
1832
|
+
/** Columns used by heatmap / heat reports */
|
|
1833
|
+
heat_columns: ColumnModel<IHeatmapRow>[];
|
|
1834
|
+
/** Columns for live trading reports and logs */
|
|
1835
|
+
live_columns: ColumnModel<TickEvent>[];
|
|
1836
|
+
/** Columns for partial-results / incremental reports */
|
|
1837
|
+
partial_columns: ColumnModel<PartialEvent>[];
|
|
1838
|
+
/** Columns for breakeven protection events */
|
|
1839
|
+
breakeven_columns: ColumnModel<BreakevenEvent>[];
|
|
1840
|
+
/** Columns for performance summary reports */
|
|
1841
|
+
performance_columns: ColumnModel<MetricStats>[];
|
|
1842
|
+
/** Columns for risk-related reports */
|
|
1843
|
+
risk_columns: ColumnModel<RiskEvent>[];
|
|
1844
|
+
/** Columns for scheduled report output */
|
|
1845
|
+
schedule_columns: ColumnModel<ScheduledEvent>[];
|
|
1846
|
+
/** Walker: PnL summary columns */
|
|
1847
|
+
walker_pnl_columns: ColumnModel<SignalData$1>[];
|
|
1848
|
+
/** Walker: strategy-level summary columns */
|
|
1849
|
+
walker_strategy_columns: ColumnModel<IStrategyResult>[];
|
|
1850
|
+
};
|
|
1851
|
+
/**
|
|
1852
|
+
* Type for the column configuration object.
|
|
1853
|
+
*/
|
|
1854
|
+
type ColumnConfig = typeof COLUMN_CONFIG;
|
|
1855
|
+
|
|
1856
|
+
/**
|
|
1857
|
+
* Sets custom logger implementation for the framework.
|
|
1858
|
+
*
|
|
1859
|
+
* All log messages from internal services will be forwarded to the provided logger
|
|
1860
|
+
* with automatic context injection (strategyName, exchangeName, symbol, etc.).
|
|
1861
|
+
*
|
|
1862
|
+
* @param logger - Custom logger implementing ILogger interface
|
|
1863
|
+
*
|
|
1864
|
+
* @example
|
|
1865
|
+
* ```typescript
|
|
1866
|
+
* setLogger({
|
|
1867
|
+
* log: (topic, ...args) => console.log(topic, args),
|
|
1868
|
+
* debug: (topic, ...args) => console.debug(topic, args),
|
|
1869
|
+
* info: (topic, ...args) => console.info(topic, args),
|
|
1870
|
+
* });
|
|
1871
|
+
* ```
|
|
1872
|
+
*/
|
|
1873
|
+
declare function setLogger(logger: ILogger): void;
|
|
1874
|
+
/**
|
|
1875
|
+
* Sets global configuration parameters for the framework.
|
|
1876
|
+
* @param config - Partial configuration object to override default settings
|
|
1877
|
+
* @param _unsafe - Skip config validations - required for testbed
|
|
1878
|
+
*
|
|
1879
|
+
* @example
|
|
1880
|
+
* ```typescript
|
|
1881
|
+
* setConfig({
|
|
1882
|
+
* CC_SCHEDULE_AWAIT_MINUTES: 90,
|
|
1883
|
+
* });
|
|
1884
|
+
* ```
|
|
1885
|
+
*/
|
|
1886
|
+
declare function setConfig(config: Partial<GlobalConfig>, _unsafe?: boolean): void;
|
|
1887
|
+
/**
|
|
1888
|
+
* Retrieves a copy of the current global configuration.
|
|
1889
|
+
*
|
|
1890
|
+
* Returns a shallow copy of the current GLOBAL_CONFIG to prevent accidental mutations.
|
|
1891
|
+
* Use this to inspect the current configuration state without modifying it.
|
|
1892
|
+
*
|
|
1893
|
+
* @returns {GlobalConfig} A copy of the current global configuration object
|
|
1894
|
+
*
|
|
1895
|
+
* @example
|
|
1896
|
+
* ```typescript
|
|
1897
|
+
* const currentConfig = getConfig();
|
|
1898
|
+
* console.log(currentConfig.CC_SCHEDULE_AWAIT_MINUTES);
|
|
1899
|
+
* ```
|
|
1900
|
+
*/
|
|
1901
|
+
declare function getConfig(): {
|
|
1902
|
+
CC_SCHEDULE_AWAIT_MINUTES: number;
|
|
1903
|
+
CC_AVG_PRICE_CANDLES_COUNT: number;
|
|
1904
|
+
CC_PERCENT_SLIPPAGE: number;
|
|
1905
|
+
CC_PERCENT_FEE: number;
|
|
1906
|
+
CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
|
|
1907
|
+
CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
|
|
1908
|
+
CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
|
|
1909
|
+
CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
|
|
1910
|
+
CC_MAX_SIGNAL_GENERATION_SECONDS: number;
|
|
1911
|
+
CC_GET_CANDLES_RETRY_COUNT: number;
|
|
1912
|
+
CC_GET_CANDLES_RETRY_DELAY_MS: number;
|
|
1913
|
+
CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
|
|
1914
|
+
CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
|
|
1915
|
+
CC_REPORT_SHOW_SIGNAL_NOTE: boolean;
|
|
1916
|
+
CC_BREAKEVEN_THRESHOLD: number;
|
|
1917
|
+
};
|
|
1918
|
+
/**
|
|
1919
|
+
* Retrieves the default configuration object for the framework.
|
|
1920
|
+
*
|
|
1921
|
+
* Returns a reference to the default configuration with all preset values.
|
|
1922
|
+
* Use this to see what configuration options are available and their default values.
|
|
1923
|
+
*
|
|
1924
|
+
* @returns {GlobalConfig} The default configuration object
|
|
1925
|
+
*
|
|
1926
|
+
* @example
|
|
1927
|
+
* ```typescript
|
|
1928
|
+
* const defaultConfig = getDefaultConfig();
|
|
1929
|
+
* console.log(defaultConfig.CC_SCHEDULE_AWAIT_MINUTES);
|
|
1930
|
+
* ```
|
|
1931
|
+
*/
|
|
1932
|
+
declare function getDefaultConfig(): Readonly<{
|
|
1933
|
+
CC_SCHEDULE_AWAIT_MINUTES: number;
|
|
1934
|
+
CC_AVG_PRICE_CANDLES_COUNT: number;
|
|
1935
|
+
CC_PERCENT_SLIPPAGE: number;
|
|
1936
|
+
CC_PERCENT_FEE: number;
|
|
1937
|
+
CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
|
|
1938
|
+
CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
|
|
1939
|
+
CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
|
|
1940
|
+
CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
|
|
1941
|
+
CC_MAX_SIGNAL_GENERATION_SECONDS: number;
|
|
1942
|
+
CC_GET_CANDLES_RETRY_COUNT: number;
|
|
1943
|
+
CC_GET_CANDLES_RETRY_DELAY_MS: number;
|
|
1944
|
+
CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
|
|
1945
|
+
CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
|
|
1946
|
+
CC_REPORT_SHOW_SIGNAL_NOTE: boolean;
|
|
1947
|
+
CC_BREAKEVEN_THRESHOLD: number;
|
|
1948
|
+
}>;
|
|
1949
|
+
/**
|
|
1950
|
+
* Sets custom column configurations for markdown report generation.
|
|
1951
|
+
*
|
|
1952
|
+
* Allows overriding default column definitions for any report type.
|
|
1953
|
+
* All columns are validated before assignment to ensure structural correctness.
|
|
1954
|
+
*
|
|
1955
|
+
* @param columns - Partial column configuration object to override default column settings
|
|
1956
|
+
* @param _unsafe - Skip column validations - required for testbed
|
|
1957
|
+
*
|
|
1958
|
+
* @example
|
|
1959
|
+
* ```typescript
|
|
1960
|
+
* setColumns({
|
|
1961
|
+
* backtest_columns: [
|
|
1962
|
+
* {
|
|
1963
|
+
* key: "customId",
|
|
1964
|
+
* label: "Custom ID",
|
|
1965
|
+
* format: (data) => data.signal.id,
|
|
1966
|
+
* isVisible: () => true
|
|
1967
|
+
* }
|
|
1968
|
+
* ],
|
|
1969
|
+
* });
|
|
1970
|
+
* ```
|
|
1971
|
+
*
|
|
1972
|
+
* @throws {Error} If column configuration is invalid
|
|
1973
|
+
*/
|
|
1974
|
+
declare function setColumns(columns: Partial<ColumnConfig>, _unsafe?: boolean): void;
|
|
1975
|
+
/**
|
|
1976
|
+
* Retrieves a copy of the current column configuration for markdown report generation.
|
|
1977
|
+
*
|
|
1978
|
+
* Returns a shallow copy of the current COLUMN_CONFIG to prevent accidental mutations.
|
|
1979
|
+
* Use this to inspect the current column definitions without modifying them.
|
|
1980
|
+
*
|
|
1981
|
+
* @returns {ColumnConfig} A copy of the current column configuration object
|
|
1982
|
+
*
|
|
1983
|
+
* @example
|
|
1984
|
+
* ```typescript
|
|
1985
|
+
* const currentColumns = getColumns();
|
|
1986
|
+
* console.log(currentColumns.backtest_columns.length);
|
|
1987
|
+
* ```
|
|
1988
|
+
*/
|
|
1989
|
+
declare function getColumns(): {
|
|
1990
|
+
backtest_columns: ColumnModel<IStrategyTickResultClosed>[];
|
|
1991
|
+
heat_columns: ColumnModel<IHeatmapRow>[];
|
|
1992
|
+
live_columns: ColumnModel<TickEvent>[];
|
|
1993
|
+
partial_columns: ColumnModel<PartialEvent>[];
|
|
1994
|
+
breakeven_columns: ColumnModel<BreakevenEvent>[];
|
|
1995
|
+
performance_columns: ColumnModel<MetricStats>[];
|
|
1996
|
+
risk_columns: ColumnModel<RiskEvent>[];
|
|
1997
|
+
schedule_columns: ColumnModel<ScheduledEvent>[];
|
|
1998
|
+
walker_pnl_columns: ColumnModel<SignalData$1>[];
|
|
1999
|
+
walker_strategy_columns: ColumnModel<IStrategyResult>[];
|
|
2000
|
+
};
|
|
2001
|
+
/**
|
|
2002
|
+
* Retrieves the default column configuration object for markdown report generation.
|
|
2003
|
+
*
|
|
2004
|
+
* Returns a reference to the default column definitions with all preset values.
|
|
2005
|
+
* Use this to see what column options are available and their default definitions.
|
|
2006
|
+
*
|
|
2007
|
+
* @returns {ColumnConfig} The default column configuration object
|
|
2008
|
+
*
|
|
2009
|
+
* @example
|
|
2010
|
+
* ```typescript
|
|
2011
|
+
* const defaultColumns = getDefaultColumns();
|
|
2012
|
+
* console.log(defaultColumns.backtest_columns);
|
|
2013
|
+
* ```
|
|
2014
|
+
*/
|
|
2015
|
+
declare function getDefaultColumns(): Readonly<{
|
|
2016
|
+
backtest_columns: ColumnModel<IStrategyTickResultClosed>[];
|
|
2017
|
+
heat_columns: ColumnModel<IHeatmapRow>[];
|
|
2018
|
+
live_columns: ColumnModel<TickEvent>[];
|
|
2019
|
+
partial_columns: ColumnModel<PartialEvent>[];
|
|
2020
|
+
breakeven_columns: ColumnModel<BreakevenEvent>[];
|
|
2021
|
+
performance_columns: ColumnModel<MetricStats>[];
|
|
2022
|
+
risk_columns: ColumnModel<RiskEvent>[];
|
|
2023
|
+
schedule_columns: ColumnModel<ScheduledEvent>[];
|
|
2024
|
+
walker_pnl_columns: ColumnModel<SignalData$1>[];
|
|
2025
|
+
walker_strategy_columns: ColumnModel<IStrategyResult>[];
|
|
2026
|
+
}>;
|
|
2027
|
+
|
|
1668
2028
|
/**
|
|
1669
2029
|
* Statistical data calculated from backtest results.
|
|
1670
2030
|
*
|
|
@@ -1783,13 +2143,13 @@ interface IWalkerSchema {
|
|
|
1783
2143
|
*/
|
|
1784
2144
|
interface IWalkerCallbacks {
|
|
1785
2145
|
/** Called when starting to test a specific strategy */
|
|
1786
|
-
onStrategyStart: (strategyName: StrategyName, symbol: string) => void
|
|
2146
|
+
onStrategyStart: (strategyName: StrategyName, symbol: string) => void | Promise<void>;
|
|
1787
2147
|
/** Called when a strategy backtest completes */
|
|
1788
|
-
onStrategyComplete: (strategyName: StrategyName, symbol: string, stats: BacktestStatisticsModel, metric: number | null) => void
|
|
2148
|
+
onStrategyComplete: (strategyName: StrategyName, symbol: string, stats: BacktestStatisticsModel, metric: number | null) => void | Promise<void>;
|
|
1789
2149
|
/** Called when a strategy backtest fails with an error */
|
|
1790
|
-
onStrategyError: (strategyName: StrategyName, symbol: string, error: Error | unknown) => void
|
|
2150
|
+
onStrategyError: (strategyName: StrategyName, symbol: string, error: Error | unknown) => void | Promise<void>;
|
|
1791
2151
|
/** Called when all strategies have been tested */
|
|
1792
|
-
onComplete: (results: IWalkerResults) => void
|
|
2152
|
+
onComplete: (results: IWalkerResults) => void | Promise<void>;
|
|
1793
2153
|
}
|
|
1794
2154
|
/**
|
|
1795
2155
|
* Result for a single strategy in the comparison.
|
|
@@ -1924,7 +2284,7 @@ interface ISizingCallbacks {
|
|
|
1924
2284
|
* @param quantity - Calculated position size
|
|
1925
2285
|
* @param params - Parameters used for calculation
|
|
1926
2286
|
*/
|
|
1927
|
-
onCalculate: (quantity: number, params: ISizingCalculateParams) => void
|
|
2287
|
+
onCalculate: (quantity: number, params: ISizingCalculateParams) => void | Promise<void>;
|
|
1928
2288
|
}
|
|
1929
2289
|
/**
|
|
1930
2290
|
* Base sizing schema with common fields.
|
|
@@ -3403,6 +3763,91 @@ interface PartialLossContract {
|
|
|
3403
3763
|
timestamp: number;
|
|
3404
3764
|
}
|
|
3405
3765
|
|
|
3766
|
+
/**
|
|
3767
|
+
* Contract for breakeven events.
|
|
3768
|
+
*
|
|
3769
|
+
* Emitted by breakevenSubject when a signal's stop-loss is moved to breakeven (entry price).
|
|
3770
|
+
* Used for tracking risk reduction milestones and monitoring strategy safety.
|
|
3771
|
+
*
|
|
3772
|
+
* Events are emitted only once per signal (idempotent - protected by ClientBreakeven state).
|
|
3773
|
+
* Breakeven is triggered when price moves far enough in profit direction to cover transaction costs.
|
|
3774
|
+
*
|
|
3775
|
+
* Consumers:
|
|
3776
|
+
* - BreakevenMarkdownService: Accumulates events for report generation
|
|
3777
|
+
* - User callbacks via listenBreakeven() / listenBreakevenOnce()
|
|
3778
|
+
*
|
|
3779
|
+
* @example
|
|
3780
|
+
* ```typescript
|
|
3781
|
+
* import { listenBreakeven } from "backtest-kit";
|
|
3782
|
+
*
|
|
3783
|
+
* // Listen to all breakeven events
|
|
3784
|
+
* listenBreakeven((event) => {
|
|
3785
|
+
* console.log(`[${event.backtest ? "Backtest" : "Live"}] Signal ${event.data.id} moved to breakeven`);
|
|
3786
|
+
* console.log(`Symbol: ${event.symbol}, Price: ${event.currentPrice}`);
|
|
3787
|
+
* console.log(`Position: ${event.data.position}, Entry: ${event.data.priceOpen}`);
|
|
3788
|
+
* console.log(`Original SL: ${event.data.priceStopLoss}, New SL: ${event.data.priceOpen}`);
|
|
3789
|
+
* });
|
|
3790
|
+
*
|
|
3791
|
+
* // Wait for specific signal to reach breakeven
|
|
3792
|
+
* listenBreakevenOnce(
|
|
3793
|
+
* (event) => event.data.id === "target-signal-id",
|
|
3794
|
+
* (event) => console.log("Signal reached breakeven:", event.data.id)
|
|
3795
|
+
* );
|
|
3796
|
+
* ```
|
|
3797
|
+
*/
|
|
3798
|
+
interface BreakevenContract {
|
|
3799
|
+
/**
|
|
3800
|
+
* Trading pair symbol (e.g., "BTCUSDT").
|
|
3801
|
+
* Identifies which market this breakeven event belongs to.
|
|
3802
|
+
*/
|
|
3803
|
+
symbol: string;
|
|
3804
|
+
/**
|
|
3805
|
+
* Strategy name that generated this signal.
|
|
3806
|
+
* Identifies which strategy execution this breakeven event belongs to.
|
|
3807
|
+
*/
|
|
3808
|
+
strategyName: StrategyName;
|
|
3809
|
+
/**
|
|
3810
|
+
* Exchange name where this signal is being executed.
|
|
3811
|
+
* Identifies which exchange this breakeven event belongs to.
|
|
3812
|
+
*/
|
|
3813
|
+
exchangeName: ExchangeName;
|
|
3814
|
+
/**
|
|
3815
|
+
* Frame name where this signal is being executed.
|
|
3816
|
+
* Identifies which frame this breakeven event belongs to (empty string for live mode).
|
|
3817
|
+
*/
|
|
3818
|
+
frameName: FrameName;
|
|
3819
|
+
/**
|
|
3820
|
+
* Complete signal row data.
|
|
3821
|
+
* Contains all signal information: id, position, priceOpen, priceTakeProfit, priceStopLoss, etc.
|
|
3822
|
+
*/
|
|
3823
|
+
data: ISignalRow;
|
|
3824
|
+
/**
|
|
3825
|
+
* Current market price at which breakeven was triggered.
|
|
3826
|
+
* Used to verify threshold calculation.
|
|
3827
|
+
*/
|
|
3828
|
+
currentPrice: number;
|
|
3829
|
+
/**
|
|
3830
|
+
* Execution mode flag.
|
|
3831
|
+
* - true: Event from backtest execution (historical candle data)
|
|
3832
|
+
* - false: Event from live trading (real-time tick)
|
|
3833
|
+
*/
|
|
3834
|
+
backtest: boolean;
|
|
3835
|
+
/**
|
|
3836
|
+
* Event timestamp in milliseconds since Unix epoch.
|
|
3837
|
+
*
|
|
3838
|
+
* Timing semantics:
|
|
3839
|
+
* - Live mode: when.getTime() at the moment breakeven was set
|
|
3840
|
+
* - Backtest mode: candle.timestamp of the candle that triggered breakeven
|
|
3841
|
+
*
|
|
3842
|
+
* @example
|
|
3843
|
+
* ```typescript
|
|
3844
|
+
* const eventDate = new Date(event.timestamp);
|
|
3845
|
+
* console.log(`Breakeven set at: ${eventDate.toISOString()}`);
|
|
3846
|
+
* ```
|
|
3847
|
+
*/
|
|
3848
|
+
timestamp: number;
|
|
3849
|
+
}
|
|
3850
|
+
|
|
3406
3851
|
/**
|
|
3407
3852
|
* Contract for risk rejection events.
|
|
3408
3853
|
*
|
|
@@ -4302,6 +4747,64 @@ declare function listenPartialLoss(fn: (event: PartialLossContract) => void): ()
|
|
|
4302
4747
|
* ```
|
|
4303
4748
|
*/
|
|
4304
4749
|
declare function listenPartialLossOnce(filterFn: (event: PartialLossContract) => boolean, fn: (event: PartialLossContract) => void): () => void;
|
|
4750
|
+
/**
|
|
4751
|
+
* Subscribes to breakeven protection events with queued async processing.
|
|
4752
|
+
*
|
|
4753
|
+
* Emits when a signal's stop-loss is moved to breakeven (entry price).
|
|
4754
|
+
* This happens when price moves far enough in profit direction to cover transaction costs.
|
|
4755
|
+
* Events are processed sequentially in order received, even if callback is async.
|
|
4756
|
+
* Uses queued wrapper to prevent concurrent execution of the callback.
|
|
4757
|
+
*
|
|
4758
|
+
* @param fn - Callback function to handle breakeven events
|
|
4759
|
+
* @returns Unsubscribe function to stop listening to events
|
|
4760
|
+
*
|
|
4761
|
+
* @example
|
|
4762
|
+
* ```typescript
|
|
4763
|
+
* import { listenBreakeven } from "./function/event";
|
|
4764
|
+
*
|
|
4765
|
+
* const unsubscribe = listenBreakeven((event) => {
|
|
4766
|
+
* console.log(`Signal ${event.data.id} reached breakeven`);
|
|
4767
|
+
* console.log(`Symbol: ${event.symbol}, Position: ${event.data.position}`);
|
|
4768
|
+
* console.log(`Entry: ${event.data.priceOpen}, Current: ${event.currentPrice}`);
|
|
4769
|
+
* console.log(`Mode: ${event.backtest ? "Backtest" : "Live"}`);
|
|
4770
|
+
* });
|
|
4771
|
+
*
|
|
4772
|
+
* // Later: stop listening
|
|
4773
|
+
* unsubscribe();
|
|
4774
|
+
* ```
|
|
4775
|
+
*/
|
|
4776
|
+
declare function listenBreakeven(fn: (event: BreakevenContract) => void): () => void;
|
|
4777
|
+
/**
|
|
4778
|
+
* Subscribes to filtered breakeven protection events with one-time execution.
|
|
4779
|
+
*
|
|
4780
|
+
* Listens for events matching the filter predicate, then executes callback once
|
|
4781
|
+
* and automatically unsubscribes. Useful for waiting for specific breakeven conditions.
|
|
4782
|
+
*
|
|
4783
|
+
* @param filterFn - Predicate to filter which events trigger the callback
|
|
4784
|
+
* @param fn - Callback function to handle the filtered event (called only once)
|
|
4785
|
+
* @returns Unsubscribe function to cancel the listener before it fires
|
|
4786
|
+
*
|
|
4787
|
+
* @example
|
|
4788
|
+
* ```typescript
|
|
4789
|
+
* import { listenBreakevenOnce } from "./function/event";
|
|
4790
|
+
*
|
|
4791
|
+
* // Wait for first breakeven on any signal
|
|
4792
|
+
* listenBreakevenOnce(
|
|
4793
|
+
* (event) => true,
|
|
4794
|
+
* (event) => console.log("First breakeven reached:", event.data.id)
|
|
4795
|
+
* );
|
|
4796
|
+
*
|
|
4797
|
+
* // Wait for breakeven on BTCUSDT LONG position
|
|
4798
|
+
* const cancel = listenBreakevenOnce(
|
|
4799
|
+
* (event) => event.symbol === "BTCUSDT" && event.data.position === "long",
|
|
4800
|
+
* (event) => console.log("BTCUSDT LONG reached breakeven at", event.currentPrice)
|
|
4801
|
+
* );
|
|
4802
|
+
*
|
|
4803
|
+
* // Cancel if needed before event fires
|
|
4804
|
+
* cancel();
|
|
4805
|
+
* ```
|
|
4806
|
+
*/
|
|
4807
|
+
declare function listenBreakevenOnce(filterFn: (event: BreakevenContract) => boolean, fn: (event: BreakevenContract) => void): () => void;
|
|
4305
4808
|
/**
|
|
4306
4809
|
* Subscribes to risk rejection events with queued async processing.
|
|
4307
4810
|
*
|
|
@@ -5369,6 +5872,12 @@ interface IPersistBase<Entity extends IEntity | null = IEntity> {
|
|
|
5369
5872
|
* @throws Error if write fails
|
|
5370
5873
|
*/
|
|
5371
5874
|
writeValue(entityId: EntityId, entity: Entity): Promise<void>;
|
|
5875
|
+
/**
|
|
5876
|
+
* Async generator yielding all entity IDs.
|
|
5877
|
+
*
|
|
5878
|
+
* @returns AsyncGenerator yielding entity IDs
|
|
5879
|
+
*/
|
|
5880
|
+
keys(): AsyncGenerator<EntityId>;
|
|
5372
5881
|
}
|
|
5373
5882
|
/**
|
|
5374
5883
|
* Base class for file-based persistence with atomic writes.
|
|
@@ -5503,9 +6012,10 @@ declare class PersistSignalUtils {
|
|
|
5503
6012
|
*
|
|
5504
6013
|
* @param symbol - Trading pair symbol
|
|
5505
6014
|
* @param strategyName - Strategy identifier
|
|
6015
|
+
* @param exchangeName - Exchange identifier
|
|
5506
6016
|
* @returns Promise resolving to signal or null
|
|
5507
6017
|
*/
|
|
5508
|
-
readSignalData: (symbol: string, strategyName: StrategyName) => Promise<ISignalRow | null>;
|
|
6018
|
+
readSignalData: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName) => Promise<ISignalRow | null>;
|
|
5509
6019
|
/**
|
|
5510
6020
|
* Writes signal data to disk with atomic file writes.
|
|
5511
6021
|
*
|
|
@@ -5515,9 +6025,10 @@ declare class PersistSignalUtils {
|
|
|
5515
6025
|
* @param signalRow - Signal data (null to clear)
|
|
5516
6026
|
* @param symbol - Trading pair symbol
|
|
5517
6027
|
* @param strategyName - Strategy identifier
|
|
6028
|
+
* @param exchangeName - Exchange identifier
|
|
5518
6029
|
* @returns Promise that resolves when write is complete
|
|
5519
6030
|
*/
|
|
5520
|
-
writeSignalData: (signalRow: ISignalRow | null, symbol: string, strategyName: StrategyName) => Promise<void>;
|
|
6031
|
+
writeSignalData: (signalRow: ISignalRow | null, symbol: string, strategyName: StrategyName, exchangeName: ExchangeName) => Promise<void>;
|
|
5521
6032
|
}
|
|
5522
6033
|
/**
|
|
5523
6034
|
* Global singleton instance of PersistSignalUtils.
|
|
@@ -5577,9 +6088,10 @@ declare class PersistRiskUtils {
|
|
|
5577
6088
|
* Returns empty Map if no positions exist.
|
|
5578
6089
|
*
|
|
5579
6090
|
* @param riskName - Risk profile identifier
|
|
6091
|
+
* @param exchangeName - Exchange identifier
|
|
5580
6092
|
* @returns Promise resolving to Map of active positions
|
|
5581
6093
|
*/
|
|
5582
|
-
readPositionData: (riskName: RiskName) => Promise<RiskData>;
|
|
6094
|
+
readPositionData: (riskName: RiskName, exchangeName: ExchangeName) => Promise<RiskData>;
|
|
5583
6095
|
/**
|
|
5584
6096
|
* Writes active positions to disk with atomic file writes.
|
|
5585
6097
|
*
|
|
@@ -5588,9 +6100,10 @@ declare class PersistRiskUtils {
|
|
|
5588
6100
|
*
|
|
5589
6101
|
* @param positions - Map of active positions
|
|
5590
6102
|
* @param riskName - Risk profile identifier
|
|
6103
|
+
* @param exchangeName - Exchange identifier
|
|
5591
6104
|
* @returns Promise that resolves when write is complete
|
|
5592
6105
|
*/
|
|
5593
|
-
writePositionData: (riskRow: RiskData, riskName: RiskName) => Promise<void>;
|
|
6106
|
+
writePositionData: (riskRow: RiskData, riskName: RiskName, exchangeName: ExchangeName) => Promise<void>;
|
|
5594
6107
|
}
|
|
5595
6108
|
/**
|
|
5596
6109
|
* Global singleton instance of PersistRiskUtils.
|
|
@@ -5651,9 +6164,10 @@ declare class PersistScheduleUtils {
|
|
|
5651
6164
|
*
|
|
5652
6165
|
* @param symbol - Trading pair symbol
|
|
5653
6166
|
* @param strategyName - Strategy identifier
|
|
6167
|
+
* @param exchangeName - Exchange identifier
|
|
5654
6168
|
* @returns Promise resolving to scheduled signal or null
|
|
5655
6169
|
*/
|
|
5656
|
-
readScheduleData: (symbol: string, strategyName: StrategyName) => Promise<IScheduledSignalRow | null>;
|
|
6170
|
+
readScheduleData: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName) => Promise<IScheduledSignalRow | null>;
|
|
5657
6171
|
/**
|
|
5658
6172
|
* Writes scheduled signal data to disk with atomic file writes.
|
|
5659
6173
|
*
|
|
@@ -5663,9 +6177,10 @@ declare class PersistScheduleUtils {
|
|
|
5663
6177
|
* @param scheduledSignalRow - Scheduled signal data (null to clear)
|
|
5664
6178
|
* @param symbol - Trading pair symbol
|
|
5665
6179
|
* @param strategyName - Strategy identifier
|
|
6180
|
+
* @param exchangeName - Exchange identifier
|
|
5666
6181
|
* @returns Promise that resolves when write is complete
|
|
5667
6182
|
*/
|
|
5668
|
-
writeScheduleData: (scheduledSignalRow: IScheduledSignalRow | null, symbol: string, strategyName: StrategyName) => Promise<void>;
|
|
6183
|
+
writeScheduleData: (scheduledSignalRow: IScheduledSignalRow | null, symbol: string, strategyName: StrategyName, exchangeName: ExchangeName) => Promise<void>;
|
|
5669
6184
|
}
|
|
5670
6185
|
/**
|
|
5671
6186
|
* Global singleton instance of PersistScheduleUtils.
|
|
@@ -5726,9 +6241,11 @@ declare class PersistPartialUtils {
|
|
|
5726
6241
|
*
|
|
5727
6242
|
* @param symbol - Trading pair symbol
|
|
5728
6243
|
* @param strategyName - Strategy identifier
|
|
6244
|
+
* @param signalId - Signal identifier
|
|
6245
|
+
* @param exchangeName - Exchange identifier
|
|
5729
6246
|
* @returns Promise resolving to partial data record
|
|
5730
6247
|
*/
|
|
5731
|
-
readPartialData: (symbol: string, strategyName: StrategyName) => Promise<PartialData>;
|
|
6248
|
+
readPartialData: (symbol: string, strategyName: StrategyName, signalId: string, exchangeName: ExchangeName) => Promise<PartialData>;
|
|
5732
6249
|
/**
|
|
5733
6250
|
* Writes partial data to disk with atomic file writes.
|
|
5734
6251
|
*
|
|
@@ -5738,9 +6255,11 @@ declare class PersistPartialUtils {
|
|
|
5738
6255
|
* @param partialData - Record of signal IDs to partial data
|
|
5739
6256
|
* @param symbol - Trading pair symbol
|
|
5740
6257
|
* @param strategyName - Strategy identifier
|
|
6258
|
+
* @param signalId - Signal identifier
|
|
6259
|
+
* @param exchangeName - Exchange identifier
|
|
5741
6260
|
* @returns Promise that resolves when write is complete
|
|
5742
6261
|
*/
|
|
5743
|
-
writePartialData: (partialData: PartialData, symbol: string, strategyName: StrategyName) => Promise<void>;
|
|
6262
|
+
writePartialData: (partialData: PartialData, symbol: string, strategyName: StrategyName, signalId: string, exchangeName: ExchangeName) => Promise<void>;
|
|
5744
6263
|
}
|
|
5745
6264
|
/**
|
|
5746
6265
|
* Global singleton instance of PersistPartialUtils.
|
|
@@ -5759,6 +6278,120 @@ declare class PersistPartialUtils {
|
|
|
5759
6278
|
* ```
|
|
5760
6279
|
*/
|
|
5761
6280
|
declare const PersistPartialAdapter: PersistPartialUtils;
|
|
6281
|
+
/**
|
|
6282
|
+
* Type for persisted breakeven data.
|
|
6283
|
+
* Stores breakeven state (reached flag) for each signal ID.
|
|
6284
|
+
*/
|
|
6285
|
+
type BreakevenData = Record<string, IBreakevenData>;
|
|
6286
|
+
/**
|
|
6287
|
+
* Persistence utility class for breakeven state management.
|
|
6288
|
+
*
|
|
6289
|
+
* Handles reading and writing breakeven state to disk.
|
|
6290
|
+
* Uses memoized PersistBase instances per symbol-strategy pair.
|
|
6291
|
+
*
|
|
6292
|
+
* Features:
|
|
6293
|
+
* - Atomic file writes via PersistBase.writeValue()
|
|
6294
|
+
* - Lazy initialization on first access
|
|
6295
|
+
* - Singleton pattern for global access
|
|
6296
|
+
* - Custom adapter support via usePersistBreakevenAdapter()
|
|
6297
|
+
*
|
|
6298
|
+
* File structure:
|
|
6299
|
+
* ```
|
|
6300
|
+
* ./dump/data/breakeven/
|
|
6301
|
+
* ├── BTCUSDT_my-strategy/
|
|
6302
|
+
* │ └── state.json // { "signal-id-1": { reached: true }, ... }
|
|
6303
|
+
* └── ETHUSDT_other-strategy/
|
|
6304
|
+
* └── state.json
|
|
6305
|
+
* ```
|
|
6306
|
+
*
|
|
6307
|
+
* @example
|
|
6308
|
+
* ```typescript
|
|
6309
|
+
* // Read breakeven data
|
|
6310
|
+
* const breakevenData = await PersistBreakevenAdapter.readBreakevenData("BTCUSDT", "my-strategy");
|
|
6311
|
+
* // Returns: { "signal-id": { reached: true }, ... }
|
|
6312
|
+
*
|
|
6313
|
+
* // Write breakeven data
|
|
6314
|
+
* await PersistBreakevenAdapter.writeBreakevenData(breakevenData, "BTCUSDT", "my-strategy");
|
|
6315
|
+
* ```
|
|
6316
|
+
*/
|
|
6317
|
+
declare class PersistBreakevenUtils {
|
|
6318
|
+
/**
|
|
6319
|
+
* Factory for creating PersistBase instances.
|
|
6320
|
+
* Can be replaced via usePersistBreakevenAdapter().
|
|
6321
|
+
*/
|
|
6322
|
+
private PersistBreakevenFactory;
|
|
6323
|
+
/**
|
|
6324
|
+
* Memoized storage factory for breakeven data.
|
|
6325
|
+
* Creates one PersistBase instance per symbol-strategy-exchange combination.
|
|
6326
|
+
* Key format: "symbol:strategyName:exchangeName"
|
|
6327
|
+
*
|
|
6328
|
+
* @param symbol - Trading pair symbol
|
|
6329
|
+
* @param strategyName - Strategy identifier
|
|
6330
|
+
* @param exchangeName - Exchange identifier
|
|
6331
|
+
* @returns PersistBase instance for this symbol-strategy-exchange combination
|
|
6332
|
+
*/
|
|
6333
|
+
private getBreakevenStorage;
|
|
6334
|
+
/**
|
|
6335
|
+
* Registers a custom persistence adapter.
|
|
6336
|
+
*
|
|
6337
|
+
* @param Ctor - Custom PersistBase constructor
|
|
6338
|
+
*
|
|
6339
|
+
* @example
|
|
6340
|
+
* ```typescript
|
|
6341
|
+
* class RedisPersist extends PersistBase {
|
|
6342
|
+
* async readValue(id) { return JSON.parse(await redis.get(id)); }
|
|
6343
|
+
* async writeValue(id, entity) { await redis.set(id, JSON.stringify(entity)); }
|
|
6344
|
+
* }
|
|
6345
|
+
* PersistBreakevenAdapter.usePersistBreakevenAdapter(RedisPersist);
|
|
6346
|
+
* ```
|
|
6347
|
+
*/
|
|
6348
|
+
usePersistBreakevenAdapter(Ctor: TPersistBaseCtor<string, BreakevenData>): void;
|
|
6349
|
+
/**
|
|
6350
|
+
* Reads persisted breakeven data for a symbol and strategy.
|
|
6351
|
+
*
|
|
6352
|
+
* Called by ClientBreakeven.waitForInit() to restore state.
|
|
6353
|
+
* Returns empty object if no breakeven data exists.
|
|
6354
|
+
*
|
|
6355
|
+
* @param symbol - Trading pair symbol
|
|
6356
|
+
* @param strategyName - Strategy identifier
|
|
6357
|
+
* @param signalId - Signal identifier
|
|
6358
|
+
* @param exchangeName - Exchange identifier
|
|
6359
|
+
* @returns Promise resolving to breakeven data record
|
|
6360
|
+
*/
|
|
6361
|
+
readBreakevenData: (symbol: string, strategyName: StrategyName, signalId: string, exchangeName: ExchangeName) => Promise<BreakevenData>;
|
|
6362
|
+
/**
|
|
6363
|
+
* Writes breakeven data to disk.
|
|
6364
|
+
*
|
|
6365
|
+
* Called by ClientBreakeven._persistState() after state changes.
|
|
6366
|
+
* Creates directory and file if they don't exist.
|
|
6367
|
+
* Uses atomic writes to prevent data corruption.
|
|
6368
|
+
*
|
|
6369
|
+
* @param breakevenData - Breakeven data record to persist
|
|
6370
|
+
* @param symbol - Trading pair symbol
|
|
6371
|
+
* @param strategyName - Strategy identifier
|
|
6372
|
+
* @param signalId - Signal identifier
|
|
6373
|
+
* @param exchangeName - Exchange identifier
|
|
6374
|
+
* @returns Promise that resolves when write is complete
|
|
6375
|
+
*/
|
|
6376
|
+
writeBreakevenData: (breakevenData: BreakevenData, symbol: string, strategyName: StrategyName, signalId: string, exchangeName: ExchangeName) => Promise<void>;
|
|
6377
|
+
}
|
|
6378
|
+
/**
|
|
6379
|
+
* Global singleton instance of PersistBreakevenUtils.
|
|
6380
|
+
* Used by ClientBreakeven for breakeven state persistence.
|
|
6381
|
+
*
|
|
6382
|
+
* @example
|
|
6383
|
+
* ```typescript
|
|
6384
|
+
* // Custom adapter
|
|
6385
|
+
* PersistBreakevenAdapter.usePersistBreakevenAdapter(RedisPersist);
|
|
6386
|
+
*
|
|
6387
|
+
* // Read breakeven data
|
|
6388
|
+
* const breakevenData = await PersistBreakevenAdapter.readBreakevenData("BTCUSDT", "my-strategy");
|
|
6389
|
+
*
|
|
6390
|
+
* // Write breakeven data
|
|
6391
|
+
* await PersistBreakevenAdapter.writeBreakevenData(breakevenData, "BTCUSDT", "my-strategy");
|
|
6392
|
+
* ```
|
|
6393
|
+
*/
|
|
6394
|
+
declare const PersistBreakevenAdapter: PersistBreakevenUtils;
|
|
5762
6395
|
|
|
5763
6396
|
/**
|
|
5764
6397
|
* Type alias for column configuration used in backtest markdown reports.
|
|
@@ -5791,7 +6424,7 @@ declare const PersistPartialAdapter: PersistPartialUtils;
|
|
|
5791
6424
|
* @see ColumnModel for the base interface
|
|
5792
6425
|
* @see IStrategyTickResultClosed for the signal data structure
|
|
5793
6426
|
*/
|
|
5794
|
-
type Columns$
|
|
6427
|
+
type Columns$7 = ColumnModel<IStrategyTickResultClosed>;
|
|
5795
6428
|
/**
|
|
5796
6429
|
* Service for generating and saving backtest markdown reports.
|
|
5797
6430
|
*
|
|
@@ -5885,7 +6518,7 @@ declare class BacktestMarkdownService {
|
|
|
5885
6518
|
* console.log(markdown);
|
|
5886
6519
|
* ```
|
|
5887
6520
|
*/
|
|
5888
|
-
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$
|
|
6521
|
+
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$7[]) => Promise<string>;
|
|
5889
6522
|
/**
|
|
5890
6523
|
* Saves symbol-strategy report to disk.
|
|
5891
6524
|
* Creates directory if it doesn't exist.
|
|
@@ -5910,7 +6543,7 @@ declare class BacktestMarkdownService {
|
|
|
5910
6543
|
* await service.dump("BTCUSDT", "my-strategy", "binance", "1h", true, "./custom/path");
|
|
5911
6544
|
* ```
|
|
5912
6545
|
*/
|
|
5913
|
-
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$
|
|
6546
|
+
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$7[]) => Promise<void>;
|
|
5914
6547
|
/**
|
|
5915
6548
|
* Clears accumulated signal data from storage.
|
|
5916
6549
|
* If payload is provided, clears only that specific symbol-strategy-exchange-frame-backtest combination's data.
|
|
@@ -5948,6 +6581,11 @@ declare class BacktestMarkdownService {
|
|
|
5948
6581
|
* ```
|
|
5949
6582
|
*/
|
|
5950
6583
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
6584
|
+
/**
|
|
6585
|
+
* Function to unsubscribe from backtest signal events.
|
|
6586
|
+
* Assigned during init().
|
|
6587
|
+
*/
|
|
6588
|
+
unsubscribe: Function;
|
|
5951
6589
|
}
|
|
5952
6590
|
|
|
5953
6591
|
/**
|
|
@@ -6172,6 +6810,59 @@ declare class BacktestUtils {
|
|
|
6172
6810
|
exchangeName: ExchangeName;
|
|
6173
6811
|
frameName: FrameName;
|
|
6174
6812
|
}) => Promise<void>;
|
|
6813
|
+
/**
|
|
6814
|
+
* Adjusts the trailing stop-loss distance for an active pending signal.
|
|
6815
|
+
*
|
|
6816
|
+
* Updates the stop-loss distance by a percentage adjustment relative to the original SL distance.
|
|
6817
|
+
* Positive percentShift tightens the SL (reduces distance), negative percentShift loosens it.
|
|
6818
|
+
*
|
|
6819
|
+
* @param symbol - Trading pair symbol
|
|
6820
|
+
* @param percentShift - Percentage adjustment to SL distance (-100 to 100)
|
|
6821
|
+
* @param context - Execution context with strategyName, exchangeName, and frameName
|
|
6822
|
+
* @returns Promise that resolves when trailing SL is updated
|
|
6823
|
+
*
|
|
6824
|
+
* @example
|
|
6825
|
+
* ```typescript
|
|
6826
|
+
* // LONG: entry=100, originalSL=90, distance=10
|
|
6827
|
+
* // Tighten stop by 50%: newSL = 100 - 10*(1-0.5) = 95
|
|
6828
|
+
* await Backtest.trailingStop("BTCUSDT", -50, {
|
|
6829
|
+
* exchangeName: "binance",
|
|
6830
|
+
* frameName: "frame1",
|
|
6831
|
+
* strategyName: "my-strategy"
|
|
6832
|
+
* });
|
|
6833
|
+
* ```
|
|
6834
|
+
*/
|
|
6835
|
+
trailingStop: (symbol: string, percentShift: number, context: {
|
|
6836
|
+
strategyName: StrategyName;
|
|
6837
|
+
exchangeName: ExchangeName;
|
|
6838
|
+
frameName: FrameName;
|
|
6839
|
+
}) => Promise<void>;
|
|
6840
|
+
/**
|
|
6841
|
+
* Moves stop-loss to breakeven when price reaches threshold.
|
|
6842
|
+
*
|
|
6843
|
+
* Moves SL to entry price (zero-risk position) when current price has moved
|
|
6844
|
+
* far enough in profit direction. Threshold is calculated as: (CC_PERCENT_SLIPPAGE + CC_PERCENT_FEE) * 2
|
|
6845
|
+
*
|
|
6846
|
+
* @param symbol - Trading pair symbol
|
|
6847
|
+
* @param currentPrice - Current market price to check threshold
|
|
6848
|
+
* @param context - Strategy context with strategyName, exchangeName, frameName
|
|
6849
|
+
* @returns Promise<boolean> - true if breakeven was set, false otherwise
|
|
6850
|
+
*
|
|
6851
|
+
* @example
|
|
6852
|
+
* ```typescript
|
|
6853
|
+
* const moved = await Backtest.breakeven(
|
|
6854
|
+
* "BTCUSDT",
|
|
6855
|
+
* 112,
|
|
6856
|
+
* { strategyName: "my-strategy", exchangeName: "binance", frameName: "1h" }
|
|
6857
|
+
* );
|
|
6858
|
+
* console.log(moved); // true (SL moved to entry price)
|
|
6859
|
+
* ```
|
|
6860
|
+
*/
|
|
6861
|
+
breakeven: (symbol: string, currentPrice: number, context: {
|
|
6862
|
+
strategyName: StrategyName;
|
|
6863
|
+
exchangeName: ExchangeName;
|
|
6864
|
+
frameName: FrameName;
|
|
6865
|
+
}) => Promise<boolean>;
|
|
6175
6866
|
/**
|
|
6176
6867
|
* Gets statistical data from all closed signals for a symbol-strategy pair.
|
|
6177
6868
|
*
|
|
@@ -6218,7 +6909,7 @@ declare class BacktestUtils {
|
|
|
6218
6909
|
strategyName: StrategyName;
|
|
6219
6910
|
exchangeName: ExchangeName;
|
|
6220
6911
|
frameName: FrameName;
|
|
6221
|
-
}, columns?: Columns$
|
|
6912
|
+
}, columns?: Columns$7[]) => Promise<string>;
|
|
6222
6913
|
/**
|
|
6223
6914
|
* Saves strategy report to disk.
|
|
6224
6915
|
*
|
|
@@ -6249,7 +6940,7 @@ declare class BacktestUtils {
|
|
|
6249
6940
|
strategyName: StrategyName;
|
|
6250
6941
|
exchangeName: ExchangeName;
|
|
6251
6942
|
frameName: FrameName;
|
|
6252
|
-
}, path?: string, columns?: Columns$
|
|
6943
|
+
}, path?: string, columns?: Columns$7[]) => Promise<void>;
|
|
6253
6944
|
/**
|
|
6254
6945
|
* Lists all active backtest instances with their current status.
|
|
6255
6946
|
*
|
|
@@ -6323,7 +7014,7 @@ declare const Backtest: BacktestUtils;
|
|
|
6323
7014
|
* @see ColumnModel for the base interface
|
|
6324
7015
|
* @see TickEvent for the event data structure
|
|
6325
7016
|
*/
|
|
6326
|
-
type Columns$
|
|
7017
|
+
type Columns$6 = ColumnModel<TickEvent>;
|
|
6327
7018
|
/**
|
|
6328
7019
|
* Service for generating and saving live trading markdown reports.
|
|
6329
7020
|
*
|
|
@@ -6422,7 +7113,7 @@ declare class LiveMarkdownService {
|
|
|
6422
7113
|
* console.log(markdown);
|
|
6423
7114
|
* ```
|
|
6424
7115
|
*/
|
|
6425
|
-
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$
|
|
7116
|
+
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$6[]) => Promise<string>;
|
|
6426
7117
|
/**
|
|
6427
7118
|
* Saves symbol-strategy report to disk.
|
|
6428
7119
|
* Creates directory if it doesn't exist.
|
|
@@ -6447,7 +7138,7 @@ declare class LiveMarkdownService {
|
|
|
6447
7138
|
* await service.dump("BTCUSDT", "my-strategy", "binance", "1h", false, "./custom/path");
|
|
6448
7139
|
* ```
|
|
6449
7140
|
*/
|
|
6450
|
-
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$
|
|
7141
|
+
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$6[]) => Promise<void>;
|
|
6451
7142
|
/**
|
|
6452
7143
|
* Clears accumulated event data from storage.
|
|
6453
7144
|
* If payload is provided, clears only that specific symbol-strategy-exchange-frame-backtest combination's data.
|
|
@@ -6485,6 +7176,11 @@ declare class LiveMarkdownService {
|
|
|
6485
7176
|
* ```
|
|
6486
7177
|
*/
|
|
6487
7178
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
7179
|
+
/**
|
|
7180
|
+
* Function to unsubscribe from backtest signal events.
|
|
7181
|
+
* Assigned during init().
|
|
7182
|
+
*/
|
|
7183
|
+
unsubscribe: Function;
|
|
6488
7184
|
}
|
|
6489
7185
|
|
|
6490
7186
|
/**
|
|
@@ -6707,6 +7403,56 @@ declare class LiveUtils {
|
|
|
6707
7403
|
strategyName: StrategyName;
|
|
6708
7404
|
exchangeName: ExchangeName;
|
|
6709
7405
|
}) => Promise<void>;
|
|
7406
|
+
/**
|
|
7407
|
+
* Adjusts the trailing stop-loss distance for an active pending signal.
|
|
7408
|
+
*
|
|
7409
|
+
* Updates the stop-loss distance by a percentage adjustment relative to the original SL distance.
|
|
7410
|
+
* Positive percentShift tightens the SL (reduces distance), negative percentShift loosens it.
|
|
7411
|
+
*
|
|
7412
|
+
* @param symbol - Trading pair symbol
|
|
7413
|
+
* @param percentShift - Percentage adjustment to SL distance (-100 to 100)
|
|
7414
|
+
* @param context - Execution context with strategyName and exchangeName
|
|
7415
|
+
* @returns Promise that resolves when trailing SL is updated
|
|
7416
|
+
*
|
|
7417
|
+
* @example
|
|
7418
|
+
* ```typescript
|
|
7419
|
+
* // LONG: entry=100, originalSL=90, distance=10
|
|
7420
|
+
* // Tighten stop by 50%: newSL = 100 - 10*(1-0.5) = 95
|
|
7421
|
+
* await Live.trailingStop("BTCUSDT", -50, {
|
|
7422
|
+
* exchangeName: "binance",
|
|
7423
|
+
* strategyName: "my-strategy"
|
|
7424
|
+
* });
|
|
7425
|
+
* ```
|
|
7426
|
+
*/
|
|
7427
|
+
trailingStop: (symbol: string, percentShift: number, context: {
|
|
7428
|
+
strategyName: StrategyName;
|
|
7429
|
+
exchangeName: ExchangeName;
|
|
7430
|
+
}) => Promise<void>;
|
|
7431
|
+
/**
|
|
7432
|
+
* Moves stop-loss to breakeven when price reaches threshold.
|
|
7433
|
+
*
|
|
7434
|
+
* Moves SL to entry price (zero-risk position) when current price has moved
|
|
7435
|
+
* far enough in profit direction. Threshold is calculated as: (CC_PERCENT_SLIPPAGE + CC_PERCENT_FEE) * 2
|
|
7436
|
+
*
|
|
7437
|
+
* @param symbol - Trading pair symbol
|
|
7438
|
+
* @param currentPrice - Current market price to check threshold
|
|
7439
|
+
* @param context - Strategy context with strategyName and exchangeName
|
|
7440
|
+
* @returns Promise<boolean> - true if breakeven was set, false otherwise
|
|
7441
|
+
*
|
|
7442
|
+
* @example
|
|
7443
|
+
* ```typescript
|
|
7444
|
+
* const moved = await Live.breakeven(
|
|
7445
|
+
* "BTCUSDT",
|
|
7446
|
+
* 112,
|
|
7447
|
+
* { strategyName: "my-strategy", exchangeName: "binance" }
|
|
7448
|
+
* );
|
|
7449
|
+
* console.log(moved); // true (SL moved to entry price)
|
|
7450
|
+
* ```
|
|
7451
|
+
*/
|
|
7452
|
+
breakeven: (symbol: string, currentPrice: number, context: {
|
|
7453
|
+
strategyName: StrategyName;
|
|
7454
|
+
exchangeName: ExchangeName;
|
|
7455
|
+
}) => Promise<boolean>;
|
|
6710
7456
|
/**
|
|
6711
7457
|
* Gets statistical data from all live trading events for a symbol-strategy pair.
|
|
6712
7458
|
*
|
|
@@ -6751,7 +7497,7 @@ declare class LiveUtils {
|
|
|
6751
7497
|
getReport: (symbol: string, context: {
|
|
6752
7498
|
strategyName: StrategyName;
|
|
6753
7499
|
exchangeName: ExchangeName;
|
|
6754
|
-
}, columns?: Columns$
|
|
7500
|
+
}, columns?: Columns$6[]) => Promise<string>;
|
|
6755
7501
|
/**
|
|
6756
7502
|
* Saves strategy report to disk.
|
|
6757
7503
|
*
|
|
@@ -6781,7 +7527,7 @@ declare class LiveUtils {
|
|
|
6781
7527
|
dump: (symbol: string, context: {
|
|
6782
7528
|
strategyName: StrategyName;
|
|
6783
7529
|
exchangeName: ExchangeName;
|
|
6784
|
-
}, path?: string, columns?: Columns$
|
|
7530
|
+
}, path?: string, columns?: Columns$6[]) => Promise<void>;
|
|
6785
7531
|
/**
|
|
6786
7532
|
* Lists all active live trading instances with their current status.
|
|
6787
7533
|
*
|
|
@@ -6851,7 +7597,7 @@ declare const Live: LiveUtils;
|
|
|
6851
7597
|
* @see ColumnModel for the base interface
|
|
6852
7598
|
* @see ScheduledEvent for the event data structure
|
|
6853
7599
|
*/
|
|
6854
|
-
type Columns$
|
|
7600
|
+
type Columns$5 = ColumnModel<ScheduledEvent>;
|
|
6855
7601
|
/**
|
|
6856
7602
|
* Service for generating and saving scheduled signals markdown reports.
|
|
6857
7603
|
*
|
|
@@ -6934,7 +7680,7 @@ declare class ScheduleMarkdownService {
|
|
|
6934
7680
|
* console.log(markdown);
|
|
6935
7681
|
* ```
|
|
6936
7682
|
*/
|
|
6937
|
-
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$
|
|
7683
|
+
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$5[]) => Promise<string>;
|
|
6938
7684
|
/**
|
|
6939
7685
|
* Saves symbol-strategy report to disk.
|
|
6940
7686
|
* Creates directory if it doesn't exist.
|
|
@@ -6959,7 +7705,7 @@ declare class ScheduleMarkdownService {
|
|
|
6959
7705
|
* await service.dump("BTCUSDT", "my-strategy", "binance", "1h", false, "./custom/path");
|
|
6960
7706
|
* ```
|
|
6961
7707
|
*/
|
|
6962
|
-
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$
|
|
7708
|
+
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$5[]) => Promise<void>;
|
|
6963
7709
|
/**
|
|
6964
7710
|
* Clears accumulated event data from storage.
|
|
6965
7711
|
* If payload is provided, clears only that specific symbol-strategy-exchange-frame-backtest combination's data.
|
|
@@ -6997,6 +7743,11 @@ declare class ScheduleMarkdownService {
|
|
|
6997
7743
|
* ```
|
|
6998
7744
|
*/
|
|
6999
7745
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
7746
|
+
/**
|
|
7747
|
+
* Function to unsubscribe from partial profit/loss events.
|
|
7748
|
+
* Assigned during init().
|
|
7749
|
+
*/
|
|
7750
|
+
unsubscribe: Function;
|
|
7000
7751
|
}
|
|
7001
7752
|
|
|
7002
7753
|
/**
|
|
@@ -7061,7 +7812,7 @@ declare class ScheduleUtils {
|
|
|
7061
7812
|
strategyName: StrategyName;
|
|
7062
7813
|
exchangeName: ExchangeName;
|
|
7063
7814
|
frameName: FrameName;
|
|
7064
|
-
}, backtest?: boolean, columns?: Columns$
|
|
7815
|
+
}, backtest?: boolean, columns?: Columns$5[]) => Promise<string>;
|
|
7065
7816
|
/**
|
|
7066
7817
|
* Saves strategy report to disk.
|
|
7067
7818
|
*
|
|
@@ -7083,7 +7834,7 @@ declare class ScheduleUtils {
|
|
|
7083
7834
|
strategyName: StrategyName;
|
|
7084
7835
|
exchangeName: ExchangeName;
|
|
7085
7836
|
frameName: FrameName;
|
|
7086
|
-
}, backtest?: boolean, path?: string, columns?: Columns$
|
|
7837
|
+
}, backtest?: boolean, path?: string, columns?: Columns$5[]) => Promise<void>;
|
|
7087
7838
|
}
|
|
7088
7839
|
/**
|
|
7089
7840
|
* Singleton instance of ScheduleUtils for convenient scheduled signals reporting.
|
|
@@ -7129,7 +7880,7 @@ declare const Schedule: ScheduleUtils;
|
|
|
7129
7880
|
* @see ColumnModel for the base interface
|
|
7130
7881
|
* @see MetricStats for the metric data structure
|
|
7131
7882
|
*/
|
|
7132
|
-
type Columns$
|
|
7883
|
+
type Columns$4 = ColumnModel<MetricStats>;
|
|
7133
7884
|
/**
|
|
7134
7885
|
* Service for collecting and analyzing performance metrics.
|
|
7135
7886
|
*
|
|
@@ -7208,7 +7959,7 @@ declare class PerformanceMarkdownService {
|
|
|
7208
7959
|
* console.log(markdown);
|
|
7209
7960
|
* ```
|
|
7210
7961
|
*/
|
|
7211
|
-
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$
|
|
7962
|
+
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$4[]) => Promise<string>;
|
|
7212
7963
|
/**
|
|
7213
7964
|
* Saves performance report to disk.
|
|
7214
7965
|
*
|
|
@@ -7229,7 +7980,7 @@ declare class PerformanceMarkdownService {
|
|
|
7229
7980
|
* await performanceService.dump("BTCUSDT", "my-strategy", "binance", "1h", false, "./custom/path");
|
|
7230
7981
|
* ```
|
|
7231
7982
|
*/
|
|
7232
|
-
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$
|
|
7983
|
+
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$4[]) => Promise<void>;
|
|
7233
7984
|
/**
|
|
7234
7985
|
* Clears accumulated performance data from storage.
|
|
7235
7986
|
*
|
|
@@ -7247,6 +7998,11 @@ declare class PerformanceMarkdownService {
|
|
|
7247
7998
|
* Uses singleshot to ensure initialization happens only once.
|
|
7248
7999
|
*/
|
|
7249
8000
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
8001
|
+
/**
|
|
8002
|
+
* Function to unsubscribe from partial profit/loss events.
|
|
8003
|
+
* Assigned during init().
|
|
8004
|
+
*/
|
|
8005
|
+
unsubscribe: Function;
|
|
7250
8006
|
}
|
|
7251
8007
|
|
|
7252
8008
|
/**
|
|
@@ -7342,7 +8098,7 @@ declare class Performance {
|
|
|
7342
8098
|
strategyName: StrategyName;
|
|
7343
8099
|
exchangeName: ExchangeName;
|
|
7344
8100
|
frameName: FrameName;
|
|
7345
|
-
}, backtest?: boolean, columns?: Columns$
|
|
8101
|
+
}, backtest?: boolean, columns?: Columns$4[]): Promise<string>;
|
|
7346
8102
|
/**
|
|
7347
8103
|
* Saves performance report to disk.
|
|
7348
8104
|
*
|
|
@@ -7367,7 +8123,7 @@ declare class Performance {
|
|
|
7367
8123
|
strategyName: StrategyName;
|
|
7368
8124
|
exchangeName: ExchangeName;
|
|
7369
8125
|
frameName: FrameName;
|
|
7370
|
-
}, backtest?: boolean, path?: string, columns?: Columns$
|
|
8126
|
+
}, backtest?: boolean, path?: string, columns?: Columns$4[]): Promise<void>;
|
|
7371
8127
|
}
|
|
7372
8128
|
|
|
7373
8129
|
/**
|
|
@@ -7574,6 +8330,11 @@ declare class WalkerMarkdownService {
|
|
|
7574
8330
|
* ```
|
|
7575
8331
|
*/
|
|
7576
8332
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
8333
|
+
/**
|
|
8334
|
+
* Function to unsubscribe from partial profit/loss events.
|
|
8335
|
+
* Assigned during init().
|
|
8336
|
+
*/
|
|
8337
|
+
unsubscribe: Function;
|
|
7577
8338
|
}
|
|
7578
8339
|
|
|
7579
8340
|
/**
|
|
@@ -7782,7 +8543,7 @@ declare const Walker: WalkerUtils;
|
|
|
7782
8543
|
* @see ColumnModel for the base interface
|
|
7783
8544
|
* @see IHeatmapRow for the row data structure
|
|
7784
8545
|
*/
|
|
7785
|
-
type Columns$
|
|
8546
|
+
type Columns$3 = ColumnModel<IHeatmapRow>;
|
|
7786
8547
|
/**
|
|
7787
8548
|
* Portfolio Heatmap Markdown Service.
|
|
7788
8549
|
*
|
|
@@ -7875,7 +8636,7 @@ declare class HeatMarkdownService {
|
|
|
7875
8636
|
* // ...
|
|
7876
8637
|
* ```
|
|
7877
8638
|
*/
|
|
7878
|
-
getReport: (strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$
|
|
8639
|
+
getReport: (strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$3[]) => Promise<string>;
|
|
7879
8640
|
/**
|
|
7880
8641
|
* Saves heatmap report to disk.
|
|
7881
8642
|
*
|
|
@@ -7900,7 +8661,7 @@ declare class HeatMarkdownService {
|
|
|
7900
8661
|
* await service.dump("my-strategy", "binance", "frame1", true, "./reports");
|
|
7901
8662
|
* ```
|
|
7902
8663
|
*/
|
|
7903
|
-
dump: (strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$
|
|
8664
|
+
dump: (strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$3[]) => Promise<void>;
|
|
7904
8665
|
/**
|
|
7905
8666
|
* Clears accumulated heatmap data from storage.
|
|
7906
8667
|
* If payload is provided, clears only that exchangeName+frameName+backtest combination's data.
|
|
@@ -7936,6 +8697,11 @@ declare class HeatMarkdownService {
|
|
|
7936
8697
|
* ```
|
|
7937
8698
|
*/
|
|
7938
8699
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
8700
|
+
/**
|
|
8701
|
+
* Function to unsubscribe from backtest signal events.
|
|
8702
|
+
* Assigned during init().
|
|
8703
|
+
*/
|
|
8704
|
+
unsubscribe: Function;
|
|
7939
8705
|
}
|
|
7940
8706
|
|
|
7941
8707
|
/**
|
|
@@ -8042,7 +8808,7 @@ declare class HeatUtils {
|
|
|
8042
8808
|
strategyName: StrategyName;
|
|
8043
8809
|
exchangeName: ExchangeName;
|
|
8044
8810
|
frameName: FrameName;
|
|
8045
|
-
}, backtest?: boolean, columns?: Columns$
|
|
8811
|
+
}, backtest?: boolean, columns?: Columns$3[]) => Promise<string>;
|
|
8046
8812
|
/**
|
|
8047
8813
|
* Saves heatmap report to disk for a strategy.
|
|
8048
8814
|
*
|
|
@@ -8075,7 +8841,7 @@ declare class HeatUtils {
|
|
|
8075
8841
|
strategyName: StrategyName;
|
|
8076
8842
|
exchangeName: ExchangeName;
|
|
8077
8843
|
frameName: FrameName;
|
|
8078
|
-
}, backtest?: boolean, path?: string, columns?: Columns$
|
|
8844
|
+
}, backtest?: boolean, path?: string, columns?: Columns$3[]) => Promise<void>;
|
|
8079
8845
|
}
|
|
8080
8846
|
/**
|
|
8081
8847
|
* Singleton instance of HeatUtils for convenient heatmap operations.
|
|
@@ -8306,7 +9072,7 @@ declare const Optimizer: OptimizerUtils;
|
|
|
8306
9072
|
* @see ColumnModel for the base interface
|
|
8307
9073
|
* @see PartialEvent for the event data structure
|
|
8308
9074
|
*/
|
|
8309
|
-
type Columns$
|
|
9075
|
+
type Columns$2 = ColumnModel<PartialEvent>;
|
|
8310
9076
|
/**
|
|
8311
9077
|
* Service for generating and saving partial profit/loss markdown reports.
|
|
8312
9078
|
*
|
|
@@ -8400,7 +9166,7 @@ declare class PartialMarkdownService {
|
|
|
8400
9166
|
* console.log(markdown);
|
|
8401
9167
|
* ```
|
|
8402
9168
|
*/
|
|
8403
|
-
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$
|
|
9169
|
+
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$2[]) => Promise<string>;
|
|
8404
9170
|
/**
|
|
8405
9171
|
* Saves symbol-strategy report to disk.
|
|
8406
9172
|
* Creates directory if it doesn't exist.
|
|
@@ -8425,7 +9191,7 @@ declare class PartialMarkdownService {
|
|
|
8425
9191
|
* await service.dump("BTCUSDT", "my-strategy", "binance", "1h", false, "./custom/path");
|
|
8426
9192
|
* ```
|
|
8427
9193
|
*/
|
|
8428
|
-
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$
|
|
9194
|
+
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$2[]) => Promise<void>;
|
|
8429
9195
|
/**
|
|
8430
9196
|
* Clears accumulated event data from storage.
|
|
8431
9197
|
* If payload is provided, clears only that specific symbol-strategy-exchange-frame-backtest combination's data.
|
|
@@ -8463,6 +9229,11 @@ declare class PartialMarkdownService {
|
|
|
8463
9229
|
* ```
|
|
8464
9230
|
*/
|
|
8465
9231
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
9232
|
+
/**
|
|
9233
|
+
* Function to unsubscribe from partial profit/loss events.
|
|
9234
|
+
* Assigned during init().
|
|
9235
|
+
*/
|
|
9236
|
+
unsubscribe: Function;
|
|
8466
9237
|
}
|
|
8467
9238
|
|
|
8468
9239
|
/**
|
|
@@ -8573,7 +9344,7 @@ declare class PartialUtils {
|
|
|
8573
9344
|
strategyName: StrategyName;
|
|
8574
9345
|
exchangeName: ExchangeName;
|
|
8575
9346
|
frameName: FrameName;
|
|
8576
|
-
}, backtest?: boolean, columns?: Columns$
|
|
9347
|
+
}, backtest?: boolean, columns?: Columns$2[]) => Promise<string>;
|
|
8577
9348
|
/**
|
|
8578
9349
|
* Generates and saves markdown report to file.
|
|
8579
9350
|
*
|
|
@@ -8610,7 +9381,7 @@ declare class PartialUtils {
|
|
|
8610
9381
|
strategyName: StrategyName;
|
|
8611
9382
|
exchangeName: ExchangeName;
|
|
8612
9383
|
frameName: FrameName;
|
|
8613
|
-
}, backtest?: boolean, path?: string, columns?: Columns$
|
|
9384
|
+
}, backtest?: boolean, path?: string, columns?: Columns$2[]) => Promise<void>;
|
|
8614
9385
|
}
|
|
8615
9386
|
/**
|
|
8616
9387
|
* Global singleton instance of PartialUtils.
|
|
@@ -8738,7 +9509,7 @@ declare const Constant: ConstantUtils;
|
|
|
8738
9509
|
* @see ColumnModel for the base interface
|
|
8739
9510
|
* @see RiskEvent for the event data structure
|
|
8740
9511
|
*/
|
|
8741
|
-
type Columns = ColumnModel<RiskEvent>;
|
|
9512
|
+
type Columns$1 = ColumnModel<RiskEvent>;
|
|
8742
9513
|
/**
|
|
8743
9514
|
* Service for generating and saving risk rejection markdown reports.
|
|
8744
9515
|
*
|
|
@@ -8819,7 +9590,7 @@ declare class RiskMarkdownService {
|
|
|
8819
9590
|
* console.log(markdown);
|
|
8820
9591
|
* ```
|
|
8821
9592
|
*/
|
|
8822
|
-
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns[]) => Promise<string>;
|
|
9593
|
+
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns$1[]) => Promise<string>;
|
|
8823
9594
|
/**
|
|
8824
9595
|
* Saves symbol-strategy report to disk.
|
|
8825
9596
|
* Creates directory if it doesn't exist.
|
|
@@ -8844,7 +9615,7 @@ declare class RiskMarkdownService {
|
|
|
8844
9615
|
* await service.dump("BTCUSDT", "my-strategy", "binance", "1h", false, "./custom/path");
|
|
8845
9616
|
* ```
|
|
8846
9617
|
*/
|
|
8847
|
-
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns[]) => Promise<void>;
|
|
9618
|
+
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns$1[]) => Promise<void>;
|
|
8848
9619
|
/**
|
|
8849
9620
|
* Clears accumulated event data from storage.
|
|
8850
9621
|
* If payload is provided, clears only that specific symbol-strategy-exchange-frame-backtest combination's data.
|
|
@@ -8882,6 +9653,11 @@ declare class RiskMarkdownService {
|
|
|
8882
9653
|
* ```
|
|
8883
9654
|
*/
|
|
8884
9655
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
9656
|
+
/**
|
|
9657
|
+
* Function to unsubscribe from partial profit/loss events.
|
|
9658
|
+
* Assigned during init().
|
|
9659
|
+
*/
|
|
9660
|
+
unsubscribe: Function;
|
|
8885
9661
|
}
|
|
8886
9662
|
|
|
8887
9663
|
/**
|
|
@@ -8994,7 +9770,7 @@ declare class RiskUtils {
|
|
|
8994
9770
|
strategyName: StrategyName;
|
|
8995
9771
|
exchangeName: ExchangeName;
|
|
8996
9772
|
frameName: FrameName;
|
|
8997
|
-
}, backtest?: boolean, columns?: Columns[]) => Promise<string>;
|
|
9773
|
+
}, backtest?: boolean, columns?: Columns$1[]) => Promise<string>;
|
|
8998
9774
|
/**
|
|
8999
9775
|
* Generates and saves markdown report to file.
|
|
9000
9776
|
*
|
|
@@ -9031,7 +9807,7 @@ declare class RiskUtils {
|
|
|
9031
9807
|
strategyName: StrategyName;
|
|
9032
9808
|
exchangeName: ExchangeName;
|
|
9033
9809
|
frameName: FrameName;
|
|
9034
|
-
}, backtest?: boolean, path?: string, columns?: Columns[]) => Promise<void>;
|
|
9810
|
+
}, backtest?: boolean, path?: string, columns?: Columns$1[]) => Promise<void>;
|
|
9035
9811
|
}
|
|
9036
9812
|
/**
|
|
9037
9813
|
* Global singleton instance of RiskUtils.
|
|
@@ -9157,7 +9933,7 @@ declare const Exchange: ExchangeUtils;
|
|
|
9157
9933
|
* Generic function type that accepts any arguments and returns any value.
|
|
9158
9934
|
* Used as a constraint for cached functions.
|
|
9159
9935
|
*/
|
|
9160
|
-
type Function = (...args: any[]) => any;
|
|
9936
|
+
type Function$1 = (...args: any[]) => any;
|
|
9161
9937
|
/**
|
|
9162
9938
|
* Utility class for function caching with timeframe-based invalidation.
|
|
9163
9939
|
*
|
|
@@ -9202,7 +9978,7 @@ declare class CacheUtils {
|
|
|
9202
9978
|
* const result2 = cachedCalculate("BTCUSDT", 14); // Cached (same 15m interval)
|
|
9203
9979
|
* ```
|
|
9204
9980
|
*/
|
|
9205
|
-
fn: <T extends Function>(run: T, context: {
|
|
9981
|
+
fn: <T extends Function$1>(run: T, context: {
|
|
9206
9982
|
interval: CandleInterval;
|
|
9207
9983
|
}) => T;
|
|
9208
9984
|
/**
|
|
@@ -9234,7 +10010,7 @@ declare class CacheUtils {
|
|
|
9234
10010
|
* Cache.flush();
|
|
9235
10011
|
* ```
|
|
9236
10012
|
*/
|
|
9237
|
-
flush: <T extends Function>(run?: T) => void;
|
|
10013
|
+
flush: <T extends Function$1>(run?: T) => void;
|
|
9238
10014
|
/**
|
|
9239
10015
|
* Clear cached value for current execution context of a specific function.
|
|
9240
10016
|
*
|
|
@@ -9264,7 +10040,7 @@ declare class CacheUtils {
|
|
|
9264
10040
|
* // Other contexts (different strategies/exchanges) remain cached
|
|
9265
10041
|
* ```
|
|
9266
10042
|
*/
|
|
9267
|
-
clear: <T extends Function>(run: T) => void;
|
|
10043
|
+
clear: <T extends Function$1>(run: T) => void;
|
|
9268
10044
|
}
|
|
9269
10045
|
/**
|
|
9270
10046
|
* Singleton instance of CacheUtils for convenient function caching.
|
|
@@ -9342,38 +10118,375 @@ declare class NotificationUtils {
|
|
|
9342
10118
|
* });
|
|
9343
10119
|
* ```
|
|
9344
10120
|
*/
|
|
9345
|
-
getData(): Promise<NotificationModel[]>;
|
|
10121
|
+
getData(): Promise<NotificationModel[]>;
|
|
10122
|
+
/**
|
|
10123
|
+
* Clears all notification history.
|
|
10124
|
+
*
|
|
10125
|
+
* @example
|
|
10126
|
+
* ```typescript
|
|
10127
|
+
* await Notification.clear();
|
|
10128
|
+
* ```
|
|
10129
|
+
*/
|
|
10130
|
+
clear(): Promise<void>;
|
|
10131
|
+
}
|
|
10132
|
+
/**
|
|
10133
|
+
* Singleton instance of NotificationUtils for convenient notification access.
|
|
10134
|
+
*
|
|
10135
|
+
* @example
|
|
10136
|
+
* ```typescript
|
|
10137
|
+
* import { Notification } from "./classes/Notification";
|
|
10138
|
+
*
|
|
10139
|
+
* // Get all notifications
|
|
10140
|
+
* const all = await Notification.getData();
|
|
10141
|
+
*
|
|
10142
|
+
* // Filter by type using type discrimination
|
|
10143
|
+
* const closedSignals = all.filter(n => n.type === "signal.closed");
|
|
10144
|
+
* const highLosses = all.filter(n =>
|
|
10145
|
+
* n.type === "partial.loss" && n.level >= 30
|
|
10146
|
+
* );
|
|
10147
|
+
*
|
|
10148
|
+
* // Clear history
|
|
10149
|
+
* await Notification.clear();
|
|
10150
|
+
* ```
|
|
10151
|
+
*/
|
|
10152
|
+
declare const Notification: NotificationUtils;
|
|
10153
|
+
|
|
10154
|
+
/**
|
|
10155
|
+
* Type alias for column configuration used in breakeven markdown reports.
|
|
10156
|
+
*
|
|
10157
|
+
* Represents a column model specifically designed to format and display
|
|
10158
|
+
* breakeven events in markdown tables.
|
|
10159
|
+
*
|
|
10160
|
+
* @typeParam BreakevenEvent - The breakeven event data type containing
|
|
10161
|
+
* signal information, symbol, and timing details
|
|
10162
|
+
*
|
|
10163
|
+
* @example
|
|
10164
|
+
* ```typescript
|
|
10165
|
+
* // Column to display symbol
|
|
10166
|
+
* const symbolColumn: Columns = {
|
|
10167
|
+
* key: "symbol",
|
|
10168
|
+
* label: "Symbol",
|
|
10169
|
+
* format: (event) => event.symbol,
|
|
10170
|
+
* isVisible: () => true
|
|
10171
|
+
* };
|
|
10172
|
+
*
|
|
10173
|
+
* // Column to display price when breakeven was reached
|
|
10174
|
+
* const priceColumn: Columns = {
|
|
10175
|
+
* key: "currentPrice",
|
|
10176
|
+
* label: "Price",
|
|
10177
|
+
* format: (event) => event.currentPrice.toString(),
|
|
10178
|
+
* isVisible: () => true
|
|
10179
|
+
* };
|
|
10180
|
+
* ```
|
|
10181
|
+
*
|
|
10182
|
+
* @see ColumnModel for the base interface
|
|
10183
|
+
* @see BreakevenEvent for the event data structure
|
|
10184
|
+
*/
|
|
10185
|
+
type Columns = ColumnModel<BreakevenEvent>;
|
|
10186
|
+
/**
|
|
10187
|
+
* Service for generating and saving breakeven markdown reports.
|
|
10188
|
+
*
|
|
10189
|
+
* Features:
|
|
10190
|
+
* - Listens to breakeven events via breakevenSubject
|
|
10191
|
+
* - Accumulates all events per symbol-strategy pair
|
|
10192
|
+
* - Generates markdown tables with detailed event information
|
|
10193
|
+
* - Provides statistics (total breakeven events)
|
|
10194
|
+
* - Saves reports to disk in dump/breakeven/{symbol}_{strategyName}.md
|
|
10195
|
+
*
|
|
10196
|
+
* @example
|
|
10197
|
+
* ```typescript
|
|
10198
|
+
* const service = new BreakevenMarkdownService();
|
|
10199
|
+
*
|
|
10200
|
+
* // Service automatically subscribes to subjects on init
|
|
10201
|
+
* // No manual callback setup needed
|
|
10202
|
+
*
|
|
10203
|
+
* // Later: generate and save report
|
|
10204
|
+
* await service.dump("BTCUSDT", "my-strategy");
|
|
10205
|
+
* ```
|
|
10206
|
+
*/
|
|
10207
|
+
declare class BreakevenMarkdownService {
|
|
10208
|
+
/** Logger service for debug output */
|
|
10209
|
+
private readonly loggerService;
|
|
10210
|
+
/**
|
|
10211
|
+
* Memoized function to get or create ReportStorage for a symbol-strategy-exchange-frame-backtest combination.
|
|
10212
|
+
* Each combination gets its own isolated storage instance.
|
|
10213
|
+
*/
|
|
10214
|
+
private getStorage;
|
|
10215
|
+
/**
|
|
10216
|
+
* Processes breakeven events and accumulates them.
|
|
10217
|
+
* Should be called from breakevenSubject subscription.
|
|
10218
|
+
*
|
|
10219
|
+
* @param data - Breakeven event data with frameName wrapper
|
|
10220
|
+
*
|
|
10221
|
+
* @example
|
|
10222
|
+
* ```typescript
|
|
10223
|
+
* const service = new BreakevenMarkdownService();
|
|
10224
|
+
* // Service automatically subscribes in init()
|
|
10225
|
+
* ```
|
|
10226
|
+
*/
|
|
10227
|
+
private tickBreakeven;
|
|
10228
|
+
/**
|
|
10229
|
+
* Gets statistical data from all breakeven events for a symbol-strategy pair.
|
|
10230
|
+
* Delegates to ReportStorage.getData().
|
|
10231
|
+
*
|
|
10232
|
+
* @param symbol - Trading pair symbol to get data for
|
|
10233
|
+
* @param strategyName - Strategy name to get data for
|
|
10234
|
+
* @param exchangeName - Exchange name
|
|
10235
|
+
* @param frameName - Frame name
|
|
10236
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
10237
|
+
* @returns Statistical data object with all metrics
|
|
10238
|
+
*
|
|
10239
|
+
* @example
|
|
10240
|
+
* ```typescript
|
|
10241
|
+
* const service = new BreakevenMarkdownService();
|
|
10242
|
+
* const stats = await service.getData("BTCUSDT", "my-strategy", "binance", "1h", false);
|
|
10243
|
+
* console.log(stats.totalEvents);
|
|
10244
|
+
* ```
|
|
10245
|
+
*/
|
|
10246
|
+
getData: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean) => Promise<BreakevenStatisticsModel>;
|
|
10247
|
+
/**
|
|
10248
|
+
* Generates markdown report with all breakeven events for a symbol-strategy pair.
|
|
10249
|
+
* Delegates to ReportStorage.getReport().
|
|
10250
|
+
*
|
|
10251
|
+
* @param symbol - Trading pair symbol to generate report for
|
|
10252
|
+
* @param strategyName - Strategy name to generate report for
|
|
10253
|
+
* @param exchangeName - Exchange name
|
|
10254
|
+
* @param frameName - Frame name
|
|
10255
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
10256
|
+
* @param columns - Column configuration for formatting the table
|
|
10257
|
+
* @returns Markdown formatted report string with table of all events
|
|
10258
|
+
*
|
|
10259
|
+
* @example
|
|
10260
|
+
* ```typescript
|
|
10261
|
+
* const service = new BreakevenMarkdownService();
|
|
10262
|
+
* const markdown = await service.getReport("BTCUSDT", "my-strategy", "binance", "1h", false);
|
|
10263
|
+
* console.log(markdown);
|
|
10264
|
+
* ```
|
|
10265
|
+
*/
|
|
10266
|
+
getReport: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, columns?: Columns[]) => Promise<string>;
|
|
10267
|
+
/**
|
|
10268
|
+
* Saves symbol-strategy report to disk.
|
|
10269
|
+
* Creates directory if it doesn't exist.
|
|
10270
|
+
* Delegates to ReportStorage.dump().
|
|
10271
|
+
*
|
|
10272
|
+
* @param symbol - Trading pair symbol to save report for
|
|
10273
|
+
* @param strategyName - Strategy name to save report for
|
|
10274
|
+
* @param exchangeName - Exchange name
|
|
10275
|
+
* @param frameName - Frame name
|
|
10276
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
10277
|
+
* @param path - Directory path to save report (default: "./dump/breakeven")
|
|
10278
|
+
* @param columns - Column configuration for formatting the table
|
|
10279
|
+
*
|
|
10280
|
+
* @example
|
|
10281
|
+
* ```typescript
|
|
10282
|
+
* const service = new BreakevenMarkdownService();
|
|
10283
|
+
*
|
|
10284
|
+
* // Save to default path: ./dump/breakeven/BTCUSDT_my-strategy.md
|
|
10285
|
+
* await service.dump("BTCUSDT", "my-strategy", "binance", "1h", false);
|
|
10286
|
+
*
|
|
10287
|
+
* // Save to custom path: ./custom/path/BTCUSDT_my-strategy.md
|
|
10288
|
+
* await service.dump("BTCUSDT", "my-strategy", "binance", "1h", false, "./custom/path");
|
|
10289
|
+
* ```
|
|
10290
|
+
*/
|
|
10291
|
+
dump: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean, path?: string, columns?: Columns[]) => Promise<void>;
|
|
10292
|
+
/**
|
|
10293
|
+
* Clears accumulated event data from storage.
|
|
10294
|
+
* If payload is provided, clears only that specific symbol-strategy-exchange-frame-backtest combination's data.
|
|
10295
|
+
* If nothing is provided, clears all data.
|
|
10296
|
+
*
|
|
10297
|
+
* @param payload - Optional payload with symbol, strategyName, exchangeName, frameName, backtest
|
|
10298
|
+
*
|
|
10299
|
+
* @example
|
|
10300
|
+
* ```typescript
|
|
10301
|
+
* const service = new BreakevenMarkdownService();
|
|
10302
|
+
*
|
|
10303
|
+
* // Clear specific combination
|
|
10304
|
+
* await service.clear({ symbol: "BTCUSDT", strategyName: "my-strategy", exchangeName: "binance", frameName: "1h", backtest: false });
|
|
10305
|
+
*
|
|
10306
|
+
* // Clear all data
|
|
10307
|
+
* await service.clear();
|
|
10308
|
+
* ```
|
|
10309
|
+
*/
|
|
10310
|
+
clear: (payload?: {
|
|
10311
|
+
symbol: string;
|
|
10312
|
+
strategyName: StrategyName;
|
|
10313
|
+
exchangeName: ExchangeName;
|
|
10314
|
+
frameName: FrameName;
|
|
10315
|
+
backtest: boolean;
|
|
10316
|
+
}) => Promise<void>;
|
|
10317
|
+
/**
|
|
10318
|
+
* Initializes the service by subscribing to breakeven events.
|
|
10319
|
+
* Uses singleshot to ensure initialization happens only once.
|
|
10320
|
+
* Automatically called on first use.
|
|
10321
|
+
*
|
|
10322
|
+
* @example
|
|
10323
|
+
* ```typescript
|
|
10324
|
+
* const service = new BreakevenMarkdownService();
|
|
10325
|
+
* await service.init(); // Subscribe to breakeven events
|
|
10326
|
+
* ```
|
|
10327
|
+
*/
|
|
10328
|
+
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
10329
|
+
/**
|
|
10330
|
+
* Function to unsubscribe from breakeven events.
|
|
10331
|
+
* Assigned during init().
|
|
10332
|
+
*/
|
|
10333
|
+
unsubscribe: Function;
|
|
10334
|
+
}
|
|
10335
|
+
|
|
10336
|
+
/**
|
|
10337
|
+
* Utility class for accessing breakeven protection reports and statistics.
|
|
10338
|
+
*
|
|
10339
|
+
* Provides static-like methods (via singleton instance) to retrieve data
|
|
10340
|
+
* accumulated by BreakevenMarkdownService from breakeven events.
|
|
10341
|
+
*
|
|
10342
|
+
* Features:
|
|
10343
|
+
* - Statistical data extraction (total breakeven events count)
|
|
10344
|
+
* - Markdown report generation with event tables
|
|
10345
|
+
* - File export to disk
|
|
10346
|
+
*
|
|
10347
|
+
* Data source:
|
|
10348
|
+
* - BreakevenMarkdownService listens to breakevenSubject
|
|
10349
|
+
* - Accumulates events in ReportStorage (max 250 events per symbol-strategy pair)
|
|
10350
|
+
* - Events include: timestamp, symbol, strategyName, signalId, position, priceOpen, currentPrice, mode
|
|
10351
|
+
*
|
|
10352
|
+
* @example
|
|
10353
|
+
* ```typescript
|
|
10354
|
+
* import { Breakeven } from "./classes/Breakeven";
|
|
10355
|
+
*
|
|
10356
|
+
* // Get statistical data for BTCUSDT:my-strategy
|
|
10357
|
+
* const stats = await Breakeven.getData("BTCUSDT", "my-strategy");
|
|
10358
|
+
* console.log(`Total breakeven events: ${stats.totalEvents}`);
|
|
10359
|
+
*
|
|
10360
|
+
* // Generate markdown report
|
|
10361
|
+
* const markdown = await Breakeven.getReport("BTCUSDT", "my-strategy");
|
|
10362
|
+
* console.log(markdown); // Formatted table with all events
|
|
10363
|
+
*
|
|
10364
|
+
* // Export report to file
|
|
10365
|
+
* await Breakeven.dump("BTCUSDT", "my-strategy"); // Saves to ./dump/breakeven/BTCUSDT_my-strategy.md
|
|
10366
|
+
* await Breakeven.dump("BTCUSDT", "my-strategy", "./custom/path"); // Custom directory
|
|
10367
|
+
* ```
|
|
10368
|
+
*/
|
|
10369
|
+
declare class BreakevenUtils {
|
|
10370
|
+
/**
|
|
10371
|
+
* Retrieves statistical data from accumulated breakeven events.
|
|
10372
|
+
*
|
|
10373
|
+
* Delegates to BreakevenMarkdownService.getData() which reads from ReportStorage.
|
|
10374
|
+
* Returns aggregated metrics calculated from all breakeven events.
|
|
10375
|
+
*
|
|
10376
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
10377
|
+
* @param strategyName - Strategy name (e.g., "my-strategy")
|
|
10378
|
+
* @returns Promise resolving to BreakevenStatisticsModel object with counts and event list
|
|
10379
|
+
*
|
|
10380
|
+
* @example
|
|
10381
|
+
* ```typescript
|
|
10382
|
+
* const stats = await Breakeven.getData("BTCUSDT", "my-strategy");
|
|
10383
|
+
*
|
|
10384
|
+
* console.log(`Total breakeven events: ${stats.totalEvents}`);
|
|
10385
|
+
*
|
|
10386
|
+
* // Iterate through all events
|
|
10387
|
+
* for (const event of stats.eventList) {
|
|
10388
|
+
* console.log(`Signal ${event.signalId} reached breakeven at ${event.currentPrice}`);
|
|
10389
|
+
* }
|
|
10390
|
+
* ```
|
|
10391
|
+
*/
|
|
10392
|
+
getData: (symbol: string, context: {
|
|
10393
|
+
strategyName: StrategyName;
|
|
10394
|
+
exchangeName: ExchangeName;
|
|
10395
|
+
frameName: FrameName;
|
|
10396
|
+
}, backtest?: boolean) => Promise<BreakevenStatisticsModel>;
|
|
10397
|
+
/**
|
|
10398
|
+
* Generates markdown report with all breakeven events for a symbol-strategy pair.
|
|
10399
|
+
*
|
|
10400
|
+
* Creates formatted table containing:
|
|
10401
|
+
* - Symbol
|
|
10402
|
+
* - Strategy
|
|
10403
|
+
* - Signal ID
|
|
10404
|
+
* - Position (LONG/SHORT)
|
|
10405
|
+
* - Entry Price
|
|
10406
|
+
* - Breakeven Price
|
|
10407
|
+
* - Timestamp (ISO 8601)
|
|
10408
|
+
* - Mode (Backtest/Live)
|
|
10409
|
+
*
|
|
10410
|
+
* Also includes summary statistics at the end.
|
|
10411
|
+
*
|
|
10412
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
10413
|
+
* @param strategyName - Strategy name (e.g., "my-strategy")
|
|
10414
|
+
* @param columns - Optional columns configuration for the report
|
|
10415
|
+
* @returns Promise resolving to markdown formatted report string
|
|
10416
|
+
*
|
|
10417
|
+
* @example
|
|
10418
|
+
* ```typescript
|
|
10419
|
+
* const markdown = await Breakeven.getReport("BTCUSDT", "my-strategy");
|
|
10420
|
+
* console.log(markdown);
|
|
10421
|
+
*
|
|
10422
|
+
* // Output:
|
|
10423
|
+
* // # Breakeven Protection Report: BTCUSDT:my-strategy
|
|
10424
|
+
* //
|
|
10425
|
+
* // | Symbol | Strategy | Signal ID | Position | Entry Price | Breakeven Price | Timestamp | Mode |
|
|
10426
|
+
* // | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
10427
|
+
* // | BTCUSDT | my-strategy | abc123 | LONG | 50000.00000000 USD | 50100.00000000 USD | 2024-01-15T10:30:00.000Z | Backtest |
|
|
10428
|
+
* //
|
|
10429
|
+
* // **Total events:** 1
|
|
10430
|
+
* ```
|
|
10431
|
+
*/
|
|
10432
|
+
getReport: (symbol: string, context: {
|
|
10433
|
+
strategyName: StrategyName;
|
|
10434
|
+
exchangeName: ExchangeName;
|
|
10435
|
+
frameName: FrameName;
|
|
10436
|
+
}, backtest?: boolean, columns?: Columns[]) => Promise<string>;
|
|
9346
10437
|
/**
|
|
9347
|
-
*
|
|
10438
|
+
* Generates and saves markdown report to file.
|
|
10439
|
+
*
|
|
10440
|
+
* Creates directory if it doesn't exist.
|
|
10441
|
+
* Filename format: {symbol}_{strategyName}.md (e.g., "BTCUSDT_my-strategy.md")
|
|
10442
|
+
*
|
|
10443
|
+
* Delegates to BreakevenMarkdownService.dump() which:
|
|
10444
|
+
* 1. Generates markdown report via getReport()
|
|
10445
|
+
* 2. Creates output directory (recursive mkdir)
|
|
10446
|
+
* 3. Writes file with UTF-8 encoding
|
|
10447
|
+
* 4. Logs success/failure to console
|
|
10448
|
+
*
|
|
10449
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
10450
|
+
* @param strategyName - Strategy name (e.g., "my-strategy")
|
|
10451
|
+
* @param path - Output directory path (default: "./dump/breakeven")
|
|
10452
|
+
* @param columns - Optional columns configuration for the report
|
|
10453
|
+
* @returns Promise that resolves when file is written
|
|
9348
10454
|
*
|
|
9349
10455
|
* @example
|
|
9350
10456
|
* ```typescript
|
|
9351
|
-
*
|
|
10457
|
+
* // Save to default path: ./dump/breakeven/BTCUSDT_my-strategy.md
|
|
10458
|
+
* await Breakeven.dump("BTCUSDT", "my-strategy");
|
|
10459
|
+
*
|
|
10460
|
+
* // Save to custom path: ./reports/breakeven/BTCUSDT_my-strategy.md
|
|
10461
|
+
* await Breakeven.dump("BTCUSDT", "my-strategy", "./reports/breakeven");
|
|
10462
|
+
*
|
|
10463
|
+
* // After multiple symbols backtested, export all reports
|
|
10464
|
+
* for (const symbol of ["BTCUSDT", "ETHUSDT", "BNBUSDT"]) {
|
|
10465
|
+
* await Breakeven.dump(symbol, "my-strategy", "./backtest-results");
|
|
10466
|
+
* }
|
|
9352
10467
|
* ```
|
|
9353
10468
|
*/
|
|
9354
|
-
|
|
10469
|
+
dump: (symbol: string, context: {
|
|
10470
|
+
strategyName: StrategyName;
|
|
10471
|
+
exchangeName: ExchangeName;
|
|
10472
|
+
frameName: FrameName;
|
|
10473
|
+
}, backtest?: boolean, path?: string, columns?: Columns[]) => Promise<void>;
|
|
9355
10474
|
}
|
|
9356
10475
|
/**
|
|
9357
|
-
*
|
|
10476
|
+
* Global singleton instance of BreakevenUtils.
|
|
10477
|
+
* Provides static-like access to breakeven protection reporting methods.
|
|
9358
10478
|
*
|
|
9359
10479
|
* @example
|
|
9360
10480
|
* ```typescript
|
|
9361
|
-
* import {
|
|
9362
|
-
*
|
|
9363
|
-
* // Get all notifications
|
|
9364
|
-
* const all = await Notification.getData();
|
|
10481
|
+
* import { Breakeven } from "backtest-kit";
|
|
9365
10482
|
*
|
|
9366
|
-
* //
|
|
9367
|
-
* const
|
|
9368
|
-
* const
|
|
9369
|
-
*
|
|
9370
|
-
* );
|
|
9371
|
-
*
|
|
9372
|
-
* // Clear history
|
|
9373
|
-
* await Notification.clear();
|
|
10483
|
+
* // Usage same as BreakevenUtils methods
|
|
10484
|
+
* const stats = await Breakeven.getData("BTCUSDT", "my-strategy");
|
|
10485
|
+
* const report = await Breakeven.getReport("BTCUSDT", "my-strategy");
|
|
10486
|
+
* await Breakeven.dump("BTCUSDT", "my-strategy");
|
|
9374
10487
|
* ```
|
|
9375
10488
|
*/
|
|
9376
|
-
declare const
|
|
10489
|
+
declare const Breakeven: BreakevenUtils;
|
|
9377
10490
|
|
|
9378
10491
|
/**
|
|
9379
10492
|
* Contract for walker stop signal events.
|
|
@@ -9498,6 +10611,11 @@ declare const partialProfitSubject: Subject<PartialProfitContract>;
|
|
|
9498
10611
|
* Emits when a signal reaches a loss level (10%, 20%, 30%, etc).
|
|
9499
10612
|
*/
|
|
9500
10613
|
declare const partialLossSubject: Subject<PartialLossContract>;
|
|
10614
|
+
/**
|
|
10615
|
+
* Breakeven emitter for stop-loss protection milestones.
|
|
10616
|
+
* Emits when a signal's stop-loss is moved to breakeven (entry price).
|
|
10617
|
+
*/
|
|
10618
|
+
declare const breakevenSubject: Subject<BreakevenContract>;
|
|
9501
10619
|
/**
|
|
9502
10620
|
* Risk rejection emitter for risk management violations.
|
|
9503
10621
|
* Emits ONLY when a signal is rejected due to risk validation failure.
|
|
@@ -9511,6 +10629,7 @@ declare const riskSubject: Subject<RiskContract>;
|
|
|
9511
10629
|
*/
|
|
9512
10630
|
declare const pingSubject: Subject<PingContract>;
|
|
9513
10631
|
|
|
10632
|
+
declare const emitters_breakevenSubject: typeof breakevenSubject;
|
|
9514
10633
|
declare const emitters_doneBacktestSubject: typeof doneBacktestSubject;
|
|
9515
10634
|
declare const emitters_doneLiveSubject: typeof doneLiveSubject;
|
|
9516
10635
|
declare const emitters_doneWalkerSubject: typeof doneWalkerSubject;
|
|
@@ -9532,7 +10651,7 @@ declare const emitters_walkerCompleteSubject: typeof walkerCompleteSubject;
|
|
|
9532
10651
|
declare const emitters_walkerEmitter: typeof walkerEmitter;
|
|
9533
10652
|
declare const emitters_walkerStopSubject: typeof walkerStopSubject;
|
|
9534
10653
|
declare namespace emitters {
|
|
9535
|
-
export { emitters_doneBacktestSubject as doneBacktestSubject, emitters_doneLiveSubject as doneLiveSubject, emitters_doneWalkerSubject as doneWalkerSubject, emitters_errorEmitter as errorEmitter, emitters_exitEmitter as exitEmitter, emitters_partialLossSubject as partialLossSubject, emitters_partialProfitSubject as partialProfitSubject, emitters_performanceEmitter as performanceEmitter, emitters_pingSubject as pingSubject, emitters_progressBacktestEmitter as progressBacktestEmitter, emitters_progressOptimizerEmitter as progressOptimizerEmitter, emitters_progressWalkerEmitter as progressWalkerEmitter, emitters_riskSubject as riskSubject, emitters_signalBacktestEmitter as signalBacktestEmitter, emitters_signalEmitter as signalEmitter, emitters_signalLiveEmitter as signalLiveEmitter, emitters_validationSubject as validationSubject, emitters_walkerCompleteSubject as walkerCompleteSubject, emitters_walkerEmitter as walkerEmitter, emitters_walkerStopSubject as walkerStopSubject };
|
|
10654
|
+
export { emitters_breakevenSubject as breakevenSubject, emitters_doneBacktestSubject as doneBacktestSubject, emitters_doneLiveSubject as doneLiveSubject, emitters_doneWalkerSubject as doneWalkerSubject, emitters_errorEmitter as errorEmitter, emitters_exitEmitter as exitEmitter, emitters_partialLossSubject as partialLossSubject, emitters_partialProfitSubject as partialProfitSubject, emitters_performanceEmitter as performanceEmitter, emitters_pingSubject as pingSubject, emitters_progressBacktestEmitter as progressBacktestEmitter, emitters_progressOptimizerEmitter as progressOptimizerEmitter, emitters_progressWalkerEmitter as progressWalkerEmitter, emitters_riskSubject as riskSubject, emitters_signalBacktestEmitter as signalBacktestEmitter, emitters_signalEmitter as signalEmitter, emitters_signalLiveEmitter as signalLiveEmitter, emitters_validationSubject as validationSubject, emitters_walkerCompleteSubject as walkerCompleteSubject, emitters_walkerEmitter as walkerEmitter, emitters_walkerStopSubject as walkerStopSubject };
|
|
9536
10655
|
}
|
|
9537
10656
|
|
|
9538
10657
|
/**
|
|
@@ -10065,7 +11184,7 @@ declare class PartialConnectionService implements IPartial {
|
|
|
10065
11184
|
* @param when - Event timestamp (current time for live, candle time for backtest)
|
|
10066
11185
|
* @returns Promise that resolves when profit processing is complete
|
|
10067
11186
|
*/
|
|
10068
|
-
profit: (symbol: string, data:
|
|
11187
|
+
profit: (symbol: string, data: IPublicSignalRow, currentPrice: number, revenuePercent: number, backtest: boolean, when: Date) => Promise<void>;
|
|
10069
11188
|
/**
|
|
10070
11189
|
* Processes loss state and emits events for newly reached loss levels.
|
|
10071
11190
|
*
|
|
@@ -10080,7 +11199,7 @@ declare class PartialConnectionService implements IPartial {
|
|
|
10080
11199
|
* @param when - Event timestamp (current time for live, candle time for backtest)
|
|
10081
11200
|
* @returns Promise that resolves when loss processing is complete
|
|
10082
11201
|
*/
|
|
10083
|
-
loss: (symbol: string, data:
|
|
11202
|
+
loss: (symbol: string, data: IPublicSignalRow, currentPrice: number, lossPercent: number, backtest: boolean, when: Date) => Promise<void>;
|
|
10084
11203
|
/**
|
|
10085
11204
|
* Clears partial profit/loss state when signal closes.
|
|
10086
11205
|
*
|
|
@@ -10101,6 +11220,88 @@ declare class PartialConnectionService implements IPartial {
|
|
|
10101
11220
|
clear: (symbol: string, data: ISignalRow, priceClose: number, backtest: boolean) => Promise<void>;
|
|
10102
11221
|
}
|
|
10103
11222
|
|
|
11223
|
+
/**
|
|
11224
|
+
* Connection service for breakeven tracking.
|
|
11225
|
+
*
|
|
11226
|
+
* Provides memoized ClientBreakeven instances per signal ID.
|
|
11227
|
+
* Acts as factory and lifetime manager for ClientBreakeven objects.
|
|
11228
|
+
*
|
|
11229
|
+
* Features:
|
|
11230
|
+
* - Creates one ClientBreakeven instance per signal ID (memoized)
|
|
11231
|
+
* - Configures instances with logger and event emitter callbacks
|
|
11232
|
+
* - Delegates check/clear operations to appropriate ClientBreakeven
|
|
11233
|
+
* - Cleans up memoized instances when signals are cleared
|
|
11234
|
+
*
|
|
11235
|
+
* Architecture:
|
|
11236
|
+
* - Injected into ClientStrategy via BreakevenGlobalService
|
|
11237
|
+
* - Uses memoize from functools-kit for instance caching
|
|
11238
|
+
* - Emits events to breakevenSubject
|
|
11239
|
+
*
|
|
11240
|
+
* @example
|
|
11241
|
+
* ```typescript
|
|
11242
|
+
* // Service injected via DI
|
|
11243
|
+
* const service = inject<BreakevenConnectionService>(TYPES.breakevenConnectionService);
|
|
11244
|
+
*
|
|
11245
|
+
* // Called by ClientStrategy during signal monitoring
|
|
11246
|
+
* await service.check("BTCUSDT", signal, 100.5, false, new Date());
|
|
11247
|
+
* // Creates or reuses ClientBreakeven for signal.id
|
|
11248
|
+
* // Delegates to ClientBreakeven.check()
|
|
11249
|
+
*
|
|
11250
|
+
* // When signal closes
|
|
11251
|
+
* await service.clear("BTCUSDT", signal, 101, false);
|
|
11252
|
+
* // Clears signal state and removes memoized instance
|
|
11253
|
+
* ```
|
|
11254
|
+
*/
|
|
11255
|
+
declare class BreakevenConnectionService implements IBreakeven {
|
|
11256
|
+
/**
|
|
11257
|
+
* Logger service injected from DI container.
|
|
11258
|
+
*/
|
|
11259
|
+
private readonly loggerService;
|
|
11260
|
+
/**
|
|
11261
|
+
* Memoized factory function for ClientBreakeven instances.
|
|
11262
|
+
*
|
|
11263
|
+
* Creates one ClientBreakeven per signal ID and backtest mode with configured callbacks.
|
|
11264
|
+
* Instances are cached until clear() is called.
|
|
11265
|
+
*
|
|
11266
|
+
* Key format: "signalId:backtest" or "signalId:live"
|
|
11267
|
+
* Value: ClientBreakeven instance with logger and event emitter
|
|
11268
|
+
*/
|
|
11269
|
+
private getBreakeven;
|
|
11270
|
+
/**
|
|
11271
|
+
* Checks if breakeven should be triggered and emits event if conditions met.
|
|
11272
|
+
*
|
|
11273
|
+
* Retrieves or creates ClientBreakeven for signal ID, initializes it if needed,
|
|
11274
|
+
* then delegates to ClientBreakeven.check() method.
|
|
11275
|
+
*
|
|
11276
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
11277
|
+
* @param data - Signal row data
|
|
11278
|
+
* @param currentPrice - Current market price
|
|
11279
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
11280
|
+
* @param when - Event timestamp (current time for live, candle time for backtest)
|
|
11281
|
+
* @returns Promise that resolves when breakeven check is complete
|
|
11282
|
+
*/
|
|
11283
|
+
check: (symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean, when: Date) => Promise<boolean>;
|
|
11284
|
+
/**
|
|
11285
|
+
* Clears breakeven state when signal closes.
|
|
11286
|
+
*
|
|
11287
|
+
* Retrieves ClientBreakeven for signal ID, initializes if needed,
|
|
11288
|
+
* delegates clear operation, then removes memoized instance.
|
|
11289
|
+
*
|
|
11290
|
+
* Sequence:
|
|
11291
|
+
* 1. Get ClientBreakeven from memoize cache
|
|
11292
|
+
* 2. Ensure initialization (waitForInit)
|
|
11293
|
+
* 3. Call ClientBreakeven.clear() - removes state, persists to disk
|
|
11294
|
+
* 4. Clear memoized instance - prevents memory leaks
|
|
11295
|
+
*
|
|
11296
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
11297
|
+
* @param data - Signal row data
|
|
11298
|
+
* @param priceClose - Final closing price
|
|
11299
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
11300
|
+
* @returns Promise that resolves when clear is complete
|
|
11301
|
+
*/
|
|
11302
|
+
clear: (symbol: string, data: ISignalRow, priceClose: number, backtest: boolean) => Promise<void>;
|
|
11303
|
+
}
|
|
11304
|
+
|
|
10104
11305
|
/**
|
|
10105
11306
|
* Type definition for strategy methods.
|
|
10106
11307
|
* Maps all keys of IStrategy to any type.
|
|
@@ -10141,6 +11342,7 @@ declare class StrategyConnectionService implements TStrategy$1 {
|
|
|
10141
11342
|
readonly riskConnectionService: RiskConnectionService;
|
|
10142
11343
|
readonly exchangeConnectionService: ExchangeConnectionService;
|
|
10143
11344
|
readonly partialConnectionService: PartialConnectionService;
|
|
11345
|
+
readonly breakevenConnectionService: BreakevenConnectionService;
|
|
10144
11346
|
/**
|
|
10145
11347
|
* Retrieves memoized ClientStrategy instance for given symbol-strategy pair with exchange and frame isolation.
|
|
10146
11348
|
*
|
|
@@ -10349,6 +11551,64 @@ declare class StrategyConnectionService implements TStrategy$1 {
|
|
|
10349
11551
|
exchangeName: ExchangeName;
|
|
10350
11552
|
frameName: FrameName;
|
|
10351
11553
|
}) => Promise<void>;
|
|
11554
|
+
/**
|
|
11555
|
+
* Adjusts the trailing stop-loss distance for an active pending signal.
|
|
11556
|
+
*
|
|
11557
|
+
* Updates the stop-loss distance by a percentage adjustment relative to the original SL distance.
|
|
11558
|
+
* Positive percentShift tightens the SL (reduces distance), negative percentShift loosens it.
|
|
11559
|
+
*
|
|
11560
|
+
* Delegates to ClientStrategy.trailingStop() with current execution context.
|
|
11561
|
+
*
|
|
11562
|
+
* @param backtest - Whether running in backtest mode
|
|
11563
|
+
* @param symbol - Trading pair symbol
|
|
11564
|
+
* @param percentShift - Percentage adjustment to SL distance (-100 to 100)
|
|
11565
|
+
* @param context - Execution context with strategyName, exchangeName, frameName
|
|
11566
|
+
* @returns Promise that resolves when trailing SL is updated
|
|
11567
|
+
*
|
|
11568
|
+
* @example
|
|
11569
|
+
* ```typescript
|
|
11570
|
+
* // LONG: entry=100, originalSL=90, distance=10
|
|
11571
|
+
* // Tighten stop by 50%: newSL = 100 - 10*(1-0.5) = 95
|
|
11572
|
+
* await strategyConnectionService.trailingStop(
|
|
11573
|
+
* false,
|
|
11574
|
+
* "BTCUSDT",
|
|
11575
|
+
* -50,
|
|
11576
|
+
* { strategyName: "my-strategy", exchangeName: "binance", frameName: "" }
|
|
11577
|
+
* );
|
|
11578
|
+
* ```
|
|
11579
|
+
*/
|
|
11580
|
+
trailingStop: (backtest: boolean, symbol: string, percentShift: number, context: {
|
|
11581
|
+
strategyName: StrategyName;
|
|
11582
|
+
exchangeName: ExchangeName;
|
|
11583
|
+
frameName: FrameName;
|
|
11584
|
+
}) => Promise<void>;
|
|
11585
|
+
/**
|
|
11586
|
+
* Delegates to ClientStrategy.breakeven() with current execution context.
|
|
11587
|
+
*
|
|
11588
|
+
* @param backtest - Whether running in backtest mode
|
|
11589
|
+
* @param symbol - Trading pair symbol
|
|
11590
|
+
* @param currentPrice - Current market price to check threshold
|
|
11591
|
+
* @param context - Execution context with strategyName, exchangeName, frameName
|
|
11592
|
+
* @returns Promise<boolean> - true if breakeven was set, false otherwise
|
|
11593
|
+
*
|
|
11594
|
+
* @example
|
|
11595
|
+
* ```typescript
|
|
11596
|
+
* // LONG: entry=100, slippage=0.1%, fee=0.1%, threshold=0.4%
|
|
11597
|
+
* // Try to move SL to breakeven when price >= 100.4
|
|
11598
|
+
* const moved = await strategyConnectionService.breakeven(
|
|
11599
|
+
* false,
|
|
11600
|
+
* "BTCUSDT",
|
|
11601
|
+
* 100.5,
|
|
11602
|
+
* { strategyName: "my-strategy", exchangeName: "binance", frameName: "" }
|
|
11603
|
+
* );
|
|
11604
|
+
* console.log(moved); // true (SL moved to 100)
|
|
11605
|
+
* ```
|
|
11606
|
+
*/
|
|
11607
|
+
breakeven: (backtest: boolean, symbol: string, currentPrice: number, context: {
|
|
11608
|
+
strategyName: StrategyName;
|
|
11609
|
+
exchangeName: ExchangeName;
|
|
11610
|
+
frameName: FrameName;
|
|
11611
|
+
}) => Promise<boolean>;
|
|
10352
11612
|
}
|
|
10353
11613
|
|
|
10354
11614
|
/**
|
|
@@ -10821,6 +12081,62 @@ declare class StrategyCoreService implements TStrategy {
|
|
|
10821
12081
|
exchangeName: ExchangeName;
|
|
10822
12082
|
frameName: FrameName;
|
|
10823
12083
|
}) => Promise<void>;
|
|
12084
|
+
/**
|
|
12085
|
+
* Adjusts the trailing stop-loss distance for an active pending signal.
|
|
12086
|
+
*
|
|
12087
|
+
* Validates strategy existence and delegates to connection service
|
|
12088
|
+
* to update the stop-loss distance by a percentage adjustment.
|
|
12089
|
+
*
|
|
12090
|
+
* Does not require execution context as this is a direct state mutation.
|
|
12091
|
+
*
|
|
12092
|
+
* @param backtest - Whether running in backtest mode
|
|
12093
|
+
* @param symbol - Trading pair symbol
|
|
12094
|
+
* @param percentShift - Percentage adjustment to SL distance (-100 to 100)
|
|
12095
|
+
* @param context - Execution context with strategyName, exchangeName, frameName
|
|
12096
|
+
* @returns Promise that resolves when trailing SL is updated
|
|
12097
|
+
*
|
|
12098
|
+
* @example
|
|
12099
|
+
* ```typescript
|
|
12100
|
+
* // LONG: entry=100, originalSL=90, distance=10
|
|
12101
|
+
* // Tighten stop by 50%: newSL = 100 - 10*(1-0.5) = 95
|
|
12102
|
+
* await strategyCoreService.trailingStop(
|
|
12103
|
+
* false,
|
|
12104
|
+
* "BTCUSDT",
|
|
12105
|
+
* -50,
|
|
12106
|
+
* { strategyName: "my-strategy", exchangeName: "binance", frameName: "" }
|
|
12107
|
+
* );
|
|
12108
|
+
* ```
|
|
12109
|
+
*/
|
|
12110
|
+
trailingStop: (backtest: boolean, symbol: string, percentShift: number, context: {
|
|
12111
|
+
strategyName: StrategyName;
|
|
12112
|
+
exchangeName: ExchangeName;
|
|
12113
|
+
frameName: FrameName;
|
|
12114
|
+
}) => Promise<void>;
|
|
12115
|
+
/**
|
|
12116
|
+
* Moves stop-loss to breakeven when price reaches threshold.
|
|
12117
|
+
* Validates context and delegates to StrategyConnectionService.
|
|
12118
|
+
*
|
|
12119
|
+
* @param backtest - Whether running in backtest mode
|
|
12120
|
+
* @param symbol - Trading pair symbol
|
|
12121
|
+
* @param currentPrice - Current market price to check threshold
|
|
12122
|
+
* @param context - Strategy context with strategyName, exchangeName, frameName
|
|
12123
|
+
* @returns Promise<boolean> - true if breakeven was set, false otherwise
|
|
12124
|
+
*
|
|
12125
|
+
* @example
|
|
12126
|
+
* ```typescript
|
|
12127
|
+
* const moved = await strategyCoreService.breakeven(
|
|
12128
|
+
* false,
|
|
12129
|
+
* "BTCUSDT",
|
|
12130
|
+
* 112,
|
|
12131
|
+
* { strategyName: "my-strategy", exchangeName: "binance", frameName: "" }
|
|
12132
|
+
* );
|
|
12133
|
+
* ```
|
|
12134
|
+
*/
|
|
12135
|
+
breakeven: (backtest: boolean, symbol: string, currentPrice: number, context: {
|
|
12136
|
+
strategyName: StrategyName;
|
|
12137
|
+
exchangeName: ExchangeName;
|
|
12138
|
+
frameName: FrameName;
|
|
12139
|
+
}) => Promise<boolean>;
|
|
10824
12140
|
}
|
|
10825
12141
|
|
|
10826
12142
|
/**
|
|
@@ -12409,7 +13725,7 @@ declare class PartialGlobalService implements TPartial {
|
|
|
12409
13725
|
* @param when - Event timestamp (current time for live, candle time for backtest)
|
|
12410
13726
|
* @returns Promise that resolves when profit processing is complete
|
|
12411
13727
|
*/
|
|
12412
|
-
profit: (symbol: string, data:
|
|
13728
|
+
profit: (symbol: string, data: IPublicSignalRow, currentPrice: number, revenuePercent: number, backtest: boolean, when: Date) => Promise<void>;
|
|
12413
13729
|
/**
|
|
12414
13730
|
* Processes loss state and emits events for newly reached loss levels.
|
|
12415
13731
|
*
|
|
@@ -12423,7 +13739,7 @@ declare class PartialGlobalService implements TPartial {
|
|
|
12423
13739
|
* @param when - Event timestamp (current time for live, candle time for backtest)
|
|
12424
13740
|
* @returns Promise that resolves when loss processing is complete
|
|
12425
13741
|
*/
|
|
12426
|
-
loss: (symbol: string, data:
|
|
13742
|
+
loss: (symbol: string, data: IPublicSignalRow, currentPrice: number, lossPercent: number, backtest: boolean, when: Date) => Promise<void>;
|
|
12427
13743
|
/**
|
|
12428
13744
|
* Clears partial profit/loss state when signal closes.
|
|
12429
13745
|
*
|
|
@@ -12437,6 +13753,101 @@ declare class PartialGlobalService implements TPartial {
|
|
|
12437
13753
|
clear: (symbol: string, data: ISignalRow, priceClose: number, backtest: boolean) => Promise<void>;
|
|
12438
13754
|
}
|
|
12439
13755
|
|
|
13756
|
+
/**
|
|
13757
|
+
* Type definition for breakeven methods.
|
|
13758
|
+
* Maps all keys of IBreakeven to any type.
|
|
13759
|
+
* Used for dynamic method routing in BreakevenGlobalService.
|
|
13760
|
+
*/
|
|
13761
|
+
type TBreakeven = {
|
|
13762
|
+
[key in keyof IBreakeven]: any;
|
|
13763
|
+
};
|
|
13764
|
+
/**
|
|
13765
|
+
* Global service for breakeven tracking.
|
|
13766
|
+
*
|
|
13767
|
+
* Thin delegation layer that forwards operations to BreakevenConnectionService.
|
|
13768
|
+
* Provides centralized logging for all breakeven operations at the global level.
|
|
13769
|
+
*
|
|
13770
|
+
* Architecture:
|
|
13771
|
+
* - Injected into ClientStrategy constructor via IStrategyParams
|
|
13772
|
+
* - Delegates all operations to BreakevenConnectionService
|
|
13773
|
+
* - Logs operations at "breakevenGlobalService" level before delegation
|
|
13774
|
+
*
|
|
13775
|
+
* Purpose:
|
|
13776
|
+
* - Single injection point for ClientStrategy (dependency injection pattern)
|
|
13777
|
+
* - Centralized logging for monitoring breakeven operations
|
|
13778
|
+
* - Layer of abstraction between strategy and connection layer
|
|
13779
|
+
*
|
|
13780
|
+
* @example
|
|
13781
|
+
* ```typescript
|
|
13782
|
+
* // Service injected into ClientStrategy via DI
|
|
13783
|
+
* const strategy = new ClientStrategy({
|
|
13784
|
+
* breakeven: breakevenGlobalService,
|
|
13785
|
+
* ...
|
|
13786
|
+
* });
|
|
13787
|
+
*
|
|
13788
|
+
* // Called during signal monitoring
|
|
13789
|
+
* await strategy.params.breakeven.check("BTCUSDT", signal, 100.5, false, new Date());
|
|
13790
|
+
* // Logs at global level → delegates to BreakevenConnectionService
|
|
13791
|
+
* ```
|
|
13792
|
+
*/
|
|
13793
|
+
declare class BreakevenGlobalService implements TBreakeven {
|
|
13794
|
+
/**
|
|
13795
|
+
* Logger service injected from DI container.
|
|
13796
|
+
* Used for logging operations at global service level.
|
|
13797
|
+
*/
|
|
13798
|
+
private readonly loggerService;
|
|
13799
|
+
/**
|
|
13800
|
+
* Connection service injected from DI container.
|
|
13801
|
+
* Handles actual ClientBreakeven instance creation and management.
|
|
13802
|
+
*/
|
|
13803
|
+
private readonly breakevenConnectionService;
|
|
13804
|
+
/**
|
|
13805
|
+
* Strategy validation service for validating strategy existence.
|
|
13806
|
+
*/
|
|
13807
|
+
private readonly strategyValidationService;
|
|
13808
|
+
/**
|
|
13809
|
+
* Strategy schema service for retrieving strategy configuration.
|
|
13810
|
+
*/
|
|
13811
|
+
private readonly strategySchemaService;
|
|
13812
|
+
/**
|
|
13813
|
+
* Risk validation service for validating risk existence.
|
|
13814
|
+
*/
|
|
13815
|
+
private readonly riskValidationService;
|
|
13816
|
+
/**
|
|
13817
|
+
* Validates strategy and associated risk configuration.
|
|
13818
|
+
* Memoized to avoid redundant validations for the same strategy-exchange-frame combination.
|
|
13819
|
+
*
|
|
13820
|
+
* @param context - Context with strategyName, exchangeName and frameName
|
|
13821
|
+
* @param methodName - Name of the calling method for error tracking
|
|
13822
|
+
*/
|
|
13823
|
+
private validate;
|
|
13824
|
+
/**
|
|
13825
|
+
* Checks if breakeven should be triggered and emits event if conditions met.
|
|
13826
|
+
*
|
|
13827
|
+
* Logs operation at global service level, then delegates to BreakevenConnectionService.
|
|
13828
|
+
*
|
|
13829
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
13830
|
+
* @param data - Signal row data
|
|
13831
|
+
* @param currentPrice - Current market price
|
|
13832
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
13833
|
+
* @param when - Event timestamp (current time for live, candle time for backtest)
|
|
13834
|
+
* @returns Promise that resolves when breakeven check is complete
|
|
13835
|
+
*/
|
|
13836
|
+
check: (symbol: string, data: IPublicSignalRow, currentPrice: number, backtest: boolean, when: Date) => Promise<boolean>;
|
|
13837
|
+
/**
|
|
13838
|
+
* Clears breakeven state when signal closes.
|
|
13839
|
+
*
|
|
13840
|
+
* Logs operation at global service level, then delegates to BreakevenConnectionService.
|
|
13841
|
+
*
|
|
13842
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
13843
|
+
* @param data - Signal row data
|
|
13844
|
+
* @param priceClose - Final closing price
|
|
13845
|
+
* @param backtest - True if backtest mode, false if live mode
|
|
13846
|
+
* @returns Promise that resolves when clear is complete
|
|
13847
|
+
*/
|
|
13848
|
+
clear: (symbol: string, data: ISignalRow, priceClose: number, backtest: boolean) => Promise<void>;
|
|
13849
|
+
}
|
|
13850
|
+
|
|
12440
13851
|
/**
|
|
12441
13852
|
* Unique identifier for outline result.
|
|
12442
13853
|
* Can be string or number for flexible ID formats.
|
|
@@ -12601,6 +14012,7 @@ declare const backtest: {
|
|
|
12601
14012
|
walkerMarkdownService: WalkerMarkdownService;
|
|
12602
14013
|
heatMarkdownService: HeatMarkdownService;
|
|
12603
14014
|
partialMarkdownService: PartialMarkdownService;
|
|
14015
|
+
breakevenMarkdownService: BreakevenMarkdownService;
|
|
12604
14016
|
outlineMarkdownService: OutlineMarkdownService;
|
|
12605
14017
|
riskMarkdownService: RiskMarkdownService;
|
|
12606
14018
|
backtestLogicPublicService: BacktestLogicPublicService;
|
|
@@ -12616,6 +14028,7 @@ declare const backtest: {
|
|
|
12616
14028
|
riskGlobalService: RiskGlobalService;
|
|
12617
14029
|
optimizerGlobalService: OptimizerGlobalService;
|
|
12618
14030
|
partialGlobalService: PartialGlobalService;
|
|
14031
|
+
breakevenGlobalService: BreakevenGlobalService;
|
|
12619
14032
|
exchangeCoreService: ExchangeCoreService;
|
|
12620
14033
|
strategyCoreService: StrategyCoreService;
|
|
12621
14034
|
frameCoreService: FrameCoreService;
|
|
@@ -12633,6 +14046,7 @@ declare const backtest: {
|
|
|
12633
14046
|
riskConnectionService: RiskConnectionService;
|
|
12634
14047
|
optimizerConnectionService: OptimizerConnectionService;
|
|
12635
14048
|
partialConnectionService: PartialConnectionService;
|
|
14049
|
+
breakevenConnectionService: BreakevenConnectionService;
|
|
12636
14050
|
executionContextService: {
|
|
12637
14051
|
readonly context: IExecutionContext;
|
|
12638
14052
|
};
|
|
@@ -12642,4 +14056,4 @@ declare const backtest: {
|
|
|
12642
14056
|
loggerService: LoggerService;
|
|
12643
14057
|
};
|
|
12644
14058
|
|
|
12645
|
-
export { Backtest, type BacktestDoneNotification, type BacktestStatisticsModel, type BootstrapNotification, Cache, type CandleInterval, type ColumnConfig, type ColumnModel, Constant, type CriticalErrorNotification, type DoneContract, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalCancelRow, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategyResult, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, type InfoErrorNotification, Live, type LiveDoneNotification, type LiveStatisticsModel, type MessageModel, type MessageRole, MethodContextService, type MetricStats, Notification, type NotificationModel, Optimizer, Partial$1 as Partial, type PartialData, type PartialEvent, type PartialLossContract, type PartialLossNotification, type PartialProfitContract, type PartialProfitNotification, type PartialStatisticsModel, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatisticsModel, PersistBase, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, type PingContract, PositionSize, type ProgressBacktestContract, type ProgressBacktestNotification, type ProgressOptimizerContract, type ProgressWalkerContract, Risk, type RiskContract, type RiskData, type RiskEvent, type RiskRejectionNotification, type RiskStatisticsModel, Schedule, type ScheduleData, type ScheduleStatisticsModel, type ScheduledEvent, type SignalCancelledNotification, type SignalClosedNotification, type SignalData, type SignalInterval, type SignalOpenedNotification, type SignalScheduledNotification, type TPersistBase, type TPersistBaseCtor, type TickEvent, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addExchange, addFrame, addOptimizer, addRisk, addSizing, addStrategy, addWalker, cancel, dumpSignal, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getColumns, getConfig, getDate, getDefaultColumns, getDefaultConfig, getMode, hasTradeContext, backtest as lib, listExchanges, listFrames, listOptimizers, listRisks, listSizings, listStrategies, listWalkers, listenBacktestProgress, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenOptimizerProgress, listenPartialLoss, listenPartialLossOnce, listenPartialProfit, listenPartialProfitOnce, listenPerformance, listenPing, listenPingOnce, listenRisk, listenRiskOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, partialLoss, partialProfit, setColumns, setConfig, setLogger, stop, validate };
|
|
14059
|
+
export { Backtest, type BacktestDoneNotification, type BacktestStatisticsModel, type BootstrapNotification, Breakeven, type BreakevenContract, type BreakevenData, Cache, type CandleInterval, type ColumnConfig, type ColumnModel, Constant, type CriticalErrorNotification, type DoneContract, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IPublicSignalRow, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalCancelRow, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategyResult, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, type InfoErrorNotification, Live, type LiveDoneNotification, type LiveStatisticsModel, type MessageModel, type MessageRole, MethodContextService, type MetricStats, Notification, type NotificationModel, Optimizer, Partial$1 as Partial, type PartialData, type PartialEvent, type PartialLossContract, type PartialLossNotification, type PartialProfitContract, type PartialProfitNotification, type PartialStatisticsModel, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatisticsModel, PersistBase, PersistBreakevenAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, type PingContract, PositionSize, type ProgressBacktestContract, type ProgressBacktestNotification, type ProgressOptimizerContract, type ProgressWalkerContract, Risk, type RiskContract, type RiskData, type RiskEvent, type RiskRejectionNotification, type RiskStatisticsModel, Schedule, type ScheduleData, type ScheduleStatisticsModel, type ScheduledEvent, type SignalCancelledNotification, type SignalClosedNotification, type SignalData, type SignalInterval, type SignalOpenedNotification, type SignalScheduledNotification, type TPersistBase, type TPersistBaseCtor, type TickEvent, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addExchange, addFrame, addOptimizer, addRisk, addSizing, addStrategy, addWalker, breakeven, cancel, dumpSignal, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getColumns, getConfig, getDate, getDefaultColumns, getDefaultConfig, getMode, hasTradeContext, backtest as lib, listExchanges, listFrames, listOptimizers, listRisks, listSizings, listStrategies, listWalkers, listenBacktestProgress, listenBreakeven, listenBreakevenOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenOptimizerProgress, listenPartialLoss, listenPartialLossOnce, listenPartialProfit, listenPartialProfitOnce, listenPerformance, listenPing, listenPingOnce, listenRisk, listenRiskOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, partialLoss, partialProfit, setColumns, setConfig, setLogger, stop, trailingStop, validate };
|