backtest-kit 2.0.4 → 2.0.6

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);
@@ -9918,6 +9919,83 @@ const VALID_METHOD_NAMES = [
9918
9919
  "riskRejection",
9919
9920
  "dispose",
9920
9921
  ];
9922
+ /**
9923
+ * Calculates the Levenshtein distance between two strings.
9924
+ *
9925
+ * Levenshtein distance is the minimum number of single-character edits
9926
+ * (insertions, deletions, or substitutions) required to change one string into another.
9927
+ * Used to find typos and similar method names in validation.
9928
+ *
9929
+ * @param str1 - First string to compare
9930
+ * @param str2 - Second string to compare
9931
+ * @returns Number of edits needed to transform str1 into str2
9932
+ */
9933
+ const LEVENSHTEIN_DISTANCE = (str1, str2) => {
9934
+ const len1 = str1.length;
9935
+ const len2 = str2.length;
9936
+ // Create a 2D array for dynamic programming
9937
+ const matrix = Array.from({ length: len1 + 1 }, () => Array(len2 + 1).fill(0));
9938
+ // Initialize first column and row
9939
+ for (let i = 0; i <= len1; i++) {
9940
+ matrix[i][0] = i;
9941
+ }
9942
+ for (let j = 0; j <= len2; j++) {
9943
+ matrix[0][j] = j;
9944
+ }
9945
+ // Fill the matrix
9946
+ for (let i = 1; i <= len1; i++) {
9947
+ for (let j = 1; j <= len2; j++) {
9948
+ const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
9949
+ matrix[i][j] = Math.min(matrix[i - 1][j] + 1, // deletion
9950
+ matrix[i][j - 1] + 1, // insertion
9951
+ matrix[i - 1][j - 1] + cost // substitution
9952
+ );
9953
+ }
9954
+ }
9955
+ return matrix[len1][len2];
9956
+ };
9957
+ /**
9958
+ * Finds suggestions for a method name based on similarity scoring.
9959
+ *
9960
+ * Uses Levenshtein distance and partial string matching to find similar method names.
9961
+ * Returns suggestions sorted by similarity (most similar first).
9962
+ * Used to provide helpful "Did you mean?" suggestions in validation error messages.
9963
+ *
9964
+ * @param methodName - The invalid method name to find suggestions for
9965
+ * @param validNames - List of valid method names to search through
9966
+ * @param maxDistance - Maximum Levenshtein distance to consider (default: 3)
9967
+ * @returns Array of suggested method names sorted by similarity
9968
+ */
9969
+ const FIND_SUGGESTIONS = (methodName, validNames, maxDistance = 3) => {
9970
+ const lowerMethodName = methodName.toLowerCase();
9971
+ // Calculate similarity score for each valid name
9972
+ const suggestions = validNames
9973
+ .map((validName) => {
9974
+ const lowerValidName = validName.toLowerCase();
9975
+ const distance = LEVENSHTEIN_DISTANCE(lowerMethodName, lowerValidName);
9976
+ // Check for partial matches
9977
+ const hasPartialMatch = lowerValidName.includes(lowerMethodName) ||
9978
+ lowerMethodName.includes(lowerValidName);
9979
+ return {
9980
+ name: validName,
9981
+ distance,
9982
+ hasPartialMatch,
9983
+ };
9984
+ })
9985
+ .filter((item) => item.distance <= maxDistance || item.hasPartialMatch)
9986
+ .sort((a, b) => {
9987
+ // Prioritize partial matches
9988
+ if (a.hasPartialMatch && !b.hasPartialMatch)
9989
+ return -1;
9990
+ if (!a.hasPartialMatch && b.hasPartialMatch)
9991
+ return 1;
9992
+ // Then sort by distance
9993
+ return a.distance - b.distance;
9994
+ })
9995
+ .slice(0, 3) // Limit to top 3 suggestions
9996
+ .map((item) => item.name);
9997
+ return suggestions;
9998
+ };
9921
9999
  /**
9922
10000
  * Validates that all public methods in a class-based action handler are in the allowed list.
9923
10001
  *
@@ -9944,7 +10022,18 @@ const VALIDATE_CLASS_METHODS = (actionName, handler, self) => {
9944
10022
  const descriptor = Object.getOwnPropertyDescriptor(handler.prototype, methodName);
9945
10023
  const isMethod = descriptor && typeof descriptor.value === "function";
9946
10024
  if (isMethod && !VALID_METHOD_NAMES.includes(methodName)) {
9947
- const msg = functoolsKit.str.newline(`ActionSchema ${actionName} contains invalid method "${methodName}". `, `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`, `If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10025
+ const suggestions = FIND_SUGGESTIONS(methodName, VALID_METHOD_NAMES);
10026
+ const lines = [
10027
+ `ActionSchema ${actionName} contains invalid method "${methodName}". `,
10028
+ `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10029
+ ];
10030
+ if (suggestions.length > 0) {
10031
+ lines.push(functoolsKit.typo.nbsp);
10032
+ lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10033
+ lines.push(functoolsKit.typo.nbsp);
10034
+ }
10035
+ lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10036
+ const msg = functoolsKit.str.newline(lines);
9948
10037
  self.loggerService.log(`actionValidationService exception thrown`, {
9949
10038
  msg,
9950
10039
  });
@@ -9973,7 +10062,18 @@ const VALIDATE_OBJECT_METHODS = (actionName, handler, self) => {
9973
10062
  }
9974
10063
  if (typeof handler[methodName] === "function" &&
9975
10064
  !VALID_METHOD_NAMES.includes(methodName)) {
9976
- const msg = functoolsKit.str.newline(`ActionSchema ${actionName} contains invalid method "${methodName}". `, `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`, `If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10065
+ const suggestions = FIND_SUGGESTIONS(methodName, VALID_METHOD_NAMES);
10066
+ const lines = [
10067
+ `ActionSchema ${actionName} contains invalid method "${methodName}". `,
10068
+ `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10069
+ ];
10070
+ if (suggestions.length > 0) {
10071
+ lines.push(functoolsKit.typo.nbsp);
10072
+ lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10073
+ lines.push(functoolsKit.typo.nbsp);
10074
+ }
10075
+ lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10076
+ const msg = functoolsKit.str.newline(lines);
9977
10077
  self.loggerService.log(`actionValidationService exception thrown`, {
9978
10078
  msg,
9979
10079
  });
@@ -31679,6 +31779,91 @@ const roundTicks = (price, tickSize) => {
31679
31779
  return price.toFixed(precision);
31680
31780
  };
31681
31781
 
31782
+ /**
31783
+ * Parses command-line arguments for trading bot configuration.
31784
+ *
31785
+ * Processes process.argv to extract trading parameters and mode flags.
31786
+ * Merges provided default values with command-line arguments.
31787
+ * Supports both backtest mode (historical simulation), paper trading mode
31788
+ * (simulated trading with live data), and live trading mode (real trading).
31789
+ *
31790
+ * Command-line options:
31791
+ * - --symbol: Trading pair symbol (e.g., "BTCUSDT")
31792
+ * - --strategy: Strategy name to use
31793
+ * - --exchange: Exchange name (e.g., "binance")
31794
+ * - --frame: Timeframe for candles (e.g., "1h", "15m")
31795
+ * - --backtest: Enable backtest mode (boolean flag)
31796
+ * - --paper: Enable paper trading mode (boolean flag)
31797
+ * - --live: Enable live trading mode (boolean flag)
31798
+ *
31799
+ * @param params - Optional default values for parameters
31800
+ * @param params.symbol - Default trading pair symbol
31801
+ * @param params.strategyName - Default strategy name
31802
+ * @param params.exchangeName - Default exchange name
31803
+ * @param params.frameName - Default timeframe
31804
+ * @returns Parsed configuration with all parameters and mode flags
31805
+ *
31806
+ * @example
31807
+ * ```typescript
31808
+ * // Parse args with defaults
31809
+ * const config = parseArgs({
31810
+ * symbol: "BTCUSDT",
31811
+ * strategyName: "rsi_divergence",
31812
+ * exchangeName: "binance",
31813
+ * frameName: "1h"
31814
+ * });
31815
+ *
31816
+ * // Command: node app.js --backtest
31817
+ * // Result: { symbol: "BTCUSDT", ..., backtest: true, paper: false, live: false }
31818
+ * ```
31819
+ */
31820
+ const parseArgs = ({ symbol, strategyName, exchangeName, frameName, } = {}) => {
31821
+ const { values } = util.parseArgs({
31822
+ args: process.argv,
31823
+ options: {
31824
+ symbol: {
31825
+ type: "string",
31826
+ default: symbol,
31827
+ },
31828
+ strategy: {
31829
+ type: "string",
31830
+ default: strategyName,
31831
+ },
31832
+ exchange: {
31833
+ type: "string",
31834
+ default: exchangeName,
31835
+ },
31836
+ frame: {
31837
+ type: "string",
31838
+ default: frameName,
31839
+ },
31840
+ backtest: {
31841
+ type: "boolean",
31842
+ default: false,
31843
+ },
31844
+ paper: {
31845
+ type: "boolean",
31846
+ default: false,
31847
+ },
31848
+ live: {
31849
+ type: "boolean",
31850
+ default: false,
31851
+ },
31852
+ },
31853
+ strict: false,
31854
+ allowPositionals: true,
31855
+ });
31856
+ return {
31857
+ symbol: String(values.symbol),
31858
+ strategyName: String(values.strategy),
31859
+ exchangeName: String(values.exchange),
31860
+ frameName: String(values.frame),
31861
+ backtest: Boolean(values.backtest),
31862
+ paper: Boolean(values.paper),
31863
+ live: Boolean(values.live),
31864
+ };
31865
+ };
31866
+
31682
31867
  /**
31683
31868
  * Updates the value of a nested object property using a specific path.
31684
31869
  *
@@ -31821,6 +32006,7 @@ exports.overrideRiskSchema = overrideRiskSchema;
31821
32006
  exports.overrideSizingSchema = overrideSizingSchema;
31822
32007
  exports.overrideStrategySchema = overrideStrategySchema;
31823
32008
  exports.overrideWalkerSchema = overrideWalkerSchema;
32009
+ exports.parseArgs = parseArgs;
31824
32010
  exports.roundTicks = roundTicks;
31825
32011
  exports.set = set;
31826
32012
  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
 
@@ -9898,6 +9899,83 @@ const VALID_METHOD_NAMES = [
9898
9899
  "riskRejection",
9899
9900
  "dispose",
9900
9901
  ];
9902
+ /**
9903
+ * Calculates the Levenshtein distance between two strings.
9904
+ *
9905
+ * Levenshtein distance is the minimum number of single-character edits
9906
+ * (insertions, deletions, or substitutions) required to change one string into another.
9907
+ * Used to find typos and similar method names in validation.
9908
+ *
9909
+ * @param str1 - First string to compare
9910
+ * @param str2 - Second string to compare
9911
+ * @returns Number of edits needed to transform str1 into str2
9912
+ */
9913
+ const LEVENSHTEIN_DISTANCE = (str1, str2) => {
9914
+ const len1 = str1.length;
9915
+ const len2 = str2.length;
9916
+ // Create a 2D array for dynamic programming
9917
+ const matrix = Array.from({ length: len1 + 1 }, () => Array(len2 + 1).fill(0));
9918
+ // Initialize first column and row
9919
+ for (let i = 0; i <= len1; i++) {
9920
+ matrix[i][0] = i;
9921
+ }
9922
+ for (let j = 0; j <= len2; j++) {
9923
+ matrix[0][j] = j;
9924
+ }
9925
+ // Fill the matrix
9926
+ for (let i = 1; i <= len1; i++) {
9927
+ for (let j = 1; j <= len2; j++) {
9928
+ const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
9929
+ matrix[i][j] = Math.min(matrix[i - 1][j] + 1, // deletion
9930
+ matrix[i][j - 1] + 1, // insertion
9931
+ matrix[i - 1][j - 1] + cost // substitution
9932
+ );
9933
+ }
9934
+ }
9935
+ return matrix[len1][len2];
9936
+ };
9937
+ /**
9938
+ * Finds suggestions for a method name based on similarity scoring.
9939
+ *
9940
+ * Uses Levenshtein distance and partial string matching to find similar method names.
9941
+ * Returns suggestions sorted by similarity (most similar first).
9942
+ * Used to provide helpful "Did you mean?" suggestions in validation error messages.
9943
+ *
9944
+ * @param methodName - The invalid method name to find suggestions for
9945
+ * @param validNames - List of valid method names to search through
9946
+ * @param maxDistance - Maximum Levenshtein distance to consider (default: 3)
9947
+ * @returns Array of suggested method names sorted by similarity
9948
+ */
9949
+ const FIND_SUGGESTIONS = (methodName, validNames, maxDistance = 3) => {
9950
+ const lowerMethodName = methodName.toLowerCase();
9951
+ // Calculate similarity score for each valid name
9952
+ const suggestions = validNames
9953
+ .map((validName) => {
9954
+ const lowerValidName = validName.toLowerCase();
9955
+ const distance = LEVENSHTEIN_DISTANCE(lowerMethodName, lowerValidName);
9956
+ // Check for partial matches
9957
+ const hasPartialMatch = lowerValidName.includes(lowerMethodName) ||
9958
+ lowerMethodName.includes(lowerValidName);
9959
+ return {
9960
+ name: validName,
9961
+ distance,
9962
+ hasPartialMatch,
9963
+ };
9964
+ })
9965
+ .filter((item) => item.distance <= maxDistance || item.hasPartialMatch)
9966
+ .sort((a, b) => {
9967
+ // Prioritize partial matches
9968
+ if (a.hasPartialMatch && !b.hasPartialMatch)
9969
+ return -1;
9970
+ if (!a.hasPartialMatch && b.hasPartialMatch)
9971
+ return 1;
9972
+ // Then sort by distance
9973
+ return a.distance - b.distance;
9974
+ })
9975
+ .slice(0, 3) // Limit to top 3 suggestions
9976
+ .map((item) => item.name);
9977
+ return suggestions;
9978
+ };
9901
9979
  /**
9902
9980
  * Validates that all public methods in a class-based action handler are in the allowed list.
9903
9981
  *
@@ -9924,7 +10002,18 @@ const VALIDATE_CLASS_METHODS = (actionName, handler, self) => {
9924
10002
  const descriptor = Object.getOwnPropertyDescriptor(handler.prototype, methodName);
9925
10003
  const isMethod = descriptor && typeof descriptor.value === "function";
9926
10004
  if (isMethod && !VALID_METHOD_NAMES.includes(methodName)) {
9927
- const msg = str.newline(`ActionSchema ${actionName} contains invalid method "${methodName}". `, `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`, `If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10005
+ const suggestions = FIND_SUGGESTIONS(methodName, VALID_METHOD_NAMES);
10006
+ const lines = [
10007
+ `ActionSchema ${actionName} contains invalid method "${methodName}". `,
10008
+ `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10009
+ ];
10010
+ if (suggestions.length > 0) {
10011
+ lines.push(typo.nbsp);
10012
+ lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10013
+ lines.push(typo.nbsp);
10014
+ }
10015
+ lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10016
+ const msg = str.newline(lines);
9928
10017
  self.loggerService.log(`actionValidationService exception thrown`, {
9929
10018
  msg,
9930
10019
  });
@@ -9953,7 +10042,18 @@ const VALIDATE_OBJECT_METHODS = (actionName, handler, self) => {
9953
10042
  }
9954
10043
  if (typeof handler[methodName] === "function" &&
9955
10044
  !VALID_METHOD_NAMES.includes(methodName)) {
9956
- const msg = str.newline(`ActionSchema ${actionName} contains invalid method "${methodName}". `, `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`, `If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10045
+ const suggestions = FIND_SUGGESTIONS(methodName, VALID_METHOD_NAMES);
10046
+ const lines = [
10047
+ `ActionSchema ${actionName} contains invalid method "${methodName}". `,
10048
+ `Valid methods are: ${VALID_METHOD_NAMES.join(", ")}`,
10049
+ ];
10050
+ if (suggestions.length > 0) {
10051
+ lines.push(typo.nbsp);
10052
+ lines.push(`Do you mean: ${suggestions.join(", ")}?`);
10053
+ lines.push(typo.nbsp);
10054
+ }
10055
+ lines.push(`If you want to keep this property name use one of these patterns: _${methodName} or #${methodName}`);
10056
+ const msg = str.newline(lines);
9957
10057
  self.loggerService.log(`actionValidationService exception thrown`, {
9958
10058
  msg,
9959
10059
  });
@@ -31659,6 +31759,91 @@ const roundTicks = (price, tickSize) => {
31659
31759
  return price.toFixed(precision);
31660
31760
  };
31661
31761
 
31762
+ /**
31763
+ * Parses command-line arguments for trading bot configuration.
31764
+ *
31765
+ * Processes process.argv to extract trading parameters and mode flags.
31766
+ * Merges provided default values with command-line arguments.
31767
+ * Supports both backtest mode (historical simulation), paper trading mode
31768
+ * (simulated trading with live data), and live trading mode (real trading).
31769
+ *
31770
+ * Command-line options:
31771
+ * - --symbol: Trading pair symbol (e.g., "BTCUSDT")
31772
+ * - --strategy: Strategy name to use
31773
+ * - --exchange: Exchange name (e.g., "binance")
31774
+ * - --frame: Timeframe for candles (e.g., "1h", "15m")
31775
+ * - --backtest: Enable backtest mode (boolean flag)
31776
+ * - --paper: Enable paper trading mode (boolean flag)
31777
+ * - --live: Enable live trading mode (boolean flag)
31778
+ *
31779
+ * @param params - Optional default values for parameters
31780
+ * @param params.symbol - Default trading pair symbol
31781
+ * @param params.strategyName - Default strategy name
31782
+ * @param params.exchangeName - Default exchange name
31783
+ * @param params.frameName - Default timeframe
31784
+ * @returns Parsed configuration with all parameters and mode flags
31785
+ *
31786
+ * @example
31787
+ * ```typescript
31788
+ * // Parse args with defaults
31789
+ * const config = parseArgs({
31790
+ * symbol: "BTCUSDT",
31791
+ * strategyName: "rsi_divergence",
31792
+ * exchangeName: "binance",
31793
+ * frameName: "1h"
31794
+ * });
31795
+ *
31796
+ * // Command: node app.js --backtest
31797
+ * // Result: { symbol: "BTCUSDT", ..., backtest: true, paper: false, live: false }
31798
+ * ```
31799
+ */
31800
+ const parseArgs = ({ symbol, strategyName, exchangeName, frameName, } = {}) => {
31801
+ const { values } = parseArgs$1({
31802
+ args: process.argv,
31803
+ options: {
31804
+ symbol: {
31805
+ type: "string",
31806
+ default: symbol,
31807
+ },
31808
+ strategy: {
31809
+ type: "string",
31810
+ default: strategyName,
31811
+ },
31812
+ exchange: {
31813
+ type: "string",
31814
+ default: exchangeName,
31815
+ },
31816
+ frame: {
31817
+ type: "string",
31818
+ default: frameName,
31819
+ },
31820
+ backtest: {
31821
+ type: "boolean",
31822
+ default: false,
31823
+ },
31824
+ paper: {
31825
+ type: "boolean",
31826
+ default: false,
31827
+ },
31828
+ live: {
31829
+ type: "boolean",
31830
+ default: false,
31831
+ },
31832
+ },
31833
+ strict: false,
31834
+ allowPositionals: true,
31835
+ });
31836
+ return {
31837
+ symbol: String(values.symbol),
31838
+ strategyName: String(values.strategy),
31839
+ exchangeName: String(values.exchange),
31840
+ frameName: String(values.frame),
31841
+ backtest: Boolean(values.backtest),
31842
+ paper: Boolean(values.paper),
31843
+ live: Boolean(values.live),
31844
+ };
31845
+ };
31846
+
31662
31847
  /**
31663
31848
  * Updates the value of a nested object property using a specific path.
31664
31849
  *
@@ -31682,4 +31867,4 @@ const set = (object, path, value) => {
31682
31867
  }
31683
31868
  };
31684
31869
 
31685
- 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 };
31870
+ 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.4",
3
+ "version": "2.0.6",
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 };