backtest-kit 2.2.10 → 2.2.12

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/types.d.ts CHANGED
@@ -1130,6 +1130,18 @@ interface IPublicSignalRow extends ISignalRow {
1130
1130
  */
1131
1131
  totalExecuted: number;
1132
1132
  }
1133
+ /**
1134
+ * Storage signal row with creation timestamp taken from IStrategyTickResult.
1135
+ * Used for persisting signals with accurate creation time.
1136
+ */
1137
+ interface IStorageSignalRow extends IPublicSignalRow {
1138
+ /** Creation timestamp taken from IStrategyTickResult */
1139
+ updatedAt: number;
1140
+ /** Storage adapter rewrite priority. Equal to Date.now for live and backtest both */
1141
+ priority: number;
1142
+ /** Current status of the signal */
1143
+ status: "opened" | "scheduled" | "closed" | "cancelled";
1144
+ }
1133
1145
  /**
1134
1146
  * Risk signal row for internal risk management.
1135
1147
  * Extends ISignalDto to include priceOpen, originalPriceStopLoss and originalPriceTakeProfit.
@@ -7517,7 +7529,7 @@ declare class PersistBase<EntityName extends string = string> implements IPersis
7517
7529
  */
7518
7530
  declare class PersistSignalUtils {
7519
7531
  private PersistSignalFactory;
7520
- private getSignalStorage;
7532
+ private getStorage;
7521
7533
  /**
7522
7534
  * Registers a custom persistence adapter.
7523
7535
  *
@@ -8047,6 +8059,71 @@ declare class PersistCandleUtils {
8047
8059
  * ```
8048
8060
  */
8049
8061
  declare const PersistCandleAdapter: PersistCandleUtils;
8062
+ /**
8063
+ * Type for persisted signal storage data.
8064
+ * Each signal is stored as a separate file keyed by its id.
8065
+ */
8066
+ type StorageData = IStorageSignalRow[];
8067
+ /**
8068
+ * Utility class for managing signal storage persistence.
8069
+ *
8070
+ * Features:
8071
+ * - Memoized storage instances
8072
+ * - Custom adapter support
8073
+ * - Atomic read/write operations for StorageData
8074
+ * - Each signal stored as separate file keyed by id
8075
+ * - Crash-safe signal state management
8076
+ *
8077
+ * Used by SignalLiveUtils for live mode persistence of signals.
8078
+ */
8079
+ declare class PersistStorageUtils {
8080
+ private PersistStorageFactory;
8081
+ private getStorageStorage;
8082
+ /**
8083
+ * Registers a custom persistence adapter.
8084
+ *
8085
+ * @param Ctor - Custom PersistBase constructor
8086
+ */
8087
+ usePersistStorageAdapter(Ctor: TPersistBaseCtor<string, IStorageSignalRow>): void;
8088
+ /**
8089
+ * Reads persisted signals data.
8090
+ *
8091
+ * Called by StorageLiveUtils/StorageBacktestUtils.waitForInit() to restore state.
8092
+ * Uses keys() from PersistBase to iterate over all stored signals.
8093
+ * Returns empty array if no signals exist.
8094
+ *
8095
+ * @param backtest - If true, reads from backtest storage; otherwise from live storage
8096
+ * @returns Promise resolving to array of signal entries
8097
+ */
8098
+ readStorageData: (backtest: boolean) => Promise<StorageData>;
8099
+ /**
8100
+ * Writes signal data to disk with atomic file writes.
8101
+ *
8102
+ * Called by StorageLiveUtils/StorageBacktestUtils after signal changes to persist state.
8103
+ * Uses signal.id as the storage key for individual file storage.
8104
+ * Uses atomic writes to prevent corruption on crashes.
8105
+ *
8106
+ * @param signalData - Signal entries to persist
8107
+ * @param backtest - If true, writes to backtest storage; otherwise to live storage
8108
+ * @returns Promise that resolves when write is complete
8109
+ */
8110
+ writeStorageData: (signalData: StorageData, backtest: boolean) => Promise<void>;
8111
+ /**
8112
+ * Switches to the default JSON persist adapter.
8113
+ * All future persistence writes will use JSON storage.
8114
+ */
8115
+ useJson(): void;
8116
+ /**
8117
+ * Switches to a dummy persist adapter that discards all writes.
8118
+ * All future persistence writes will be no-ops.
8119
+ */
8120
+ useDummy(): void;
8121
+ }
8122
+ /**
8123
+ * Global singleton instance of PersistStorageUtils.
8124
+ * Used by SignalLiveUtils for signal storage persistence.
8125
+ */
8126
+ declare const PersistStorageAdapter: PersistStorageUtils;
8050
8127
 
8051
8128
  declare const WAIT_FOR_INIT_SYMBOL$1: unique symbol;
8052
8129
  declare const WRITE_SAFE_SYMBOL$1: unique symbol;
@@ -12367,6 +12444,220 @@ declare class RiskUtils {
12367
12444
  */
12368
12445
  declare const Risk: RiskUtils;
12369
12446
 
12447
+ type StorageId = IStorageSignalRow["id"];
12448
+ /**
12449
+ * Utility class for managing backtest signal history.
12450
+ *
12451
+ * Stores trading signal history for admin dashboard display during backtesting
12452
+ * with automatic initialization, deduplication, and storage limits.
12453
+ *
12454
+ * @example
12455
+ * ```typescript
12456
+ * import { StorageBacktestUtils } from "./classes/Storage";
12457
+ *
12458
+ * const storage = new StorageBacktestUtils();
12459
+ *
12460
+ * // Handle signal events
12461
+ * await storage.handleOpened(tickResult);
12462
+ * await storage.handleClosed(tickResult);
12463
+ *
12464
+ * // Query signals
12465
+ * const signal = await storage.findById("signal-123");
12466
+ * const allSignals = await storage.list();
12467
+ * ```
12468
+ */
12469
+ declare class StorageBacktestUtils {
12470
+ private _signals;
12471
+ /**
12472
+ * Initializes storage by loading existing signal history from persist layer.
12473
+ * Uses singleshot to ensure initialization happens only once.
12474
+ */
12475
+ private waitForInit;
12476
+ /**
12477
+ * Persists current signal history to storage.
12478
+ * Sorts by priority and limits to MAX_SIGNALS entries.
12479
+ *
12480
+ * @throws Error if storage not initialized
12481
+ */
12482
+ private _updateStorage;
12483
+ /**
12484
+ * Handles signal opened event.
12485
+ *
12486
+ * @param tick - Tick result containing opened signal data
12487
+ * @returns Promise resolving when storage is updated
12488
+ */
12489
+ handleOpened: (tick: IStrategyTickResultOpened) => Promise<void>;
12490
+ /**
12491
+ * Handles signal closed event.
12492
+ *
12493
+ * @param tick - Tick result containing closed signal data
12494
+ * @returns Promise resolving when storage is updated
12495
+ */
12496
+ handleClosed: (tick: IStrategyTickResultClosed) => Promise<void>;
12497
+ /**
12498
+ * Handles signal scheduled event.
12499
+ *
12500
+ * @param tick - Tick result containing scheduled signal data
12501
+ * @returns Promise resolving when storage is updated
12502
+ */
12503
+ handleScheduled: (tick: IStrategyTickResultScheduled) => Promise<void>;
12504
+ /**
12505
+ * Handles signal cancelled event.
12506
+ *
12507
+ * @param tick - Tick result containing cancelled signal data
12508
+ * @returns Promise resolving when storage is updated
12509
+ */
12510
+ handleCancelled: (tick: IStrategyTickResultCancelled) => Promise<void>;
12511
+ /**
12512
+ * Finds a signal by its unique identifier.
12513
+ *
12514
+ * @param id - Signal identifier
12515
+ * @returns Promise resolving to signal row or null if not found
12516
+ */
12517
+ findById: (id: StorageId) => Promise<IStorageSignalRow | null>;
12518
+ /**
12519
+ * Lists all stored backtest signals.
12520
+ *
12521
+ * @returns Promise resolving to array of signal rows
12522
+ */
12523
+ list: () => Promise<IStorageSignalRow[]>;
12524
+ }
12525
+ /**
12526
+ * Utility class for managing live trading signal history.
12527
+ *
12528
+ * Stores trading signal history for admin dashboard display during live trading
12529
+ * with automatic initialization, deduplication, and storage limits.
12530
+ *
12531
+ * @example
12532
+ * ```typescript
12533
+ * import { StorageLiveUtils } from "./classes/Storage";
12534
+ *
12535
+ * const storage = new StorageLiveUtils();
12536
+ *
12537
+ * // Handle signal events
12538
+ * await storage.handleOpened(tickResult);
12539
+ * await storage.handleClosed(tickResult);
12540
+ *
12541
+ * // Query signals
12542
+ * const signal = await storage.findById("signal-123");
12543
+ * const allSignals = await storage.list();
12544
+ * ```
12545
+ */
12546
+ declare class StorageLiveUtils {
12547
+ private _signals;
12548
+ /**
12549
+ * Initializes storage by loading existing signal history from persist layer.
12550
+ * Uses singleshot to ensure initialization happens only once.
12551
+ */
12552
+ private waitForInit;
12553
+ /**
12554
+ * Persists current signal history to storage.
12555
+ * Sorts by priority and limits to MAX_SIGNALS entries.
12556
+ *
12557
+ * @throws Error if storage not initialized
12558
+ */
12559
+ private _updateStorage;
12560
+ /**
12561
+ * Handles signal opened event.
12562
+ *
12563
+ * @param tick - Tick result containing opened signal data
12564
+ * @returns Promise resolving when history is updated
12565
+ */
12566
+ handleOpened: (tick: IStrategyTickResultOpened) => Promise<void>;
12567
+ /**
12568
+ * Handles signal closed event.
12569
+ *
12570
+ * @param tick - Tick result containing closed signal data
12571
+ * @returns Promise resolving when history is updated
12572
+ */
12573
+ handleClosed: (tick: IStrategyTickResultClosed) => Promise<void>;
12574
+ /**
12575
+ * Handles signal scheduled event.
12576
+ *
12577
+ * @param tick - Tick result containing scheduled signal data
12578
+ * @returns Promise resolving when history is updated
12579
+ */
12580
+ handleScheduled: (tick: IStrategyTickResultScheduled) => Promise<void>;
12581
+ /**
12582
+ * Handles signal cancelled event.
12583
+ *
12584
+ * @param tick - Tick result containing cancelled signal data
12585
+ * @returns Promise resolving when history is updated
12586
+ */
12587
+ handleCancelled: (tick: IStrategyTickResultCancelled) => Promise<void>;
12588
+ /**
12589
+ * Finds a signal by its unique identifier.
12590
+ *
12591
+ * @param id - Signal identifier
12592
+ * @returns Promise resolving to signal row or null if not found
12593
+ */
12594
+ findById: (id: StorageId) => Promise<IStorageSignalRow | null>;
12595
+ /**
12596
+ * Lists all stored live signals.
12597
+ *
12598
+ * @returns Promise resolving to array of signal rows
12599
+ */
12600
+ list: () => Promise<IStorageSignalRow[]>;
12601
+ }
12602
+ /**
12603
+ * Main storage adapter for signal history management.
12604
+ *
12605
+ * Provides unified interface for accessing backtest and live signal history
12606
+ * for admin dashboard. Subscribes to signal emitters and automatically
12607
+ * updates history on signal events.
12608
+ *
12609
+ * @example
12610
+ * ```typescript
12611
+ * import { Storage } from "./classes/Storage";
12612
+ *
12613
+ * // Enable signal history tracking
12614
+ * const unsubscribe = Storage.enable();
12615
+ *
12616
+ * // Query signals
12617
+ * const backtestSignals = await Storage.listSignalBacktest();
12618
+ * const liveSignals = await Storage.listSignalLive();
12619
+ * const signal = await Storage.findSignalById("signal-123");
12620
+ *
12621
+ * // Disable tracking
12622
+ * Storage.disable();
12623
+ * ```
12624
+ */
12625
+ declare class StorageAdapter {
12626
+ _signalLiveUtils: StorageLiveUtils;
12627
+ _signalBacktestUtils: StorageBacktestUtils;
12628
+ /**
12629
+ * Enables signal history tracking by subscribing to emitters.
12630
+ *
12631
+ * @returns Cleanup function to unsubscribe from all emitters
12632
+ */
12633
+ enable: (() => () => void) & functools_kit.ISingleshotClearable;
12634
+ /**
12635
+ * Disables signal history tracking by unsubscribing from emitters.
12636
+ */
12637
+ disable: () => void;
12638
+ /**
12639
+ * Finds a signal by ID across both backtest and live history.
12640
+ *
12641
+ * @param id - Signal identifier
12642
+ * @returns Promise resolving to signal row
12643
+ * @throws Error if signal not found in either storage
12644
+ */
12645
+ findSignalById: (id: StorageId) => Promise<IStorageSignalRow | null>;
12646
+ /**
12647
+ * Lists all backtest signal history.
12648
+ *
12649
+ * @returns Promise resolving to array of backtest signal rows
12650
+ */
12651
+ listSignalBacktest: () => Promise<IStorageSignalRow[]>;
12652
+ /**
12653
+ * Lists all live signal history.
12654
+ *
12655
+ * @returns Promise resolving to array of live signal rows
12656
+ */
12657
+ listSignalLive: () => Promise<IStorageSignalRow[]>;
12658
+ }
12659
+ declare const Storage: StorageAdapter;
12660
+
12370
12661
  /**
12371
12662
  * Utility class for exchange operations.
12372
12663
  *
@@ -19327,4 +19618,4 @@ declare const backtest: {
19327
19618
  loggerService: LoggerService;
19328
19619
  };
19329
19620
 
19330
- export { ActionBase, type ActivePingContract, Backtest, type BacktestStatisticsModel, Breakeven, type BreakevenAvailableNotification, type BreakevenCommitNotification, type BreakevenContract, type BreakevenData, Cache, type CandleData, type CandleInterval, type ColumnConfig, type ColumnModel, Constant, type CriticalErrorNotification, type DoneContract, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, type IBidData, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IMarkdownDumpOptions, type IOrderBookData, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IPublicSignalRow, type IReportDumpOptions, 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 LiveStatisticsModel, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, MethodContextService, type MetricStats, Notification, type NotificationModel, Partial$1 as Partial, type PartialData, type PartialEvent, type PartialLossAvailableNotification, type PartialLossCommitNotification, type PartialLossContract, type PartialProfitAvailableNotification, type PartialProfitCommitNotification, type PartialProfitContract, type PartialStatisticsModel, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatisticsModel, PersistBase, PersistBreakevenAdapter, PersistCandleAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, type ProgressBacktestContract, type ProgressWalkerContract, Report, ReportBase, type ReportName, Risk, type RiskContract, type RiskData, type RiskEvent, type RiskRejectionNotification, type RiskStatisticsModel, Schedule, type ScheduleData, type SchedulePingContract, type ScheduleStatisticsModel, type ScheduledEvent, type SignalCancelledNotification, type SignalClosedNotification, type SignalData, type SignalInterval, type SignalOpenedNotification, type SignalScheduledNotification, Strategy, type StrategyActionType, type StrategyCommitContract, type StrategyEvent, type StrategyStatisticsModel, type TMarkdownBase, type TPersistBase, type TPersistBaseCtor, type TReportBase, type TickEvent, type TrailingStopCommitNotification, type TrailingTakeCommitNotification, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addActionSchema, addExchangeSchema, addFrameSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, commitBreakeven, commitCancelScheduled, commitClosePending, commitPartialLoss, commitPartialProfit, commitTrailingStop, commitTrailingTake, emitters, formatPrice, formatQuantity, get, getActionSchema, getAveragePrice, getBacktestTimeframe, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getExchangeSchema, getFrameSchema, getMode, getOrderBook, getRawCandles, getRiskSchema, getSizingSchema, getStrategySchema, getSymbol, getWalkerSchema, hasTradeContext, backtest as lib, listExchangeSchema, listFrameSchema, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenStrategyCommit, listenStrategyCommitOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, roundTicks, set, setColumns, setConfig, setLogger, stopStrategy, validate };
19621
+ export { ActionBase, type ActivePingContract, Backtest, type BacktestStatisticsModel, Breakeven, type BreakevenAvailableNotification, type BreakevenCommitNotification, type BreakevenContract, type BreakevenData, Cache, type CandleData, type CandleInterval, type ColumnConfig, type ColumnModel, Constant, type CriticalErrorNotification, type DoneContract, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, type IBidData, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IMarkdownDumpOptions, type IOrderBookData, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IPublicSignalRow, type IReportDumpOptions, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskSignalRow, 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 IStorageSignalRow, type IStrategyPnL, type IStrategyResult, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IStrategyTickResultWaiting, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, type InfoErrorNotification, Live, type LiveStatisticsModel, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, MethodContextService, type MetricStats, Notification, type NotificationModel, Partial$1 as Partial, type PartialData, type PartialEvent, type PartialLossAvailableNotification, type PartialLossCommitNotification, type PartialLossContract, type PartialProfitAvailableNotification, type PartialProfitCommitNotification, type PartialProfitContract, type PartialStatisticsModel, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatisticsModel, PersistBase, PersistBreakevenAdapter, PersistCandleAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PersistStorageAdapter, PositionSize, type ProgressBacktestContract, type ProgressWalkerContract, Report, ReportBase, type ReportName, Risk, type RiskContract, type RiskData, type RiskEvent, type RiskRejectionNotification, type RiskStatisticsModel, Schedule, type ScheduleData, type SchedulePingContract, type ScheduleStatisticsModel, type ScheduledEvent, type SignalCancelledNotification, type SignalClosedNotification, type SignalData, type SignalInterval, type SignalOpenedNotification, type SignalScheduledNotification, Storage, type StorageData, Strategy, type StrategyActionType, type StrategyCancelReason, type StrategyCloseReason, type StrategyCommitContract, type StrategyEvent, type StrategyStatisticsModel, type TMarkdownBase, type TPersistBase, type TPersistBaseCtor, type TReportBase, type TickEvent, type TrailingStopCommitNotification, type TrailingTakeCommitNotification, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addActionSchema, addExchangeSchema, addFrameSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, commitBreakeven, commitCancelScheduled, commitClosePending, commitPartialLoss, commitPartialProfit, commitTrailingStop, commitTrailingTake, emitters, formatPrice, formatQuantity, get, getActionSchema, getAveragePrice, getBacktestTimeframe, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getExchangeSchema, getFrameSchema, getMode, getOrderBook, getRawCandles, getRiskSchema, getSizingSchema, getStrategySchema, getSymbol, getWalkerSchema, hasTradeContext, backtest as lib, listExchangeSchema, listFrameSchema, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenStrategyCommit, listenStrategyCommitOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, roundTicks, set, setColumns, setConfig, setLogger, stopStrategy, validate };