backtest-kit 2.0.5 → 2.0.7

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/build/index.cjs CHANGED
@@ -8,6 +8,7 @@ var path = require('path');
8
8
  var crypto = require('crypto');
9
9
  var os = require('os');
10
10
  var fs$1 = require('fs');
11
+ var util = require('util');
11
12
 
12
13
  function _interopNamespaceDefault(e) {
13
14
  var n = Object.create(null);
@@ -752,7 +753,7 @@ class ClientExchange {
752
753
  limit,
753
754
  });
754
755
  const step = INTERVAL_MINUTES$4[interval];
755
- const adjust = step * limit - step;
756
+ const adjust = step * limit;
756
757
  if (!adjust) {
757
758
  throw new Error(`ClientExchange unknown time adjust for interval=${interval}`);
758
759
  }
@@ -779,7 +780,8 @@ class ClientExchange {
779
780
  // Filter candles to strictly match the requested range
780
781
  const whenTimestamp = this.params.execution.context.when.getTime();
781
782
  const sinceTimestamp = since.getTime();
782
- const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp <= whenTimestamp);
783
+ const stepMs = step * 60 * 1000;
784
+ const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp < whenTimestamp + stepMs);
783
785
  // Apply distinct by timestamp to remove duplicates
784
786
  const uniqueData = Array.from(new Map(filteredData.map((candle) => [candle.timestamp, candle])).values());
785
787
  if (filteredData.length !== uniqueData.length) {
@@ -841,14 +843,18 @@ class ClientExchange {
841
843
  }
842
844
  // Filter candles to strictly match the requested range
843
845
  const sinceTimestamp = since.getTime();
844
- const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp <= endTime);
846
+ const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp < endTime);
845
847
  // Apply distinct by timestamp to remove duplicates
846
848
  const uniqueData = Array.from(new Map(filteredData.map((candle) => [candle.timestamp, candle])).values());
847
849
  if (filteredData.length !== uniqueData.length) {
848
- this.params.logger.warn(`ClientExchange getNextCandles: Removed ${filteredData.length - uniqueData.length} duplicate candles by timestamp`);
850
+ const msg = `ClientExchange getNextCandles: Removed ${filteredData.length - uniqueData.length} duplicate candles by timestamp`;
851
+ this.params.logger.warn(msg);
852
+ console.warn(msg);
849
853
  }
850
854
  if (uniqueData.length < limit) {
851
- this.params.logger.warn(`ClientExchange getNextCandles: Expected ${limit} candles, got ${uniqueData.length}`);
855
+ const msg = `ClientExchange getNextCandles: Expected ${limit} candles, got ${uniqueData.length}`;
856
+ this.params.logger.warn(msg);
857
+ console.warn(msg);
852
858
  }
853
859
  await CALL_CANDLE_DATA_CALLBACKS_FN(this, symbol, interval, since, limit, uniqueData);
854
860
  return uniqueData;
@@ -10027,9 +10033,9 @@ const VALIDATE_CLASS_METHODS = (actionName, handler, self) => {
10027
10033
  `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10028
10034
  ];
10029
10035
  if (suggestions.length > 0) {
10030
- lines.push("");
10036
+ lines.push(functoolsKit.typo.nbsp);
10031
10037
  lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10032
- lines.push("");
10038
+ lines.push(functoolsKit.typo.nbsp);
10033
10039
  }
10034
10040
  lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10035
10041
  const msg = functoolsKit.str.newline(lines);
@@ -10067,9 +10073,9 @@ const VALIDATE_OBJECT_METHODS = (actionName, handler, self) => {
10067
10073
  `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10068
10074
  ];
10069
10075
  if (suggestions.length > 0) {
10070
- lines.push("");
10076
+ lines.push(functoolsKit.typo.nbsp);
10071
10077
  lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10072
- lines.push("");
10078
+ lines.push(functoolsKit.typo.nbsp);
10073
10079
  }
10074
10080
  lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10075
10081
  const msg = functoolsKit.str.newline(lines);
@@ -10520,7 +10526,7 @@ class BacktestLogicPrivateService {
10520
10526
  // Запрашиваем minuteEstimatedTime + буфер свечей одним запросом
10521
10527
  const bufferMinutes = GLOBAL_CONFIG.CC_AVG_PRICE_CANDLES_COUNT - 1;
10522
10528
  const bufferStartTime = new Date(when.getTime() - bufferMinutes * 60 * 1000);
10523
- const totalCandles = signal.minuteEstimatedTime + bufferMinutes;
10529
+ const totalCandles = signal.minuteEstimatedTime + GLOBAL_CONFIG.CC_AVG_PRICE_CANDLES_COUNT;
10524
10530
  let candles;
10525
10531
  try {
10526
10532
  candles = await this.exchangeCoreService.getNextCandles(symbol, "1m", totalCandles, bufferStartTime, true);
@@ -30073,7 +30079,7 @@ class ExchangeInstance {
30073
30079
  });
30074
30080
  const getCandles = this._methods.getCandles;
30075
30081
  const step = INTERVAL_MINUTES$1[interval];
30076
- const adjust = step * limit - step;
30082
+ const adjust = step * limit;
30077
30083
  if (!adjust) {
30078
30084
  throw new Error(`ExchangeInstance unknown time adjust for interval=${interval}`);
30079
30085
  }
@@ -30101,9 +30107,10 @@ class ExchangeInstance {
30101
30107
  allData = await getCandles(symbol, interval, since, limit, isBacktest);
30102
30108
  }
30103
30109
  // Filter candles to strictly match the requested range
30104
- const whenTimestamp = when.getTime();
30105
30110
  const sinceTimestamp = since.getTime();
30106
- const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp <= whenTimestamp);
30111
+ const whenTimestamp = when.getTime();
30112
+ const stepMs = step * 60 * 1000;
30113
+ const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp < whenTimestamp + stepMs);
30107
30114
  // Apply distinct by timestamp to remove duplicates
30108
30115
  const uniqueData = Array.from(new Map(filteredData.map((candle) => [candle.timestamp, candle])).values());
30109
30116
  if (filteredData.length !== uniqueData.length) {
@@ -31778,6 +31785,91 @@ const roundTicks = (price, tickSize) => {
31778
31785
  return price.toFixed(precision);
31779
31786
  };
31780
31787
 
31788
+ /**
31789
+ * Parses command-line arguments for trading bot configuration.
31790
+ *
31791
+ * Processes process.argv to extract trading parameters and mode flags.
31792
+ * Merges provided default values with command-line arguments.
31793
+ * Supports both backtest mode (historical simulation), paper trading mode
31794
+ * (simulated trading with live data), and live trading mode (real trading).
31795
+ *
31796
+ * Command-line options:
31797
+ * - --symbol: Trading pair symbol (e.g., "BTCUSDT")
31798
+ * - --strategy: Strategy name to use
31799
+ * - --exchange: Exchange name (e.g., "binance")
31800
+ * - --frame: Timeframe for candles (e.g., "1h", "15m")
31801
+ * - --backtest: Enable backtest mode (boolean flag)
31802
+ * - --paper: Enable paper trading mode (boolean flag)
31803
+ * - --live: Enable live trading mode (boolean flag)
31804
+ *
31805
+ * @param params - Optional default values for parameters
31806
+ * @param params.symbol - Default trading pair symbol
31807
+ * @param params.strategyName - Default strategy name
31808
+ * @param params.exchangeName - Default exchange name
31809
+ * @param params.frameName - Default timeframe
31810
+ * @returns Parsed configuration with all parameters and mode flags
31811
+ *
31812
+ * @example
31813
+ * ```typescript
31814
+ * // Parse args with defaults
31815
+ * const config = parseArgs({
31816
+ * symbol: "BTCUSDT",
31817
+ * strategyName: "rsi_divergence",
31818
+ * exchangeName: "binance",
31819
+ * frameName: "1h"
31820
+ * });
31821
+ *
31822
+ * // Command: node app.js --backtest
31823
+ * // Result: { symbol: "BTCUSDT", ..., backtest: true, paper: false, live: false }
31824
+ * ```
31825
+ */
31826
+ const parseArgs = ({ symbol, strategyName, exchangeName, frameName, } = {}) => {
31827
+ const { values } = util.parseArgs({
31828
+ args: process.argv,
31829
+ options: {
31830
+ symbol: {
31831
+ type: "string",
31832
+ default: symbol,
31833
+ },
31834
+ strategy: {
31835
+ type: "string",
31836
+ default: strategyName,
31837
+ },
31838
+ exchange: {
31839
+ type: "string",
31840
+ default: exchangeName,
31841
+ },
31842
+ frame: {
31843
+ type: "string",
31844
+ default: frameName,
31845
+ },
31846
+ backtest: {
31847
+ type: "boolean",
31848
+ default: false,
31849
+ },
31850
+ paper: {
31851
+ type: "boolean",
31852
+ default: false,
31853
+ },
31854
+ live: {
31855
+ type: "boolean",
31856
+ default: false,
31857
+ },
31858
+ },
31859
+ strict: false,
31860
+ allowPositionals: true,
31861
+ });
31862
+ return {
31863
+ symbol: String(values.symbol),
31864
+ strategyName: String(values.strategy),
31865
+ exchangeName: String(values.exchange),
31866
+ frameName: String(values.frame),
31867
+ backtest: Boolean(values.backtest),
31868
+ paper: Boolean(values.paper),
31869
+ live: Boolean(values.live),
31870
+ };
31871
+ };
31872
+
31781
31873
  /**
31782
31874
  * Updates the value of a nested object property using a specific path.
31783
31875
  *
@@ -31920,6 +32012,7 @@ exports.overrideRiskSchema = overrideRiskSchema;
31920
32012
  exports.overrideSizingSchema = overrideSizingSchema;
31921
32013
  exports.overrideStrategySchema = overrideStrategySchema;
31922
32014
  exports.overrideWalkerSchema = overrideWalkerSchema;
32015
+ exports.parseArgs = parseArgs;
31923
32016
  exports.roundTicks = roundTicks;
31924
32017
  exports.set = set;
31925
32018
  exports.setColumns = setColumns;
package/build/index.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  import { createActivator } from 'di-kit';
2
2
  import { scoped } from 'di-scoped';
3
- import { Subject, trycatch, errorData, getErrorMessage, sleep, memoize, makeExtendable, singleshot, not, retry, randomString, str, isObject, ToolRegistry, and, resolveDocuments, timeout, TIMEOUT_SYMBOL as TIMEOUT_SYMBOL$1, compose, iterateDocuments, distinctDocuments, queued, singlerun } from 'functools-kit';
3
+ import { Subject, trycatch, errorData, getErrorMessage, sleep, memoize, makeExtendable, singleshot, not, retry, randomString, str, isObject, ToolRegistry, typo, and, resolveDocuments, timeout, TIMEOUT_SYMBOL as TIMEOUT_SYMBOL$1, compose, iterateDocuments, distinctDocuments, queued, singlerun } from 'functools-kit';
4
4
  import * as fs from 'fs/promises';
5
5
  import fs__default, { mkdir, writeFile } from 'fs/promises';
6
6
  import path, { join, dirname } from 'path';
7
7
  import crypto from 'crypto';
8
8
  import os from 'os';
9
9
  import { createWriteStream } from 'fs';
10
+ import { parseArgs as parseArgs$1 } from 'util';
10
11
 
11
12
  const { init, inject, provide } = createActivator("backtest");
12
13
 
@@ -732,7 +733,7 @@ class ClientExchange {
732
733
  limit,
733
734
  });
734
735
  const step = INTERVAL_MINUTES$4[interval];
735
- const adjust = step * limit - step;
736
+ const adjust = step * limit;
736
737
  if (!adjust) {
737
738
  throw new Error(`ClientExchange unknown time adjust for interval=${interval}`);
738
739
  }
@@ -759,7 +760,8 @@ class ClientExchange {
759
760
  // Filter candles to strictly match the requested range
760
761
  const whenTimestamp = this.params.execution.context.when.getTime();
761
762
  const sinceTimestamp = since.getTime();
762
- const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp <= whenTimestamp);
763
+ const stepMs = step * 60 * 1000;
764
+ const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp < whenTimestamp + stepMs);
763
765
  // Apply distinct by timestamp to remove duplicates
764
766
  const uniqueData = Array.from(new Map(filteredData.map((candle) => [candle.timestamp, candle])).values());
765
767
  if (filteredData.length !== uniqueData.length) {
@@ -821,14 +823,18 @@ class ClientExchange {
821
823
  }
822
824
  // Filter candles to strictly match the requested range
823
825
  const sinceTimestamp = since.getTime();
824
- const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp <= endTime);
826
+ const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp < endTime);
825
827
  // Apply distinct by timestamp to remove duplicates
826
828
  const uniqueData = Array.from(new Map(filteredData.map((candle) => [candle.timestamp, candle])).values());
827
829
  if (filteredData.length !== uniqueData.length) {
828
- this.params.logger.warn(`ClientExchange getNextCandles: Removed ${filteredData.length - uniqueData.length} duplicate candles by timestamp`);
830
+ const msg = `ClientExchange getNextCandles: Removed ${filteredData.length - uniqueData.length} duplicate candles by timestamp`;
831
+ this.params.logger.warn(msg);
832
+ console.warn(msg);
829
833
  }
830
834
  if (uniqueData.length < limit) {
831
- this.params.logger.warn(`ClientExchange getNextCandles: Expected ${limit} candles, got ${uniqueData.length}`);
835
+ const msg = `ClientExchange getNextCandles: Expected ${limit} candles, got ${uniqueData.length}`;
836
+ this.params.logger.warn(msg);
837
+ console.warn(msg);
832
838
  }
833
839
  await CALL_CANDLE_DATA_CALLBACKS_FN(this, symbol, interval, since, limit, uniqueData);
834
840
  return uniqueData;
@@ -10007,9 +10013,9 @@ const VALIDATE_CLASS_METHODS = (actionName, handler, self) => {
10007
10013
  `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10008
10014
  ];
10009
10015
  if (suggestions.length > 0) {
10010
- lines.push("");
10016
+ lines.push(typo.nbsp);
10011
10017
  lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10012
- lines.push("");
10018
+ lines.push(typo.nbsp);
10013
10019
  }
10014
10020
  lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10015
10021
  const msg = str.newline(lines);
@@ -10047,9 +10053,9 @@ const VALIDATE_OBJECT_METHODS = (actionName, handler, self) => {
10047
10053
  `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10048
10054
  ];
10049
10055
  if (suggestions.length > 0) {
10050
- lines.push("");
10056
+ lines.push(typo.nbsp);
10051
10057
  lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10052
- lines.push("");
10058
+ lines.push(typo.nbsp);
10053
10059
  }
10054
10060
  lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10055
10061
  const msg = str.newline(lines);
@@ -10500,7 +10506,7 @@ class BacktestLogicPrivateService {
10500
10506
  // Запрашиваем minuteEstimatedTime + буфер свечей одним запросом
10501
10507
  const bufferMinutes = GLOBAL_CONFIG.CC_AVG_PRICE_CANDLES_COUNT - 1;
10502
10508
  const bufferStartTime = new Date(when.getTime() - bufferMinutes * 60 * 1000);
10503
- const totalCandles = signal.minuteEstimatedTime + bufferMinutes;
10509
+ const totalCandles = signal.minuteEstimatedTime + GLOBAL_CONFIG.CC_AVG_PRICE_CANDLES_COUNT;
10504
10510
  let candles;
10505
10511
  try {
10506
10512
  candles = await this.exchangeCoreService.getNextCandles(symbol, "1m", totalCandles, bufferStartTime, true);
@@ -30053,7 +30059,7 @@ class ExchangeInstance {
30053
30059
  });
30054
30060
  const getCandles = this._methods.getCandles;
30055
30061
  const step = INTERVAL_MINUTES$1[interval];
30056
- const adjust = step * limit - step;
30062
+ const adjust = step * limit;
30057
30063
  if (!adjust) {
30058
30064
  throw new Error(`ExchangeInstance unknown time adjust for interval=${interval}`);
30059
30065
  }
@@ -30081,9 +30087,10 @@ class ExchangeInstance {
30081
30087
  allData = await getCandles(symbol, interval, since, limit, isBacktest);
30082
30088
  }
30083
30089
  // Filter candles to strictly match the requested range
30084
- const whenTimestamp = when.getTime();
30085
30090
  const sinceTimestamp = since.getTime();
30086
- const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp <= whenTimestamp);
30091
+ const whenTimestamp = when.getTime();
30092
+ const stepMs = step * 60 * 1000;
30093
+ const filteredData = allData.filter((candle) => candle.timestamp >= sinceTimestamp && candle.timestamp < whenTimestamp + stepMs);
30087
30094
  // Apply distinct by timestamp to remove duplicates
30088
30095
  const uniqueData = Array.from(new Map(filteredData.map((candle) => [candle.timestamp, candle])).values());
30089
30096
  if (filteredData.length !== uniqueData.length) {
@@ -31758,6 +31765,91 @@ const roundTicks = (price, tickSize) => {
31758
31765
  return price.toFixed(precision);
31759
31766
  };
31760
31767
 
31768
+ /**
31769
+ * Parses command-line arguments for trading bot configuration.
31770
+ *
31771
+ * Processes process.argv to extract trading parameters and mode flags.
31772
+ * Merges provided default values with command-line arguments.
31773
+ * Supports both backtest mode (historical simulation), paper trading mode
31774
+ * (simulated trading with live data), and live trading mode (real trading).
31775
+ *
31776
+ * Command-line options:
31777
+ * - --symbol: Trading pair symbol (e.g., "BTCUSDT")
31778
+ * - --strategy: Strategy name to use
31779
+ * - --exchange: Exchange name (e.g., "binance")
31780
+ * - --frame: Timeframe for candles (e.g., "1h", "15m")
31781
+ * - --backtest: Enable backtest mode (boolean flag)
31782
+ * - --paper: Enable paper trading mode (boolean flag)
31783
+ * - --live: Enable live trading mode (boolean flag)
31784
+ *
31785
+ * @param params - Optional default values for parameters
31786
+ * @param params.symbol - Default trading pair symbol
31787
+ * @param params.strategyName - Default strategy name
31788
+ * @param params.exchangeName - Default exchange name
31789
+ * @param params.frameName - Default timeframe
31790
+ * @returns Parsed configuration with all parameters and mode flags
31791
+ *
31792
+ * @example
31793
+ * ```typescript
31794
+ * // Parse args with defaults
31795
+ * const config = parseArgs({
31796
+ * symbol: "BTCUSDT",
31797
+ * strategyName: "rsi_divergence",
31798
+ * exchangeName: "binance",
31799
+ * frameName: "1h"
31800
+ * });
31801
+ *
31802
+ * // Command: node app.js --backtest
31803
+ * // Result: { symbol: "BTCUSDT", ..., backtest: true, paper: false, live: false }
31804
+ * ```
31805
+ */
31806
+ const parseArgs = ({ symbol, strategyName, exchangeName, frameName, } = {}) => {
31807
+ const { values } = parseArgs$1({
31808
+ args: process.argv,
31809
+ options: {
31810
+ symbol: {
31811
+ type: "string",
31812
+ default: symbol,
31813
+ },
31814
+ strategy: {
31815
+ type: "string",
31816
+ default: strategyName,
31817
+ },
31818
+ exchange: {
31819
+ type: "string",
31820
+ default: exchangeName,
31821
+ },
31822
+ frame: {
31823
+ type: "string",
31824
+ default: frameName,
31825
+ },
31826
+ backtest: {
31827
+ type: "boolean",
31828
+ default: false,
31829
+ },
31830
+ paper: {
31831
+ type: "boolean",
31832
+ default: false,
31833
+ },
31834
+ live: {
31835
+ type: "boolean",
31836
+ default: false,
31837
+ },
31838
+ },
31839
+ strict: false,
31840
+ allowPositionals: true,
31841
+ });
31842
+ return {
31843
+ symbol: String(values.symbol),
31844
+ strategyName: String(values.strategy),
31845
+ exchangeName: String(values.exchange),
31846
+ frameName: String(values.frame),
31847
+ backtest: Boolean(values.backtest),
31848
+ paper: Boolean(values.paper),
31849
+ live: Boolean(values.live),
31850
+ };
31851
+ };
31852
+
31761
31853
  /**
31762
31854
  * Updates the value of a nested object property using a specific path.
31763
31855
  *
@@ -31781,4 +31873,4 @@ const set = (object, path, value) => {
31781
31873
  }
31782
31874
  };
31783
31875
 
31784
- export { ActionBase, Backtest, Breakeven, Cache, Constant, Exchange, ExecutionContextService, Heat, Live, Markdown, MarkdownFileBase, MarkdownFolderBase, MethodContextService, Notification, Optimizer, Partial, Performance, PersistBase, PersistBreakevenAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, Report, ReportBase, Risk, Schedule, Walker, addActionSchema, addExchangeSchema, addFrameSchema, addOptimizerSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, commitBreakeven, commitCancel, commitPartialLoss, commitPartialProfit, 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, roundTicks, set, setColumns, setConfig, setLogger, stop, validate };
31876
+ export { ActionBase, Backtest, Breakeven, Cache, Constant, Exchange, ExecutionContextService, Heat, Live, Markdown, MarkdownFileBase, MarkdownFolderBase, MethodContextService, Notification, Optimizer, Partial, Performance, PersistBase, PersistBreakevenAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, Report, ReportBase, Risk, Schedule, Walker, addActionSchema, addExchangeSchema, addFrameSchema, addOptimizerSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, commitBreakeven, commitCancel, commitPartialLoss, commitPartialProfit, 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, stop, validate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backtest-kit",
3
- "version": "2.0.5",
3
+ "version": "2.0.7",
4
4
  "description": "A TypeScript library for trading system backtest",
5
5
  "author": {
6
6
  "name": "Petr Tripolsky",
package/types.d.ts CHANGED
@@ -2,6 +2,9 @@ import * as di_scoped from 'di-scoped';
2
2
  import * as functools_kit from 'functools-kit';
3
3
  import { Subject } from 'functools-kit';
4
4
  import { WriteStream } from 'fs';
5
+ import { ExchangeName as ExchangeName$1 } from 'src/interfaces/Exchange.interface';
6
+ import { FrameName as FrameName$1 } from 'src/interfaces/Frame.interface';
7
+ import { StrategyName as StrategyName$1 } from 'src/interfaces/Strategy.interface';
5
8
 
6
9
  /**
7
10
  * Retrieves current backtest timeframe for given symbol.
@@ -13774,6 +13777,72 @@ declare namespace emitters {
13774
13777
  */
13775
13778
  declare const roundTicks: (price: string | number, tickSize: number) => string;
13776
13779
 
13780
+ /**
13781
+ * Input parameters for parseArgs function.
13782
+ * Defines the default values for command-line argument parsing.
13783
+ */
13784
+ interface IParseArgsParams {
13785
+ /** Trading pair symbol (e.g., "BTCUSDT", "ETHUSDT") */
13786
+ symbol: string;
13787
+ /** Name of the trading strategy to execute */
13788
+ strategyName: StrategyName$1;
13789
+ /** Name of the exchange to connect to (e.g., "binance", "bybit") */
13790
+ exchangeName: ExchangeName$1;
13791
+ /** Timeframe for candle data (e.g., "1h", "15m", "1d") */
13792
+ frameName: FrameName$1;
13793
+ }
13794
+ /**
13795
+ * Result of parseArgs function.
13796
+ * Extends input parameters with trading mode flags parsed from command-line arguments.
13797
+ */
13798
+ interface IParseArgsResult extends IParseArgsParams {
13799
+ /** Whether to run in backtest mode (historical data simulation) */
13800
+ backtest: boolean;
13801
+ /** Whether to run in paper trading mode (simulated trading with live data) */
13802
+ paper: boolean;
13803
+ /** Whether to run in live trading mode (real trading with real money) */
13804
+ live: boolean;
13805
+ }
13806
+ /**
13807
+ * Parses command-line arguments for trading bot configuration.
13808
+ *
13809
+ * Processes process.argv to extract trading parameters and mode flags.
13810
+ * Merges provided default values with command-line arguments.
13811
+ * Supports both backtest mode (historical simulation), paper trading mode
13812
+ * (simulated trading with live data), and live trading mode (real trading).
13813
+ *
13814
+ * Command-line options:
13815
+ * - --symbol: Trading pair symbol (e.g., "BTCUSDT")
13816
+ * - --strategy: Strategy name to use
13817
+ * - --exchange: Exchange name (e.g., "binance")
13818
+ * - --frame: Timeframe for candles (e.g., "1h", "15m")
13819
+ * - --backtest: Enable backtest mode (boolean flag)
13820
+ * - --paper: Enable paper trading mode (boolean flag)
13821
+ * - --live: Enable live trading mode (boolean flag)
13822
+ *
13823
+ * @param params - Optional default values for parameters
13824
+ * @param params.symbol - Default trading pair symbol
13825
+ * @param params.strategyName - Default strategy name
13826
+ * @param params.exchangeName - Default exchange name
13827
+ * @param params.frameName - Default timeframe
13828
+ * @returns Parsed configuration with all parameters and mode flags
13829
+ *
13830
+ * @example
13831
+ * ```typescript
13832
+ * // Parse args with defaults
13833
+ * const config = parseArgs({
13834
+ * symbol: "BTCUSDT",
13835
+ * strategyName: "rsi_divergence",
13836
+ * exchangeName: "binance",
13837
+ * frameName: "1h"
13838
+ * });
13839
+ *
13840
+ * // Command: node app.js --backtest
13841
+ * // Result: { symbol: "BTCUSDT", ..., backtest: true, paper: false, live: false }
13842
+ * ```
13843
+ */
13844
+ declare const parseArgs: ({ symbol, strategyName, exchangeName, frameName, }?: Partial<IParseArgsParams>) => IParseArgsResult;
13845
+
13777
13846
  /**
13778
13847
  * Retrieves a value from an object using a given path.
13779
13848
  *
@@ -18855,4 +18924,4 @@ declare const backtest: {
18855
18924
  loggerService: LoggerService;
18856
18925
  };
18857
18926
 
18858
- export { ActionBase, type ActivePingContract, 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 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, commitCancel, commitPartialLoss, commitPartialProfit, 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, roundTicks, set, setColumns, setConfig, setLogger, stop, validate };
18927
+ export { ActionBase, type ActivePingContract, 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 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, commitCancel, commitPartialLoss, commitPartialProfit, 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, stop, validate };