backtest-kit 2.1.1 → 2.1.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backtest-kit",
3
- "version": "2.1.1",
3
+ "version": "2.1.2",
4
4
  "description": "A TypeScript library for trading system backtest",
5
5
  "author": {
6
6
  "name": "Petr Tripolsky",
package/types.d.ts CHANGED
@@ -7665,8 +7665,8 @@ interface IEntity {
7665
7665
  * Custom adapters should implement this interface.
7666
7666
  *
7667
7667
  * Architecture:
7668
- * - IPersistBase: Public API for custom adapters (4 methods: waitForInit, readValue, hasValue, writeValue)
7669
- * - PersistBase: Default implementation with internal keys() method for validation
7668
+ * - IPersistBase: Public API for custom adapters (5 methods: waitForInit, readValue, hasValue, writeValue, keys)
7669
+ * - PersistBase: Default implementation with keys() method for validation and iteration
7670
7670
  * - TPersistBaseCtor: Constructor type requiring IPersistBase
7671
7671
  */
7672
7672
  interface IPersistBase<Entity extends IEntity | null = IEntity> {
@@ -7702,6 +7702,15 @@ interface IPersistBase<Entity extends IEntity | null = IEntity> {
7702
7702
  * @throws Error if write fails
7703
7703
  */
7704
7704
  writeValue(entityId: EntityId, entity: Entity): Promise<void>;
7705
+ /**
7706
+ * Async generator yielding all entity IDs.
7707
+ * Sorted alphanumerically.
7708
+ * Used for iteration and validation.
7709
+ *
7710
+ * @returns AsyncGenerator yielding entity IDs
7711
+ * @throws Error if reading fails
7712
+ */
7713
+ keys(): AsyncGenerator<EntityId>;
7705
7714
  }
7706
7715
  /**
7707
7716
  * Base class for file-based persistence with atomic writes.
@@ -8221,6 +8230,82 @@ declare class PersistBreakevenUtils {
8221
8230
  * ```
8222
8231
  */
8223
8232
  declare const PersistBreakevenAdapter: PersistBreakevenUtils;
8233
+ /**
8234
+ * Type for persisted candle cache data.
8235
+ * Each candle is stored as a separate JSON file.
8236
+ */
8237
+ type CandleData = ICandleData;
8238
+ /**
8239
+ * Utility class for managing candles cache persistence.
8240
+ *
8241
+ * Features:
8242
+ * - Each candle stored as separate JSON file: ${exchangeName}/${symbol}/${interval}/${timestamp}.json
8243
+ * - Cache validation: returns cached data if file count matches requested limit
8244
+ * - Automatic cache invalidation and refresh when data is incomplete
8245
+ * - Atomic read/write operations
8246
+ *
8247
+ * Used by ClientExchange for candle data caching.
8248
+ */
8249
+ declare class PersistCandleUtils {
8250
+ private PersistCandlesFactory;
8251
+ private getCandlesStorage;
8252
+ /**
8253
+ * Registers a custom persistence adapter.
8254
+ *
8255
+ * @param Ctor - Custom PersistBase constructor
8256
+ */
8257
+ usePersistCandleAdapter(Ctor: TPersistBaseCtor<string, CandleData>): void;
8258
+ /**
8259
+ * Reads cached candles for a specific exchange, symbol, and interval.
8260
+ * Returns candles only if cache contains exactly the requested limit.
8261
+ *
8262
+ * @param symbol - Trading pair symbol
8263
+ * @param interval - Candle interval
8264
+ * @param exchangeName - Exchange identifier
8265
+ * @param limit - Number of candles requested
8266
+ * @param sinceTimestamp - Start timestamp (inclusive)
8267
+ * @param untilTimestamp - End timestamp (exclusive)
8268
+ * @returns Promise resolving to array of candles or null if cache is incomplete
8269
+ */
8270
+ readCandlesData: (symbol: string, interval: CandleInterval, exchangeName: ExchangeName, limit: number, sinceTimestamp: number, untilTimestamp: number) => Promise<CandleData[] | null>;
8271
+ /**
8272
+ * Writes candles to cache with atomic file writes.
8273
+ * Each candle is stored as a separate JSON file named by its timestamp.
8274
+ *
8275
+ * @param candles - Array of candle data to cache
8276
+ * @param symbol - Trading pair symbol
8277
+ * @param interval - Candle interval
8278
+ * @param exchangeName - Exchange identifier
8279
+ * @returns Promise that resolves when all writes are complete
8280
+ */
8281
+ writeCandlesData: (candles: CandleData[], symbol: string, interval: CandleInterval, exchangeName: ExchangeName) => Promise<void>;
8282
+ /**
8283
+ * Switches to the default JSON persist adapter.
8284
+ * All future persistence writes will use JSON storage.
8285
+ */
8286
+ useJson(): void;
8287
+ /**
8288
+ * Switches to a dummy persist adapter that discards all writes.
8289
+ * All future persistence writes will be no-ops.
8290
+ */
8291
+ useDummy(): void;
8292
+ }
8293
+ /**
8294
+ * Global singleton instance of PersistCandleUtils.
8295
+ * Used by ClientExchange for candle data caching.
8296
+ *
8297
+ * @example
8298
+ * ```typescript
8299
+ * // Read cached candles
8300
+ * const candles = await PersistCandleAdapter.readCandlesData(
8301
+ * "BTCUSDT", "1m", "binance", 100, since.getTime(), until.getTime()
8302
+ * );
8303
+ *
8304
+ * // Write candles to cache
8305
+ * await PersistCandleAdapter.writeCandlesData(candles, "BTCUSDT", "1m", "binance");
8306
+ * ```
8307
+ */
8308
+ declare const PersistCandleAdapter: PersistCandleUtils;
8224
8309
 
8225
8310
  declare const WAIT_FOR_INIT_SYMBOL$1: unique symbol;
8226
8311
  declare const WRITE_SAFE_SYMBOL$1: unique symbol;
@@ -12655,7 +12740,7 @@ declare class ExchangeUtils {
12655
12740
  */
12656
12741
  getCandles: (symbol: string, interval: CandleInterval, limit: number, context: {
12657
12742
  exchangeName: ExchangeName;
12658
- }) => Promise<ICandleData[]>;
12743
+ }) => Promise<any>;
12659
12744
  /**
12660
12745
  * Calculates VWAP (Volume Weighted Average Price) from last N 1m candles.
12661
12746
  *
@@ -14333,6 +14418,35 @@ declare class ClientExchange implements IExchange {
14333
14418
  * @returns Promise resolving to formatted price as string
14334
14419
  */
14335
14420
  formatPrice(symbol: string, price: number): Promise<string>;
14421
+ /**
14422
+ * Fetches raw candles with flexible date/limit parameters.
14423
+ *
14424
+ * Compatibility layer that:
14425
+ * - RAW MODE (sDate + eDate + limit): fetches exactly as specified, NO look-ahead bias protection
14426
+ * - Other modes: respects execution context and prevents look-ahead bias
14427
+ *
14428
+ * Parameter combinations:
14429
+ * 1. sDate + eDate + limit: RAW MODE - fetches exactly as specified, no validation against when
14430
+ * 2. sDate + eDate: calculates limit from date range, validates endTimestamp <= when
14431
+ * 3. eDate + limit: calculates sDate backward, validates endTimestamp <= when
14432
+ * 4. sDate + limit: fetches forward, validates endTimestamp <= when
14433
+ * 5. Only limit: uses execution.context.when as reference (backward)
14434
+ *
14435
+ * Edge cases:
14436
+ * - If calculated limit is 0 or negative: throws error
14437
+ * - If sDate >= eDate: throws error
14438
+ * - If startTimestamp >= endTimestamp: throws error
14439
+ * - If endTimestamp > when (non-RAW modes only): throws error to prevent look-ahead bias
14440
+ *
14441
+ * @param symbol - Trading pair symbol
14442
+ * @param interval - Candle interval
14443
+ * @param limit - Optional number of candles to fetch
14444
+ * @param sDate - Optional start date in milliseconds
14445
+ * @param eDate - Optional end date in milliseconds
14446
+ * @returns Promise resolving to array of candles
14447
+ * @throws Error if parameters are invalid or conflicting
14448
+ */
14449
+ getRawCandles(symbol: string, interval: CandleInterval, limit?: number, sDate?: number, eDate?: number): Promise<ICandleData[]>;
14336
14450
  /**
14337
14451
  * Fetches order book for a trading pair.
14338
14452
  *
@@ -19341,4 +19455,4 @@ declare const backtest: {
19341
19455
  loggerService: LoggerService;
19342
19456
  };
19343
19457
 
19344
- export { ActionBase, type ActivePingContract, Backtest, type BacktestDoneNotification, type BacktestStatisticsModel, 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 IBidData, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IMarkdownDumpOptions, type IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, 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 LiveDoneNotification, type LiveStatisticsModel, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, 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, PositionSize, type ProgressBacktestContract, type ProgressBacktestNotification, type ProgressOptimizerContract, 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, type TMarkdownBase, type TPersistBase, type TPersistBaseCtor, type TReportBase, type TickEvent, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addActionSchema, addExchangeSchema, addFrameSchema, addOptimizerSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, commitBreakeven, commitCancelScheduled, commitClosePending, commitPartialLoss, commitPartialProfit, commitSignalPromptHistory, commitTrailingStop, commitTrailingTake, dumpSignalData, emitters, formatPrice, formatQuantity, get, getActionSchema, getAveragePrice, getBacktestTimeframe, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getExchangeSchema, getFrameSchema, getMode, getOptimizerSchema, getOrderBook, getRiskSchema, getSizingSchema, getStrategySchema, getSymbol, getWalkerSchema, hasTradeContext, backtest as lib, listExchangeSchema, listFrameSchema, listOptimizerSchema, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenOptimizerProgress, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideOptimizerSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, roundTicks, set, setColumns, setConfig, setLogger, stopStrategy, validate };
19458
+ export { ActionBase, type ActivePingContract, Backtest, type BacktestDoneNotification, type BacktestStatisticsModel, Breakeven, 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 IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, 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 LiveDoneNotification, type LiveStatisticsModel, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, 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, PersistCandleAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, type ProgressBacktestContract, type ProgressBacktestNotification, type ProgressOptimizerContract, 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, type TMarkdownBase, type TPersistBase, type TPersistBaseCtor, type TReportBase, type TickEvent, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addActionSchema, addExchangeSchema, addFrameSchema, addOptimizerSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, commitBreakeven, commitCancelScheduled, commitClosePending, commitPartialLoss, commitPartialProfit, commitSignalPromptHistory, commitTrailingStop, commitTrailingTake, dumpSignalData, emitters, formatPrice, formatQuantity, get, getActionSchema, getAveragePrice, getBacktestTimeframe, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getExchangeSchema, getFrameSchema, getMode, getOptimizerSchema, getOrderBook, getRiskSchema, getSizingSchema, getStrategySchema, getSymbol, getWalkerSchema, hasTradeContext, backtest as lib, listExchangeSchema, listFrameSchema, listOptimizerSchema, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenOptimizerProgress, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideOptimizerSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, roundTicks, set, setColumns, setConfig, setLogger, stopStrategy, validate };