backtest-kit 1.5.12 → 1.5.13

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
@@ -13,10 +13,30 @@ declare const GLOBAL_CONFIG: {
13
13
  * Default: 5 candles (last 5 minutes when using 1m interval)
14
14
  */
15
15
  CC_AVG_PRICE_CANDLES_COUNT: number;
16
+ /**
17
+ * Slippage percentage applied to entry and exit prices.
18
+ * Simulates market impact and order book depth.
19
+ * Applied twice (entry and exit) for realistic execution simulation.
20
+ * Default: 0.1% per transaction
21
+ */
22
+ CC_PERCENT_SLIPPAGE: number;
23
+ /**
24
+ * Fee percentage charged per transaction.
25
+ * Applied twice (entry and exit) for total fee calculation.
26
+ * Default: 0.1% per transaction (total 0.2%)
27
+ */
28
+ CC_PERCENT_FEE: number;
16
29
  /**
17
30
  * Minimum TakeProfit distance from priceOpen (percentage)
18
- * Must be greater than trading fees to ensure profitable trades
19
- * Default: 0.3% (covers 2×0.1% fees + minimum profit margin)
31
+ * Must be greater than (slippage + fees) to ensure profitable trades
32
+ *
33
+ * Calculation:
34
+ * - Slippage effect: ~0.2% (0.1% × 2 transactions)
35
+ * - Fees: 0.2% (0.1% × 2 transactions)
36
+ * - Minimum profit buffer: 0.1%
37
+ * - Total: 0.5%
38
+ *
39
+ * Default: 0.5% (covers all costs + minimum profit margin)
20
40
  */
21
41
  CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
22
42
  /**
@@ -135,7 +155,7 @@ interface ILogger {
135
155
  * });
136
156
  * ```
137
157
  */
138
- declare function setLogger(logger: ILogger): Promise<void>;
158
+ declare function setLogger(logger: ILogger): void;
139
159
  /**
140
160
  * Sets global configuration parameters for the framework.
141
161
  * @param config - Partial configuration object to override default settings
@@ -147,7 +167,65 @@ declare function setLogger(logger: ILogger): Promise<void>;
147
167
  * });
148
168
  * ```
149
169
  */
150
- declare function setConfig(config: Partial<GlobalConfig>): Promise<void>;
170
+ declare function setConfig(config: Partial<GlobalConfig>, _unsafe?: boolean): void;
171
+ /**
172
+ * Retrieves a copy of the current global configuration.
173
+ *
174
+ * Returns a shallow copy of the current GLOBAL_CONFIG to prevent accidental mutations.
175
+ * Use this to inspect the current configuration state without modifying it.
176
+ *
177
+ * @returns {GlobalConfig} A copy of the current global configuration object
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * const currentConfig = getConfig();
182
+ * console.log(currentConfig.CC_SCHEDULE_AWAIT_MINUTES);
183
+ * ```
184
+ */
185
+ declare function getConfig(): {
186
+ CC_SCHEDULE_AWAIT_MINUTES: number;
187
+ CC_AVG_PRICE_CANDLES_COUNT: number;
188
+ CC_PERCENT_SLIPPAGE: number;
189
+ CC_PERCENT_FEE: number;
190
+ CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
191
+ CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
192
+ CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
193
+ CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
194
+ CC_MAX_SIGNAL_GENERATION_SECONDS: number;
195
+ CC_GET_CANDLES_RETRY_COUNT: number;
196
+ CC_GET_CANDLES_RETRY_DELAY_MS: number;
197
+ CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
198
+ CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
199
+ };
200
+ /**
201
+ * Retrieves the default configuration object for the framework.
202
+ *
203
+ * Returns a reference to the default configuration with all preset values.
204
+ * Use this to see what configuration options are available and their default values.
205
+ *
206
+ * @returns {GlobalConfig} The default configuration object
207
+ *
208
+ * @example
209
+ * ```typescript
210
+ * const defaultConfig = getDefaultConfig();
211
+ * console.log(defaultConfig.CC_SCHEDULE_AWAIT_MINUTES);
212
+ * ```
213
+ */
214
+ declare function getDefaultConfig(): Readonly<{
215
+ CC_SCHEDULE_AWAIT_MINUTES: number;
216
+ CC_AVG_PRICE_CANDLES_COUNT: number;
217
+ CC_PERCENT_SLIPPAGE: number;
218
+ CC_PERCENT_FEE: number;
219
+ CC_MIN_TAKEPROFIT_DISTANCE_PERCENT: number;
220
+ CC_MIN_STOPLOSS_DISTANCE_PERCENT: number;
221
+ CC_MAX_STOPLOSS_DISTANCE_PERCENT: number;
222
+ CC_MAX_SIGNAL_LIFETIME_MINUTES: number;
223
+ CC_MAX_SIGNAL_GENERATION_SECONDS: number;
224
+ CC_GET_CANDLES_RETRY_COUNT: number;
225
+ CC_GET_CANDLES_RETRY_DELAY_MS: number;
226
+ CC_GET_CANDLES_PRICE_ANOMALY_THRESHOLD_FACTOR: number;
227
+ CC_GET_CANDLES_MIN_CANDLES_FOR_MEDIAN: number;
228
+ }>;
151
229
 
152
230
  /**
153
231
  * Execution context containing runtime parameters for strategy/exchange operations.
@@ -8194,8 +8272,27 @@ declare class HeatMarkdownService {
8194
8272
  }
8195
8273
 
8196
8274
  /**
8197
- * @class ExchangeValidationService
8198
- * Service for managing and validating exchange configurations
8275
+ * Service for managing and validating exchange configurations.
8276
+ *
8277
+ * Maintains a registry of all configured exchanges and validates
8278
+ * their existence before operations. Uses memoization for performance.
8279
+ *
8280
+ * Key features:
8281
+ * - Registry management: addExchange() to register new exchanges
8282
+ * - Validation: validate() ensures exchange exists before use
8283
+ * - Memoization: validation results are cached for performance
8284
+ * - Listing: list() returns all registered exchanges
8285
+ *
8286
+ * @throws {Error} If duplicate exchange name is added
8287
+ * @throws {Error} If unknown exchange is referenced
8288
+ *
8289
+ * @example
8290
+ * ```typescript
8291
+ * const exchangeValidation = new ExchangeValidationService();
8292
+ * exchangeValidation.addExchange("binance", binanceSchema);
8293
+ * exchangeValidation.validate("binance", "backtest"); // OK
8294
+ * exchangeValidation.validate("unknown", "live"); // Throws error
8295
+ * ```
8199
8296
  */
8200
8297
  declare class ExchangeValidationService {
8201
8298
  /**
@@ -8231,8 +8328,29 @@ declare class ExchangeValidationService {
8231
8328
  }
8232
8329
 
8233
8330
  /**
8234
- * @class StrategyValidationService
8235
- * Service for managing and validating strategy configurations
8331
+ * Service for managing and validating trading strategy configurations.
8332
+ *
8333
+ * Maintains a registry of all configured strategies, validates their existence
8334
+ * before operations, and ensures associated risk profiles are valid.
8335
+ * Uses memoization for performance.
8336
+ *
8337
+ * Key features:
8338
+ * - Registry management: addStrategy() to register new strategies
8339
+ * - Dual validation: validates both strategy existence and risk profile (if configured)
8340
+ * - Memoization: validation results are cached for performance
8341
+ * - Listing: list() returns all registered strategies
8342
+ *
8343
+ * @throws {Error} If duplicate strategy name is added
8344
+ * @throws {Error} If unknown strategy is referenced
8345
+ * @throws {Error} If strategy's risk profile doesn't exist
8346
+ *
8347
+ * @example
8348
+ * ```typescript
8349
+ * const strategyValidation = new StrategyValidationService();
8350
+ * strategyValidation.addStrategy("momentum-btc", { ...schema, riskName: "conservative" });
8351
+ * strategyValidation.validate("momentum-btc", "backtest"); // Validates strategy + risk
8352
+ * strategyValidation.validate("unknown", "live"); // Throws error
8353
+ * ```
8236
8354
  */
8237
8355
  declare class StrategyValidationService {
8238
8356
  /**
@@ -8275,8 +8393,27 @@ declare class StrategyValidationService {
8275
8393
  }
8276
8394
 
8277
8395
  /**
8278
- * @class FrameValidationService
8279
- * Service for managing and validating frame configurations
8396
+ * Service for managing and validating frame (timeframe) configurations.
8397
+ *
8398
+ * Maintains a registry of all configured frames and validates
8399
+ * their existence before operations. Uses memoization for performance.
8400
+ *
8401
+ * Key features:
8402
+ * - Registry management: addFrame() to register new timeframes
8403
+ * - Validation: validate() ensures frame exists before use
8404
+ * - Memoization: validation results are cached for performance
8405
+ * - Listing: list() returns all registered frames
8406
+ *
8407
+ * @throws {Error} If duplicate frame name is added
8408
+ * @throws {Error} If unknown frame is referenced
8409
+ *
8410
+ * @example
8411
+ * ```typescript
8412
+ * const frameValidation = new FrameValidationService();
8413
+ * frameValidation.addFrame("2024-Q1", frameSchema);
8414
+ * frameValidation.validate("2024-Q1", "backtest"); // OK
8415
+ * frameValidation.validate("unknown", "live"); // Throws error
8416
+ * ```
8280
8417
  */
8281
8418
  declare class FrameValidationService {
8282
8419
  /**
@@ -8312,8 +8449,29 @@ declare class FrameValidationService {
8312
8449
  }
8313
8450
 
8314
8451
  /**
8315
- * @class WalkerValidationService
8316
- * Service for managing and validating walker configurations
8452
+ * Service for managing and validating walker (parameter sweep) configurations.
8453
+ *
8454
+ * Maintains a registry of all configured walkers and validates
8455
+ * their existence before operations. Uses memoization for performance.
8456
+ *
8457
+ * Walkers define parameter ranges for optimization and hyperparameter tuning.
8458
+ *
8459
+ * Key features:
8460
+ * - Registry management: addWalker() to register new walker configurations
8461
+ * - Validation: validate() ensures walker exists before use
8462
+ * - Memoization: validation results are cached for performance
8463
+ * - Listing: list() returns all registered walkers
8464
+ *
8465
+ * @throws {Error} If duplicate walker name is added
8466
+ * @throws {Error} If unknown walker is referenced
8467
+ *
8468
+ * @example
8469
+ * ```typescript
8470
+ * const walkerValidation = new WalkerValidationService();
8471
+ * walkerValidation.addWalker("rsi-sweep", walkerSchema);
8472
+ * walkerValidation.validate("rsi-sweep", "optimizer"); // OK
8473
+ * walkerValidation.validate("unknown", "optimizer"); // Throws error
8474
+ * ```
8317
8475
  */
8318
8476
  declare class WalkerValidationService {
8319
8477
  /**
@@ -8349,8 +8507,27 @@ declare class WalkerValidationService {
8349
8507
  }
8350
8508
 
8351
8509
  /**
8352
- * @class SizingValidationService
8353
- * Service for managing and validating sizing configurations
8510
+ * Service for managing and validating position sizing configurations.
8511
+ *
8512
+ * Maintains a registry of all configured sizing strategies and validates
8513
+ * their existence before operations. Uses memoization for performance.
8514
+ *
8515
+ * Key features:
8516
+ * - Registry management: addSizing() to register new sizing strategies
8517
+ * - Validation: validate() ensures sizing strategy exists before use
8518
+ * - Memoization: validation results are cached for performance
8519
+ * - Listing: list() returns all registered sizing strategies
8520
+ *
8521
+ * @throws {Error} If duplicate sizing name is added
8522
+ * @throws {Error} If unknown sizing strategy is referenced
8523
+ *
8524
+ * @example
8525
+ * ```typescript
8526
+ * const sizingValidation = new SizingValidationService();
8527
+ * sizingValidation.addSizing("fixed-1000", fixedSizingSchema);
8528
+ * sizingValidation.validate("fixed-1000", "strategy-1"); // OK
8529
+ * sizingValidation.validate("unknown", "strategy-2"); // Throws error
8530
+ * ```
8354
8531
  */
8355
8532
  declare class SizingValidationService {
8356
8533
  /**
@@ -8387,8 +8564,27 @@ declare class SizingValidationService {
8387
8564
  }
8388
8565
 
8389
8566
  /**
8390
- * @class RiskValidationService
8391
- * Service for managing and validating risk configurations
8567
+ * Service for managing and validating risk management configurations.
8568
+ *
8569
+ * Maintains a registry of all configured risk profiles and validates
8570
+ * their existence before operations. Uses memoization for performance.
8571
+ *
8572
+ * Key features:
8573
+ * - Registry management: addRisk() to register new risk profiles
8574
+ * - Validation: validate() ensures risk profile exists before use
8575
+ * - Memoization: validation results are cached by riskName:source for performance
8576
+ * - Listing: list() returns all registered risk profiles
8577
+ *
8578
+ * @throws {Error} If duplicate risk name is added
8579
+ * @throws {Error} If unknown risk profile is referenced
8580
+ *
8581
+ * @example
8582
+ * ```typescript
8583
+ * const riskValidation = new RiskValidationService();
8584
+ * riskValidation.addRisk("conservative", conservativeSchema);
8585
+ * riskValidation.validate("conservative", "strategy-1"); // OK
8586
+ * riskValidation.validate("unknown", "strategy-2"); // Throws error
8587
+ * ```
8392
8588
  */
8393
8589
  declare class RiskValidationService {
8394
8590
  /**
@@ -9019,6 +9215,57 @@ declare class OutlineMarkdownService {
9019
9215
  dumpSignal: (signalId: ResultId, history: MessageModel[], signal: ISignalDto, outputDir?: string) => Promise<void>;
9020
9216
  }
9021
9217
 
9218
+ /**
9219
+ * Service for validating GLOBAL_CONFIG parameters to ensure mathematical correctness
9220
+ * and prevent unprofitable trading configurations.
9221
+ *
9222
+ * Performs comprehensive validation on:
9223
+ * - **Percentage parameters**: Slippage, fees, and profit margins must be non-negative
9224
+ * - **Economic viability**: Ensures CC_MIN_TAKEPROFIT_DISTANCE_PERCENT covers all trading costs
9225
+ * (slippage + fees) to guarantee profitable trades when TakeProfit is hit
9226
+ * - **Range constraints**: Validates MIN < MAX relationships (e.g., StopLoss distances)
9227
+ * - **Time-based parameters**: Ensures positive integer values for timeouts and lifetimes
9228
+ * - **Candle parameters**: Validates retry counts, delays, and anomaly detection thresholds
9229
+ *
9230
+ * @throws {Error} If any validation fails, throws with detailed breakdown of all errors
9231
+ *
9232
+ * @example
9233
+ * ```typescript
9234
+ * const validator = new ConfigValidationService();
9235
+ * validator.validate(); // Throws if config is invalid
9236
+ * ```
9237
+ *
9238
+ * @example Validation failure output:
9239
+ * ```
9240
+ * GLOBAL_CONFIG validation failed:
9241
+ * 1. CC_MIN_TAKEPROFIT_DISTANCE_PERCENT (0.3%) is too low to cover trading costs.
9242
+ * Required minimum: 0.40%
9243
+ * Breakdown:
9244
+ * - Slippage effect: 0.20% (0.1% × 2 transactions)
9245
+ * - Fees: 0.20% (0.1% × 2 transactions)
9246
+ * All TakeProfit signals will be unprofitable with current settings!
9247
+ * ```
9248
+ */
9249
+ declare class ConfigValidationService {
9250
+ /**
9251
+ * @private
9252
+ * @readonly
9253
+ * Injected logger service instance
9254
+ */
9255
+ private readonly loggerService;
9256
+ /**
9257
+ * Validates GLOBAL_CONFIG parameters for mathematical correctness.
9258
+ *
9259
+ * Checks:
9260
+ * 1. CC_MIN_TAKEPROFIT_DISTANCE_PERCENT must cover slippage + fees
9261
+ * 2. All percentage values must be positive
9262
+ * 3. Time/count values must be positive integers
9263
+ *
9264
+ * @throws Error if configuration is invalid
9265
+ */
9266
+ validate: () => void;
9267
+ }
9268
+
9022
9269
  declare const backtest: {
9023
9270
  optimizerTemplateService: OptimizerTemplateService;
9024
9271
  exchangeValidationService: ExchangeValidationService;
@@ -9028,6 +9275,7 @@ declare const backtest: {
9028
9275
  sizingValidationService: SizingValidationService;
9029
9276
  riskValidationService: RiskValidationService;
9030
9277
  optimizerValidationService: OptimizerValidationService;
9278
+ configValidationService: ConfigValidationService;
9031
9279
  backtestMarkdownService: BacktestMarkdownService;
9032
9280
  liveMarkdownService: LiveMarkdownService;
9033
9281
  scheduleMarkdownService: ScheduleMarkdownService;
@@ -9075,4 +9323,4 @@ declare const backtest: {
9075
9323
  loggerService: LoggerService;
9076
9324
  };
9077
9325
 
9078
- export { Backtest, type BacktestStatistics, type CandleInterval, Constant, type DoneContract, type EntityId, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IHeatmapStatistics, 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 IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, Live, type LiveStatistics, type MessageModel, type MessageRole, MethodContextService, Optimizer, Partial$1 as Partial, type PartialData, type PartialLossContract, type PartialProfitContract, type PartialStatistics, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatistics, PersistBase, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, type ProgressBacktestContract, type ProgressOptimizerContract, type ProgressWalkerContract, type RiskData, Schedule, type ScheduleData, type ScheduleStatistics, type SignalData, type SignalInterval, type TPersistBase, type TPersistBaseCtor, Walker, type WalkerContract, type WalkerMetric, type WalkerStatistics, addExchange, addFrame, addOptimizer, addRisk, addSizing, addStrategy, addWalker, dumpSignal, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getDate, getMode, 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, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, setConfig, setLogger };
9326
+ export { Backtest, type BacktestStatistics, type CandleInterval, Constant, type DoneContract, type EntityId, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IHeatmapStatistics, 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 IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, Live, type LiveStatistics, type MessageModel, type MessageRole, MethodContextService, Optimizer, Partial$1 as Partial, type PartialData, type PartialLossContract, type PartialProfitContract, type PartialStatistics, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatistics, PersistBase, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, type ProgressBacktestContract, type ProgressOptimizerContract, type ProgressWalkerContract, type RiskData, Schedule, type ScheduleData, type ScheduleStatistics, type SignalData, type SignalInterval, type TPersistBase, type TPersistBaseCtor, Walker, type WalkerContract, type WalkerMetric, type WalkerStatistics, addExchange, addFrame, addOptimizer, addRisk, addSizing, addStrategy, addWalker, dumpSignal, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getConfig, getDate, getDefaultConfig, getMode, 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, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, setConfig, setLogger };