backtest-kit 1.1.3 → 1.1.5

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
@@ -140,6 +140,8 @@ interface IExchangeCallbacks {
140
140
  interface IExchangeSchema {
141
141
  /** Unique exchange identifier for registration */
142
142
  exchangeName: ExchangeName;
143
+ /** Optional developer note for documentation */
144
+ note?: string;
143
145
  /**
144
146
  * Fetch candles from data source (API or database).
145
147
  *
@@ -278,6 +280,8 @@ interface IFrameCallbacks {
278
280
  interface IFrameSchema {
279
281
  /** Unique identifier for this frame */
280
282
  frameName: FrameName;
283
+ /** Optional developer note for documentation */
284
+ note?: string;
281
285
  /** Interval for timestamp generation */
282
286
  interval: FrameInterval;
283
287
  /** Start of backtest period (inclusive) */
@@ -413,6 +417,8 @@ interface IStrategyCallbacks {
413
417
  interface IStrategySchema {
414
418
  /** Unique strategy identifier for registration */
415
419
  strategyName: StrategyName;
420
+ /** Optional developer note for documentation */
421
+ note?: string;
416
422
  /** Minimum interval between getSignal calls (throttling) */
417
423
  interval: SignalInterval;
418
424
  /** Signal generation function (returns null if no signal, validated DTO if signal) */
@@ -536,6 +542,27 @@ interface IStrategy {
536
542
  * @returns Promise resolving to closed result (always completes signal)
537
543
  */
538
544
  backtest: (candles: ICandleData[]) => Promise<IStrategyBacktestResult>;
545
+ /**
546
+ * Stops the strategy from generating new signals.
547
+ *
548
+ * Sets internal flag to prevent getSignal from being called on subsequent ticks.
549
+ * Does NOT force-close active pending signals - they continue monitoring until natural closure (TP/SL/time_expired).
550
+ *
551
+ * Use case: Graceful shutdown in live trading mode without abandoning open positions.
552
+ *
553
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
554
+ * @returns Promise that resolves immediately when stop flag is set
555
+ *
556
+ * @example
557
+ * ```typescript
558
+ * // Graceful shutdown in Live.background() cancellation
559
+ * const cancel = await Live.background("BTCUSDT", { ... });
560
+ *
561
+ * // Later: stop new signals, let existing ones close naturally
562
+ * await cancel();
563
+ * ```
564
+ */
565
+ stop: (symbol: string) => Promise<void>;
539
566
  }
540
567
  /**
541
568
  * Unique strategy identifier.
@@ -645,6 +672,90 @@ declare function addExchange(exchangeSchema: IExchangeSchema): void;
645
672
  */
646
673
  declare function addFrame(frameSchema: IFrameSchema): void;
647
674
 
675
+ /**
676
+ * Returns a list of all registered exchange schemas.
677
+ *
678
+ * Retrieves all exchanges that have been registered via addExchange().
679
+ * Useful for debugging, documentation, or building dynamic UIs.
680
+ *
681
+ * @returns Array of exchange schemas with their configurations
682
+ *
683
+ * @example
684
+ * ```typescript
685
+ * import { listExchanges, addExchange } from "backtest-kit";
686
+ *
687
+ * addExchange({
688
+ * exchangeName: "binance",
689
+ * note: "Binance cryptocurrency exchange",
690
+ * getCandles: async (symbol, interval, since, limit) => [...],
691
+ * formatPrice: async (symbol, price) => price.toFixed(2),
692
+ * formatQuantity: async (symbol, quantity) => quantity.toFixed(8),
693
+ * });
694
+ *
695
+ * const exchanges = listExchanges();
696
+ * console.log(exchanges);
697
+ * // [{ exchangeName: "binance", note: "Binance cryptocurrency exchange", ... }]
698
+ * ```
699
+ */
700
+ declare function listExchanges(): Promise<IExchangeSchema[]>;
701
+ /**
702
+ * Returns a list of all registered strategy schemas.
703
+ *
704
+ * Retrieves all strategies that have been registered via addStrategy().
705
+ * Useful for debugging, documentation, or building dynamic UIs.
706
+ *
707
+ * @returns Array of strategy schemas with their configurations
708
+ *
709
+ * @example
710
+ * ```typescript
711
+ * import { listStrategies, addStrategy } from "backtest-kit";
712
+ *
713
+ * addStrategy({
714
+ * strategyName: "my-strategy",
715
+ * note: "Simple moving average crossover strategy",
716
+ * interval: "5m",
717
+ * getSignal: async (symbol) => ({
718
+ * position: "long",
719
+ * priceOpen: 50000,
720
+ * priceTakeProfit: 51000,
721
+ * priceStopLoss: 49000,
722
+ * minuteEstimatedTime: 60,
723
+ * }),
724
+ * });
725
+ *
726
+ * const strategies = listStrategies();
727
+ * console.log(strategies);
728
+ * // [{ strategyName: "my-strategy", note: "Simple moving average...", ... }]
729
+ * ```
730
+ */
731
+ declare function listStrategies(): Promise<IStrategySchema[]>;
732
+ /**
733
+ * Returns a list of all registered frame schemas.
734
+ *
735
+ * Retrieves all frames that have been registered via addFrame().
736
+ * Useful for debugging, documentation, or building dynamic UIs.
737
+ *
738
+ * @returns Array of frame schemas with their configurations
739
+ *
740
+ * @example
741
+ * ```typescript
742
+ * import { listFrames, addFrame } from "backtest-kit";
743
+ *
744
+ * addFrame({
745
+ * frameName: "1d-backtest",
746
+ * note: "One day backtest period for testing",
747
+ * interval: "1m",
748
+ * startDate: new Date("2024-01-01T00:00:00Z"),
749
+ * endDate: new Date("2024-01-02T00:00:00Z"),
750
+ * });
751
+ *
752
+ * const frames = listFrames();
753
+ * console.log(frames);
754
+ * // [{ frameName: "1d-backtest", note: "One day backtest...", ... }]
755
+ * ```
756
+ */
757
+ declare function listFrames(): Promise<IFrameSchema[]>;
758
+
648
759
  /**
649
760
  * Contract for background execution completion events.
650
761
  *
@@ -675,6 +786,37 @@ interface DoneContract {
675
786
  symbol: string;
676
787
  }
677
788
 
789
+ /**
790
+ * Contract for backtest progress events.
791
+ *
792
+ * Emitted during Backtest.background() execution to track progress.
793
+ * Contains information about total frames, processed frames, and completion percentage.
794
+ *
795
+ * @example
796
+ * ```typescript
797
+ * import { listenProgress } from "backtest-kit";
798
+ *
799
+ * listenProgress((event) => {
800
+ * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
801
+ * console.log(`Processed: ${event.processedFrames} / ${event.totalFrames}`);
802
+ * });
803
+ * ```
804
+ */
805
+ interface ProgressContract {
806
+ /** exchangeName - Name of the exchange used in execution */
807
+ exchangeName: string;
808
+ /** strategyName - Name of the strategy being executed */
809
+ strategyName: string;
810
+ /** symbol - Trading symbol (e.g., "BTCUSDT") */
811
+ symbol: string;
812
+ /** totalFrames - Total number of frames to process */
813
+ totalFrames: number;
814
+ /** processedFrames - Number of frames processed so far */
815
+ processedFrames: number;
816
+ /** progress - Completion percentage from 0.0 to 1.0 */
817
+ progress: number;
818
+ }
819
+
678
820
  /**
679
821
  * Subscribes to all signal events with queued async processing.
680
822
  *
@@ -903,6 +1045,37 @@ declare function listenDone(fn: (event: DoneContract) => void): () => void;
903
1045
  * ```
904
1046
  */
905
1047
  declare function listenDoneOnce(filterFn: (event: DoneContract) => boolean, fn: (event: DoneContract) => void): () => void;
1048
+ /**
1049
+ * Subscribes to backtest progress events with queued async processing.
1050
+ *
1051
+ * Emits during Backtest.background() execution to track progress.
1052
+ * Events are processed sequentially in order received, even if callback is async.
1053
+ * Uses queued wrapper to prevent concurrent execution of the callback.
1054
+ *
1055
+ * @param fn - Callback function to handle progress events
1056
+ * @returns Unsubscribe function to stop listening to events
1057
+ *
1058
+ * @example
1059
+ * ```typescript
1060
+ * import { listenProgress, Backtest } from "backtest-kit";
1061
+ *
1062
+ * const unsubscribe = listenProgress((event) => {
1063
+ * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
1064
+ * console.log(`${event.processedFrames} / ${event.totalFrames} frames`);
1065
+ * console.log(`Strategy: ${event.strategyName}, Symbol: ${event.symbol}`);
1066
+ * });
1067
+ *
1068
+ * Backtest.background("BTCUSDT", {
1069
+ * strategyName: "my-strategy",
1070
+ * exchangeName: "binance",
1071
+ * frameName: "1d-backtest"
1072
+ * });
1073
+ *
1074
+ * // Later: stop listening
1075
+ * unsubscribe();
1076
+ * ```
1077
+ */
1078
+ declare function listenProgress(fn: (event: ProgressContract) => void): () => void;
906
1079
 
907
1080
  /**
908
1081
  * Fetches historical candle data from the registered exchange.
@@ -1737,6 +1910,25 @@ declare class StrategyConnectionService implements IStrategy {
1737
1910
  * @returns Promise resolving to backtest result (signal or idle)
1738
1911
  */
1739
1912
  backtest: (candles: ICandleData[]) => Promise<IStrategyBacktestResult>;
1913
+ /**
1914
+ * Stops the specified strategy from generating new signals.
1915
+ *
1916
+ * Delegates to ClientStrategy.stop() which sets internal flag to prevent
1917
+ * getSignal from being called on subsequent ticks.
1918
+ *
1919
+ * @param strategyName - Name of strategy to stop
1920
+ * @returns Promise that resolves when stop flag is set
1921
+ */
1922
+ stop: (strategyName: StrategyName) => Promise<void>;
1923
+ /**
1924
+ * Clears the memoized ClientStrategy instance from cache.
1925
+ *
1926
+ * Forces re-initialization of strategy on next getStrategy call.
1927
+ * Useful for resetting strategy state or releasing resources.
1928
+ *
1929
+ * @param strategyName - Name of strategy to clear from cache
1930
+ */
1931
+ clear: (strategyName: StrategyName) => Promise<void>;
1740
1932
  }
1741
1933
 
1742
1934
  /**
@@ -1912,6 +2104,25 @@ declare class StrategyGlobalService {
1912
2104
  * @returns Closed signal result with PNL
1913
2105
  */
1914
2106
  backtest: (symbol: string, candles: ICandleData[], when: Date, backtest: boolean) => Promise<IStrategyBacktestResult>;
2107
+ /**
2108
+ * Stops the strategy from generating new signals.
2109
+ *
2110
+ * Delegates to StrategyConnectionService.stop() to set internal flag.
2111
+ * Does not require execution context.
2112
+ *
2113
+ * @param strategyName - Name of strategy to stop
2114
+ * @returns Promise that resolves when stop flag is set
2115
+ */
2116
+ stop: (strategyName: StrategyName) => Promise<void>;
2117
+ /**
2118
+ * Clears the memoized ClientStrategy instance from cache.
2119
+ *
2120
+ * Delegates to StrategyConnectionService.clear() to remove strategy from cache.
2121
+ * Forces re-initialization of strategy on next operation.
2122
+ *
2123
+ * @param strategyName - Name of strategy to clear from cache
2124
+ */
2125
+ clear: (strategyName: StrategyName) => Promise<void>;
1915
2126
  }
1916
2127
 
1917
2128
  /**
@@ -2066,7 +2277,7 @@ declare class FrameSchemaService {
2066
2277
  * @param value - Partial schema updates
2067
2278
  * @throws Error if frame name doesn't exist
2068
2279
  */
2069
- override(key: FrameName, value: Partial<IFrameSchema>): void;
2280
+ override(key: FrameName, value: Partial<IFrameSchema>): IFrameSchema;
2070
2281
  /**
2071
2282
  * Retrieves a frame schema by name.
2072
2283
  *
@@ -2095,6 +2306,7 @@ declare class BacktestLogicPrivateService {
2095
2306
  private readonly strategyGlobalService;
2096
2307
  private readonly exchangeGlobalService;
2097
2308
  private readonly frameGlobalService;
2309
+ private readonly methodContextService;
2098
2310
  /**
2099
2311
  * Runs backtest for a symbol, streaming closed signals as async generator.
2100
2312
  *
@@ -2583,6 +2795,12 @@ declare class ExchangeValidationService {
2583
2795
  * Memoized function to cache validation results
2584
2796
  */
2585
2797
  validate: (exchangeName: ExchangeName, source: string) => void;
2798
+ /**
2799
+ * Returns a list of all registered exchange schemas
2800
+ * @public
2801
+ * @returns Array of exchange schemas with their configurations
2802
+ */
2803
+ list: () => Promise<IExchangeSchema[]>;
2586
2804
  }
2587
2805
 
2588
2806
  /**
@@ -2614,6 +2832,12 @@ declare class StrategyValidationService {
2614
2832
  * Memoized function to cache validation results
2615
2833
  */
2616
2834
  validate: (strategyName: StrategyName, source: string) => void;
2835
+ /**
2836
+ * Returns a list of all registered strategy schemas
2837
+ * @public
2838
+ * @returns Array of strategy schemas with their configurations
2839
+ */
2840
+ list: () => Promise<IStrategySchema[]>;
2617
2841
  }
2618
2842
 
2619
2843
  /**
@@ -2645,6 +2869,12 @@ declare class FrameValidationService {
2645
2869
  * Memoized function to cache validation results
2646
2870
  */
2647
2871
  validate: (frameName: FrameName, source: string) => void;
2872
+ /**
2873
+ * Returns a list of all registered frame schemas
2874
+ * @public
2875
+ * @returns Array of frame schemas with their configurations
2876
+ */
2877
+ list: () => Promise<IFrameSchema[]>;
2648
2878
  }
2649
2879
 
2650
2880
  declare const backtest: {
@@ -2677,4 +2907,4 @@ declare const backtest: {
2677
2907
  loggerService: LoggerService;
2678
2908
  };
2679
2909
 
2680
- export { Backtest, type CandleInterval, type EntityId, ExecutionContextService, type FrameInterval, type ICandleData, type IExchangeSchema, type IFrameSchema, type IPersistBase, type ISignalData, type ISignalDto, type ISignalRow, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, Live, MethodContextService, PersistBase, PersistSignalAdaper, type SignalInterval, type TPersistBase, type TPersistBaseCtor, addExchange, addFrame, addStrategy, formatPrice, formatQuantity, getAveragePrice, getCandles, getDate, getMode, backtest as lib, listenDone, listenDoneOnce, listenError, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, setLogger };
2910
+ export { Backtest, type CandleInterval, type DoneContract, type EntityId, ExecutionContextService, type FrameInterval, type ICandleData, type IExchangeSchema, type IFrameSchema, type IPersistBase, type ISignalData, type ISignalDto, type ISignalRow, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, Live, MethodContextService, PersistBase, PersistSignalAdaper, type ProgressContract, type SignalInterval, type TPersistBase, type TPersistBaseCtor, addExchange, addFrame, addStrategy, formatPrice, formatQuantity, getAveragePrice, getCandles, getDate, getMode, backtest as lib, listExchanges, listFrames, listStrategies, listenDone, listenDoneOnce, listenError, listenProgress, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, setLogger };