backtest-kit 3.6.0 → 3.7.1

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
@@ -1959,6 +1959,23 @@ interface ISignalRow extends ISignalDto {
1959
1959
  percent: number;
1960
1960
  /** Price at which this partial was executed */
1961
1961
  price: number;
1962
+ /** Debug only timestamp in milliseconds */
1963
+ debugTimestamp?: number;
1964
+ /**
1965
+ * Effective entry price (DCA average) at the moment this partial close was executed.
1966
+ * Captured from GET_EFFECTIVE_PRICE_OPEN at partial close time.
1967
+ * Used in PNL calculation when averageBuy() is called after partial closes,
1968
+ * so each partial's profit is calculated against the correct entry price at that moment.
1969
+ */
1970
+ effectivePrice: number;
1971
+ /**
1972
+ * Entry count (number of entries in _entry history) at the moment this partial close was executed.
1973
+ * Used to determine which entries are included in the effective price calculation for this partial close.
1974
+ * When averageBuy() is called after partial closes, new entries are added to _entry, but they should not affect the effective price used for already executed partial closes.
1975
+ * By capturing entryCountAtClose, we can slice the _entry array to include only the entries that were part of the position at the time of this partial close when calculating the effective price for PNL.
1976
+ * This ensures that each partial close's PNL is calculated against the correct average entry price, even if more averaging happens after the partial close.
1977
+ */
1978
+ entryCountAtClose: number;
1962
1979
  }>;
1963
1980
  /**
1964
1981
  * Trailing stop-loss price that overrides priceStopLoss when set.
@@ -1979,6 +1996,8 @@ interface ISignalRow extends ISignalDto {
1979
1996
  _entry?: Array<{
1980
1997
  /** Price at which this entry was executed */
1981
1998
  price: number;
1999
+ /** Debug only timestamp in milliseconds */
2000
+ debugTimestamp?: number;
1982
2001
  }>;
1983
2002
  /**
1984
2003
  * Trailing take-profit price that overrides priceTakeProfit when set.
@@ -2568,6 +2587,30 @@ interface IStrategy {
2568
2587
  * @returns Promise resolving to true if strategy is stopped, false otherwise
2569
2588
  */
2570
2589
  getStopped: (symbol: string) => Promise<boolean>;
2590
+ /**
2591
+ * Returns how much of the position is still held, as a percentage of totalInvested.
2592
+ *
2593
+ * Uses dollar-basis cost-basis replay (DCA-aware).
2594
+ * 100% means nothing was closed yet. Decreases with each partial close.
2595
+ *
2596
+ * Returns 100 if no pending signal or no partial closes.
2597
+ *
2598
+ * @param symbol - Trading pair symbol
2599
+ * @returns Promise resolving to held percentage (0–100)
2600
+ */
2601
+ getTotalPercentClosed: (symbol: string) => Promise<number | null>;
2602
+ /**
2603
+ * Returns how many dollars of cost basis are still held (not yet closed by partials).
2604
+ *
2605
+ * Full position open: equals totalInvested (entries × $100).
2606
+ * Decreases with each partial close, increases with each averageBuy().
2607
+ *
2608
+ * Returns totalInvested if no pending signal or no partial closes.
2609
+ *
2610
+ * @param symbol - Trading pair symbol
2611
+ * @returns Promise resolving to held cost basis in dollars
2612
+ */
2613
+ getTotalCostClosed: (symbol: string) => Promise<number | null>;
2571
2614
  /**
2572
2615
  * Fast backtest using historical candles.
2573
2616
  * Iterates through candles, calculates VWAP, checks TP/SL on each candle.
@@ -2989,10 +3032,12 @@ interface ILogEntry {
2989
3032
  id: string;
2990
3033
  /** Log level */
2991
3034
  type: "log" | "debug" | "info" | "warn";
2992
- /** Unix timestamp in milliseconds when the entry was created */
2993
- timestamp: number;
3035
+ /** Current Unix timestamp in milliseconds for storage rotate */
3036
+ priority: number;
2994
3037
  /** Date taken from backtest context to improve user experience */
2995
3038
  createdAt: string;
3039
+ /** Unix timestamp in milliseconds taken from backtest context to improve user experience */
3040
+ timestamp: number;
2996
3041
  /** Optional method context associated with the log entry, providing additional details about the execution environment or state when the log was recorded */
2997
3042
  methodContext: IMethodContext | null;
2998
3043
  /** Optional execution context associated with the log entry, providing additional details about the execution environment or state when the log was recorded */
@@ -4208,6 +4253,107 @@ declare function commitActivateScheduled(symbol: string, activateId?: string): P
4208
4253
  * ```
4209
4254
  */
4210
4255
  declare function commitAverageBuy(symbol: string): Promise<boolean>;
4256
+ /**
4257
+ * Returns the percentage of the position currently held (not closed).
4258
+ * 100 = nothing has been closed (full position), 0 = fully closed.
4259
+ * Correctly accounts for DCA entries between partial closes.
4260
+ *
4261
+ * Automatically detects backtest/live mode from execution context.
4262
+ *
4263
+ * @param symbol - Trading pair symbol
4264
+ * @returns Promise<number> - held percentage (0–100)
4265
+ *
4266
+ * @example
4267
+ * ```typescript
4268
+ * import { getTotalPercentClosed } from "backtest-kit";
4269
+ *
4270
+ * const heldPct = await getTotalPercentClosed("BTCUSDT");
4271
+ * console.log(`Holding ${heldPct}% of position`);
4272
+ * ```
4273
+ */
4274
+ declare function getTotalPercentClosed(symbol: string): Promise<number>;
4275
+ /**
4276
+ * Returns the cost basis in dollars of the position currently held (not closed).
4277
+ * Correctly accounts for DCA entries between partial closes.
4278
+ *
4279
+ * Automatically detects backtest/live mode from execution context.
4280
+ *
4281
+ * @param symbol - Trading pair symbol
4282
+ * @returns Promise<number> - held cost basis in dollars
4283
+ *
4284
+ * @example
4285
+ * ```typescript
4286
+ * import { getTotalCostClosed } from "backtest-kit";
4287
+ *
4288
+ * const heldCost = await getTotalCostClosed("BTCUSDT");
4289
+ * console.log(`Holding $${heldCost} of position`);
4290
+ * ```
4291
+ */
4292
+ declare function getTotalCostClosed(symbol: string): Promise<number>;
4293
+ /**
4294
+ * Returns the currently active pending signal for the strategy.
4295
+ * If no active signal exists, returns null.
4296
+ *
4297
+ * Automatically detects backtest/live mode from execution context.
4298
+ *
4299
+ * @param symbol - Trading pair symbol
4300
+ * @returns Promise resolving to pending signal or null
4301
+ *
4302
+ * @example
4303
+ * ```typescript
4304
+ * import { getPendingSignal } from "backtest-kit";
4305
+ *
4306
+ * const pending = await getPendingSignal("BTCUSDT");
4307
+ * if (pending) {
4308
+ * console.log("Active signal:", pending.id);
4309
+ * }
4310
+ * ```
4311
+ */
4312
+ declare function getPendingSignal(symbol: string): Promise<ISignalRow>;
4313
+ /**
4314
+ * Returns the currently active scheduled signal for the strategy.
4315
+ * If no scheduled signal exists, returns null.
4316
+ *
4317
+ * Automatically detects backtest/live mode from execution context.
4318
+ *
4319
+ * @param symbol - Trading pair symbol
4320
+ * @returns Promise resolving to scheduled signal or null
4321
+ *
4322
+ * @example
4323
+ * ```typescript
4324
+ * import { getScheduledSignal } from "backtest-kit";
4325
+ *
4326
+ * const scheduled = await getScheduledSignal("BTCUSDT");
4327
+ * if (scheduled) {
4328
+ * console.log("Scheduled signal:", scheduled.id);
4329
+ * }
4330
+ * ```
4331
+ */
4332
+ declare function getScheduledSignal(symbol: string): Promise<IScheduledSignalRow>;
4333
+ /**
4334
+ * Checks if breakeven threshold has been reached for the current pending signal.
4335
+ *
4336
+ * Returns true if price has moved far enough in profit direction to cover
4337
+ * transaction costs. Threshold is calculated as: (CC_PERCENT_SLIPPAGE + CC_PERCENT_FEE) * 2
4338
+ *
4339
+ * Automatically detects backtest/live mode from execution context.
4340
+ *
4341
+ * @param symbol - Trading pair symbol
4342
+ * @param currentPrice - Current market price to check against threshold
4343
+ * @returns Promise<boolean> - true if breakeven threshold reached, false otherwise
4344
+ *
4345
+ * @example
4346
+ * ```typescript
4347
+ * import { getBreakeven, getAveragePrice } from "backtest-kit";
4348
+ *
4349
+ * const price = await getAveragePrice("BTCUSDT");
4350
+ * const canBreakeven = await getBreakeven("BTCUSDT", price);
4351
+ * if (canBreakeven) {
4352
+ * console.log("Breakeven available");
4353
+ * }
4354
+ * ```
4355
+ */
4356
+ declare function getBreakeven(symbol: string, currentPrice: number): Promise<boolean>;
4211
4357
 
4212
4358
  /**
4213
4359
  * Stops the strategy from generating new signals.
@@ -4481,6 +4627,14 @@ declare const GLOBAL_CONFIG: {
4481
4627
  * Default: true (mutex locking enabled for candle fetching)
4482
4628
  */
4483
4629
  CC_ENABLE_CANDLE_FETCH_MUTEX: boolean;
4630
+ /**
4631
+ * Enables DCA (Dollar-Cost Averaging) logic even if antirecord is not broken.
4632
+ * Allows to commitAverageBuy if currentPrice is not the lowest price since entry, but still lower than priceOpen.
4633
+ * This can help improve average entry price in cases where price has rebounded after entry but is still below priceOpen, without waiting for a new lower price.
4634
+ *
4635
+ * Default: true (DCA logic enabled everywhere, not just when antirecord is broken)
4636
+ */
4637
+ CC_ENABLE_DCA_EVERYWHERE: boolean;
4484
4638
  };
4485
4639
  /**
4486
4640
  * Type for global configuration object.
@@ -4592,6 +4746,7 @@ declare function getConfig(): {
4592
4746
  CC_MAX_SIGNALS: number;
4593
4747
  CC_MAX_LOG_LINES: number;
4594
4748
  CC_ENABLE_CANDLE_FETCH_MUTEX: boolean;
4749
+ CC_ENABLE_DCA_EVERYWHERE: boolean;
4595
4750
  };
4596
4751
  /**
4597
4752
  * Retrieves the default configuration object for the framework.
@@ -4631,6 +4786,7 @@ declare function getDefaultConfig(): Readonly<{
4631
4786
  CC_MAX_SIGNALS: number;
4632
4787
  CC_MAX_LOG_LINES: number;
4633
4788
  CC_ENABLE_CANDLE_FETCH_MUTEX: boolean;
4789
+ CC_ENABLE_DCA_EVERYWHERE: boolean;
4634
4790
  }>;
4635
4791
  /**
4636
4792
  * Sets custom column configurations for markdown report generation.
@@ -4738,7 +4894,6 @@ declare function getDefaultColumns(): Readonly<{
4738
4894
  * priceTakeProfit: 51000,
4739
4895
  * priceStopLoss: 49000,
4740
4896
  * minuteEstimatedTime: 60,
4741
- * timestamp: Date.now(),
4742
4897
  * }),
4743
4898
  * callbacks: {
4744
4899
  * onOpen: (symbol, signal, currentPrice, backtest) => console.log("Signal opened"),
@@ -6859,6 +7014,20 @@ declare function formatQuantity(symbol: string, quantity: number): Promise<strin
6859
7014
  * ```
6860
7015
  */
6861
7016
  declare function getDate(): Promise<Date>;
7017
+ /**
7018
+ * Gets the current timestamp from execution context.
7019
+ *
7020
+ * In backtest mode: returns the current timeframe timestamp being processed
7021
+ * In live mode: returns current real-time timestamp
7022
+ *
7023
+ * @returns Promise resolving to current execution context timestamp in milliseconds
7024
+ * @example
7025
+ * ```typescript
7026
+ * const timestamp = await getTimestamp();
7027
+ * console.log(timestamp); // 1700000000000
7028
+ * ```
7029
+ */
7030
+ declare function getTimestamp(): Promise<number>;
6862
7031
  /**
6863
7032
  * Gets the current execution mode.
6864
7033
  *
@@ -8443,6 +8612,10 @@ declare const BASE_WAIT_FOR_INIT_SYMBOL: unique symbol;
8443
8612
  * Contains nullable signal for atomic updates.
8444
8613
  */
8445
8614
  type SignalData = ISignalRow | null;
8615
+ /**
8616
+ * Cache.file data type stored in persistence layer.
8617
+ */
8618
+ type MeasureData = unknown;
8446
8619
  /**
8447
8620
  * Type helper for PersistBase instance.
8448
8621
  */
@@ -9314,6 +9487,57 @@ declare class PersistLogUtils {
9314
9487
  * Used by LogPersistUtils for log entry persistence.
9315
9488
  */
9316
9489
  declare const PersistLogAdapter: PersistLogUtils;
9490
+ /**
9491
+ * Utility class for managing external API response cache persistence.
9492
+ *
9493
+ * Features:
9494
+ * - Memoized storage instances per cache bucket (aligned timestamp + symbol)
9495
+ * - Custom adapter support
9496
+ * - Atomic read/write operations
9497
+ * - Crash-safe cache state management
9498
+ *
9499
+ * Used by Cache.file for persistent caching of external API responses.
9500
+ */
9501
+ declare class PersistMeasureUtils {
9502
+ private PersistMeasureFactory;
9503
+ private getMeasureStorage;
9504
+ /**
9505
+ * Registers a custom persistence adapter.
9506
+ *
9507
+ * @param Ctor - Custom PersistBase constructor
9508
+ */
9509
+ usePersistMeasureAdapter(Ctor: TPersistBaseCtor<string, unknown>): void;
9510
+ /**
9511
+ * Reads cached measure data for a given bucket and key.
9512
+ *
9513
+ * @param bucket - Storage bucket (e.g. aligned timestamp + symbol)
9514
+ * @param key - Dynamic cache key within the bucket
9515
+ * @returns Promise resolving to cached value or null if not found
9516
+ */
9517
+ readMeasureData: (bucket: string, key: string) => Promise<MeasureData | null>;
9518
+ /**
9519
+ * Writes measure data to disk with atomic file writes.
9520
+ *
9521
+ * @param data - Data to cache
9522
+ * @param bucket - Storage bucket (e.g. aligned timestamp + symbol)
9523
+ * @param key - Dynamic cache key within the bucket
9524
+ * @returns Promise that resolves when write is complete
9525
+ */
9526
+ writeMeasureData: (data: MeasureData, bucket: string, key: string) => Promise<void>;
9527
+ /**
9528
+ * Switches to the default JSON persist adapter.
9529
+ */
9530
+ useJson(): void;
9531
+ /**
9532
+ * Switches to a dummy persist adapter that discards all writes.
9533
+ */
9534
+ useDummy(): void;
9535
+ }
9536
+ /**
9537
+ * Global singleton instance of PersistMeasureUtils.
9538
+ * Used by Cache.file for persistent caching of external API responses.
9539
+ */
9540
+ declare const PersistMeasureAdapter: PersistMeasureUtils;
9317
9541
 
9318
9542
  declare const WAIT_FOR_INIT_SYMBOL$1: unique symbol;
9319
9543
  declare const WRITE_SAFE_SYMBOL$1: unique symbol;
@@ -10312,6 +10536,45 @@ declare class BacktestUtils {
10312
10536
  exchangeName: ExchangeName;
10313
10537
  frameName: FrameName;
10314
10538
  }) => Promise<ISignalRow>;
10539
+ /**
10540
+ * Returns the percentage of the position currently held (not closed).
10541
+ * 100 = nothing has been closed (full position), 0 = fully closed.
10542
+ * Correctly accounts for DCA entries between partial closes.
10543
+ *
10544
+ * @param symbol - Trading pair symbol
10545
+ * @param context - Context with strategyName, exchangeName, frameName
10546
+ * @returns Promise<number> - held percentage (0–100)
10547
+ *
10548
+ * @example
10549
+ * ```typescript
10550
+ * const heldPct = await Backtest.getTotalPercentClosed("BTCUSDT", { strategyName, exchangeName, frameName });
10551
+ * console.log(`Holding ${heldPct}% of position`);
10552
+ * ```
10553
+ */
10554
+ getTotalPercentClosed: (symbol: string, context: {
10555
+ strategyName: StrategyName;
10556
+ exchangeName: ExchangeName;
10557
+ frameName: FrameName;
10558
+ }) => Promise<number>;
10559
+ /**
10560
+ * Returns the cost basis in dollars of the position currently held (not closed).
10561
+ * Correctly accounts for DCA entries between partial closes.
10562
+ *
10563
+ * @param symbol - Trading pair symbol
10564
+ * @param context - Context with strategyName, exchangeName, frameName
10565
+ * @returns Promise<number> - held cost basis in dollars
10566
+ *
10567
+ * @example
10568
+ * ```typescript
10569
+ * const heldCost = await Backtest.getTotalCostClosed("BTCUSDT", { strategyName, exchangeName, frameName });
10570
+ * console.log(`Holding $${heldCost} of position`);
10571
+ * ```
10572
+ */
10573
+ getTotalCostClosed: (symbol: string, context: {
10574
+ strategyName: StrategyName;
10575
+ exchangeName: ExchangeName;
10576
+ frameName: FrameName;
10577
+ }) => Promise<number>;
10315
10578
  /**
10316
10579
  * Retrieves the currently active scheduled signal for the strategy.
10317
10580
  * If no scheduled signal exists, returns null.
@@ -11116,6 +11379,43 @@ declare class LiveUtils {
11116
11379
  strategyName: StrategyName;
11117
11380
  exchangeName: ExchangeName;
11118
11381
  }) => Promise<ISignalRow>;
11382
+ /**
11383
+ * Returns the percentage of the position currently held (not closed).
11384
+ * 100 = nothing has been closed (full position), 0 = fully closed.
11385
+ * Correctly accounts for DCA entries between partial closes.
11386
+ *
11387
+ * @param symbol - Trading pair symbol
11388
+ * @param context - Context with strategyName and exchangeName
11389
+ * @returns Promise<number> - held percentage (0–100)
11390
+ *
11391
+ * @example
11392
+ * ```typescript
11393
+ * const heldPct = await Live.getTotalPercentClosed("BTCUSDT", { strategyName, exchangeName });
11394
+ * console.log(`Holding ${heldPct}% of position`);
11395
+ * ```
11396
+ */
11397
+ getTotalPercentClosed: (symbol: string, context: {
11398
+ strategyName: StrategyName;
11399
+ exchangeName: ExchangeName;
11400
+ }) => Promise<number>;
11401
+ /**
11402
+ * Returns the cost basis in dollars of the position currently held (not closed).
11403
+ * Correctly accounts for DCA entries between partial closes.
11404
+ *
11405
+ * @param symbol - Trading pair symbol
11406
+ * @param context - Context with strategyName and exchangeName
11407
+ * @returns Promise<number> - held cost basis in dollars
11408
+ *
11409
+ * @example
11410
+ * ```typescript
11411
+ * const heldCost = await Live.getTotalCostClosed("BTCUSDT", { strategyName, exchangeName });
11412
+ * console.log(`Holding $${heldCost} of position`);
11413
+ * ```
11414
+ */
11415
+ getTotalCostClosed: (symbol: string, context: {
11416
+ strategyName: StrategyName;
11417
+ exchangeName: ExchangeName;
11418
+ }) => Promise<number>;
11119
11419
  /**
11120
11420
  * Retrieves the currently active scheduled signal for the strategy.
11121
11421
  * If no scheduled signal exists, returns null.
@@ -14559,6 +14859,30 @@ declare const Exchange: ExchangeUtils;
14559
14859
  * Used as a constraint for cached functions.
14560
14860
  */
14561
14861
  type Function = (...args: any[]) => any;
14862
+ /**
14863
+ * Async function type for file-cached functions.
14864
+ * First argument is always `symbol: string`, followed by optional spread args.
14865
+ */
14866
+ type CacheFileFunction = (symbol: string, ...args: any[]) => Promise<any>;
14867
+ /**
14868
+ * Utility type to drop the first argument from a function type.
14869
+ * For example, for a function type `(symbol: string, arg1: number, arg2: string) => Promise<void>`,
14870
+ * this type will infer the rest of the arguments as `[arg1: number, arg2: string]`.
14871
+ */
14872
+ type DropFirst<T extends (...args: any) => any> = T extends (first: any, ...rest: infer R) => any ? R : never;
14873
+ /**
14874
+ * Extracts the `key` generator argument tuple from a `CacheFileFunction`.
14875
+ * The first two arguments are always `symbol: string` and `alignMs: number` (aligned timestamp),
14876
+ * followed by the rest of the original function's arguments.
14877
+ *
14878
+ * For example, for a function type `(symbol: string, arg1: number, arg2: string) => Promise<void>`,
14879
+ * this type will produce the tuple `[symbol: string, alignMs: number, arg1: number, arg2: string]`.
14880
+ */
14881
+ type CacheFileKeyArgs<T extends CacheFileFunction> = [
14882
+ symbol: string,
14883
+ alignMs: number,
14884
+ ...rest: DropFirst<T>
14885
+ ];
14562
14886
  /**
14563
14887
  * Utility class for function caching with timeframe-based invalidation.
14564
14888
  *
@@ -14579,7 +14903,12 @@ declare class CacheUtils {
14579
14903
  * Memoized function to get or create CacheInstance for a function.
14580
14904
  * Each function gets its own isolated cache instance.
14581
14905
  */
14582
- private _getInstance;
14906
+ private _getFnInstance;
14907
+ /**
14908
+ * Memoized function to get or create CacheFileInstance for an async function.
14909
+ * Each function gets its own isolated file-cache instance.
14910
+ */
14911
+ private _getFileInstance;
14583
14912
  /**
14584
14913
  * Wrap a function with caching based on timeframe intervals.
14585
14914
  *
@@ -14617,6 +14946,49 @@ declare class CacheUtils {
14617
14946
  interval: CandleInterval;
14618
14947
  key?: (args: Parameters<T>) => K;
14619
14948
  }) => T;
14949
+ /**
14950
+ * Wrap an async function with persistent file-based caching.
14951
+ *
14952
+ * Returns a wrapped version of the function that reads from disk on cache hit
14953
+ * and writes the result to disk on cache miss. Files are stored under
14954
+ * `./dump/data/measure/{name}_{interval}_{index}/`.
14955
+ *
14956
+ * The `run` function reference is used as the memoization key for the underlying
14957
+ * `CacheFileInstance`, so each unique function reference gets its own isolated instance.
14958
+ * Pass the same function reference each time to reuse the same cache.
14959
+ *
14960
+ * @template T - Async function type to cache
14961
+ * @param run - Async function to wrap with file caching
14962
+ * @param context.interval - Candle interval for cache invalidation
14963
+ * @param context.name - Human-readable bucket name; becomes the directory prefix
14964
+ * @param context.key - Optional entity key generator. Receives `[symbol, alignMs, ...rest]`
14965
+ * where `alignMs` is the timestamp aligned to `interval`.
14966
+ * Default: `([symbol, alignMs]) => \`${symbol}_${alignMs}\``
14967
+ * @returns Wrapped async function with automatic persistent caching
14968
+ *
14969
+ * @example
14970
+ * ```typescript
14971
+ * const fetchData = async (symbol: string, period: number) => {
14972
+ * return await externalApi.fetch(symbol, period);
14973
+ * };
14974
+ *
14975
+ * // Default key — one cache file per symbol per aligned candle
14976
+ * const cachedFetch = Cache.file(fetchData, { interval: "1h", name: "fetchData" });
14977
+ *
14978
+ * // Custom key — one cache file per symbol + period combination
14979
+ * const cachedFetch = Cache.file(fetchData, {
14980
+ * interval: "1h",
14981
+ * name: "fetchData",
14982
+ * key: ([symbol, alignMs, period]) => `${symbol}_${alignMs}_${period}`,
14983
+ * });
14984
+ * const result = await cachedFetch("BTCUSDT", 14);
14985
+ * ```
14986
+ */
14987
+ file: <T extends CacheFileFunction>(run: T, context: {
14988
+ interval: CandleInterval;
14989
+ name: string;
14990
+ key?: (args: CacheFileKeyArgs<T>) => string;
14991
+ }) => T;
14620
14992
  /**
14621
14993
  * Flush (remove) cached CacheInstance for a specific function or all functions.
14622
14994
  *
@@ -15175,6 +15547,35 @@ declare class StrategyCoreService implements TStrategy$1 {
15175
15547
  exchangeName: ExchangeName;
15176
15548
  frameName: FrameName;
15177
15549
  }) => Promise<ISignalRow | null>;
15550
+ /**
15551
+ * Returns the percentage of the position currently held (not closed).
15552
+ * 100 = nothing has been closed (full position), 0 = fully closed.
15553
+ * Correctly accounts for DCA entries between partial closes.
15554
+ *
15555
+ * @param backtest - Whether running in backtest mode
15556
+ * @param symbol - Trading pair symbol
15557
+ * @param context - Execution context with strategyName, exchangeName, frameName
15558
+ * @returns Promise<number> - held percentage (0–100)
15559
+ */
15560
+ getTotalPercentClosed: (backtest: boolean, symbol: string, context: {
15561
+ strategyName: StrategyName;
15562
+ exchangeName: ExchangeName;
15563
+ frameName: FrameName;
15564
+ }) => Promise<number | null>;
15565
+ /**
15566
+ * Returns the cost basis in dollars of the position currently held (not closed).
15567
+ * Correctly accounts for DCA entries between partial closes.
15568
+ *
15569
+ * @param backtest - Whether running in backtest mode
15570
+ * @param symbol - Trading pair symbol
15571
+ * @param context - Execution context with strategyName, exchangeName, frameName
15572
+ * @returns Promise<number> - held cost basis in dollars
15573
+ */
15574
+ getTotalCostClosed: (backtest: boolean, symbol: string, context: {
15575
+ strategyName: StrategyName;
15576
+ exchangeName: ExchangeName;
15577
+ frameName: FrameName;
15578
+ }) => Promise<number | null>;
15178
15579
  /**
15179
15580
  * Retrieves the currently active scheduled signal for the symbol.
15180
15581
  * If no scheduled signal exists, returns null.
@@ -16582,7 +16983,7 @@ declare class ActionBase implements IPublicAction {
16582
16983
  * @example
16583
16984
  * ```typescript
16584
16985
  * pingScheduled(event: SchedulePingContract) {
16585
- * const waitTime = Date.now() - event.data.timestampScheduled;
16986
+ * const waitTime = getTimestamp() - event.data.timestampScheduled;
16586
16987
  * const waitMinutes = Math.floor(waitTime / 60000);
16587
16988
  * console.log(`Scheduled signal waiting ${waitMinutes} minutes`);
16588
16989
  * }
@@ -16606,7 +17007,7 @@ declare class ActionBase implements IPublicAction {
16606
17007
  * @example
16607
17008
  * ```typescript
16608
17009
  * pingActive(event: ActivePingContract) {
16609
- * const holdTime = Date.now() - event.data.pendingAt;
17010
+ * const holdTime = getTimestamp() - event.data.pendingAt;
16610
17011
  * const holdMinutes = Math.floor(holdTime / 60000);
16611
17012
  * console.log(`Active signal holding ${holdMinutes} minutes`);
16612
17013
  * }
@@ -18028,6 +18429,35 @@ declare class StrategyConnectionService implements TStrategy {
18028
18429
  exchangeName: ExchangeName;
18029
18430
  frameName: FrameName;
18030
18431
  }) => Promise<ISignalRow | null>;
18432
+ /**
18433
+ * Returns the percentage of the position currently held (not closed).
18434
+ * 100 = nothing has been closed (full position), 0 = fully closed.
18435
+ * Correctly accounts for DCA entries between partial closes.
18436
+ *
18437
+ * @param backtest - Whether running in backtest mode
18438
+ * @param symbol - Trading pair symbol
18439
+ * @param context - Execution context with strategyName, exchangeName, frameName
18440
+ * @returns Promise<number> - held percentage (0–100)
18441
+ */
18442
+ getTotalPercentClosed: (backtest: boolean, symbol: string, context: {
18443
+ strategyName: StrategyName;
18444
+ exchangeName: ExchangeName;
18445
+ frameName: FrameName;
18446
+ }) => Promise<number | null>;
18447
+ /**
18448
+ * Returns the cost basis in dollars of the position currently held (not closed).
18449
+ * Correctly accounts for DCA entries between partial closes.
18450
+ *
18451
+ * @param backtest - Whether running in backtest mode
18452
+ * @param symbol - Trading pair symbol
18453
+ * @param context - Execution context with strategyName, exchangeName, frameName
18454
+ * @returns Promise<number> - held cost basis in dollars
18455
+ */
18456
+ getTotalCostClosed: (backtest: boolean, symbol: string, context: {
18457
+ strategyName: StrategyName;
18458
+ exchangeName: ExchangeName;
18459
+ frameName: FrameName;
18460
+ }) => Promise<number | null>;
18031
18461
  /**
18032
18462
  * Retrieves the currently active scheduled signal for the strategy.
18033
18463
  * If no scheduled signal exists, returns null.
@@ -21612,4 +22042,75 @@ declare const backtest: {
21612
22042
  loggerService: LoggerService;
21613
22043
  };
21614
22044
 
21615
- export { ActionBase, type ActivateScheduledCommit, type ActivateScheduledCommitNotification, type ActivePingContract, type AverageBuyCommit, Backtest, type BacktestStatisticsModel, Breakeven, type BreakevenAvailableNotification, type BreakevenCommit, type BreakevenCommitNotification, type BreakevenContract, type BreakevenData, Cache, type CancelScheduledCommit, type CandleData, type CandleInterval, type ClosePendingCommit, type ColumnConfig, type ColumnModel, Constant, type CriticalErrorNotification, type DoneContract, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, type IActionSchema, type IActivateScheduledCommitRow, type IAggregatedTradeData, type IBidData, type IBreakevenCommitRow, type ICandleData, type ICommitRow, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type ILog, type ILogEntry, type ILogger, type IMarkdownDumpOptions, type INotificationUtils, type IOrderBookData, type IPartialLossCommitRow, type IPartialProfitCommitRow, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IPublicAction, type IPublicCandleData, type IPublicSignalRow, type IReportDumpOptions, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskSignalRow, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalCancelRow, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingParams, type ISizingParamsATR, type ISizingParamsFixedPercentage, type ISizingParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStorageSignalRow, type IStorageUtils, type IStrategyPnL, type IStrategyResult, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IStrategyTickResultWaiting, type ITrailingStopCommitRow, type ITrailingTakeCommitRow, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, type InfoErrorNotification, Live, type LiveStatisticsModel, Log, type LogData, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, MethodContextService, type MetricStats, Notification, NotificationBacktest, type NotificationData, NotificationLive, type NotificationModel, Partial$1 as Partial, type PartialData, type PartialEvent, type PartialLossAvailableNotification, type PartialLossCommit, type PartialLossCommitNotification, type PartialLossContract, type PartialProfitAvailableNotification, type PartialProfitCommit, type PartialProfitCommitNotification, type PartialProfitContract, type PartialStatisticsModel, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatisticsModel, PersistBase, PersistBreakevenAdapter, PersistCandleAdapter, PersistLogAdapter, PersistNotificationAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PersistStorageAdapter, PositionSize, type ProgressBacktestContract, 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, Storage, StorageBacktest, type StorageData, StorageLive, Strategy, type StrategyActionType, type StrategyCancelReason, type StrategyCloseReason, type StrategyCommitContract, type StrategyEvent, type StrategyStatisticsModel, type TLogCtor, type TMarkdownBase, type TNotificationUtilsCtor, type TPersistBase, type TPersistBaseCtor, type TReportBase, type TStorageUtilsCtor, type TickEvent, type TrailingStopCommit, type TrailingStopCommitNotification, type TrailingTakeCommit, type TrailingTakeCommitNotification, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addActionSchema, addExchangeSchema, addFrameSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, alignToInterval, checkCandles, commitActivateScheduled, commitAverageBuy, commitBreakeven, commitCancelScheduled, commitClosePending, commitPartialLoss, commitPartialProfit, commitTrailingStop, commitTrailingTake, dumpMessages, emitters, formatPrice, formatQuantity, get, getActionSchema, getAggregatedTrades, getAveragePrice, getBacktestTimeframe, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getExchangeSchema, getFrameSchema, getMode, getNextCandles, getOrderBook, getRawCandles, getRiskSchema, getSizingSchema, getStrategySchema, getSymbol, getWalkerSchema, hasTradeContext, backtest as lib, listExchangeSchema, listFrameSchema, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenStrategyCommit, listenStrategyCommitOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, roundTicks, set, setColumns, setConfig, setLogger, shutdown, stopStrategy, validate, waitForCandle, warmCandles };
22045
+ /**
22046
+ * Calculates profit/loss for a closed signal with slippage and fees.
22047
+ *
22048
+ * For signals with partial closes:
22049
+ * - Weights are calculated by ACTUAL DOLLAR VALUE of each partial relative to total invested.
22050
+ * This correctly handles DCA entries that occur before or after partial closes.
22051
+ *
22052
+ * Cost basis is reconstructed by replaying the partial sequence via entryCountAtClose + percent:
22053
+ * costBasis = 0
22054
+ * for each partial[i]:
22055
+ * costBasis += (entryCountAtClose[i] - entryCountAtClose[i-1]) × $100
22056
+ * partialDollarValue[i] = (percent[i] / 100) × costBasis
22057
+ * weight[i] = partialDollarValue[i] / totalInvested
22058
+ * costBasis *= (1 - percent[i] / 100)
22059
+ *
22060
+ * Fee structure:
22061
+ * - Open fee: CC_PERCENT_FEE (charged once)
22062
+ * - Close fee: CC_PERCENT_FEE × weight × (closeWithSlip / openWithSlip) per partial/remaining
22063
+ *
22064
+ * @param signal - Closed signal with position details and optional partial history
22065
+ * @param priceClose - Actual close price at final exit
22066
+ * @returns PNL data with percentage and prices
22067
+ */
22068
+ declare const toProfitLossDto: (signal: ISignalRow, priceClose: number) => IStrategyPnL;
22069
+
22070
+ /**
22071
+ * Returns the effective entry price for price calculations.
22072
+ *
22073
+ * Uses harmonic mean (correct for fixed-dollar DCA: $100 per entry).
22074
+ *
22075
+ * When partial closes exist, replays the partial sequence to reconstruct
22076
+ * the running cost basis at each partial — no extra stored fields needed.
22077
+ *
22078
+ * Cost basis replay:
22079
+ * costBasis starts at 0
22080
+ * for each partial[i]:
22081
+ * newEntries = entryCountAtClose[i] - entryCountAtClose[i-1] (or entryCountAtClose[0] for i=0)
22082
+ * costBasis += newEntries × $100 ← add DCA entries up to this partial
22083
+ * positionCostBasisAtClose[i] = costBasis ← snapshot BEFORE close
22084
+ * costBasis × = (1 - percent[i] / 100) ← reduce after close
22085
+ *
22086
+ * @param signal - Signal row
22087
+ * @returns Effective entry price for PNL calculations
22088
+ */
22089
+ declare const getEffectivePriceOpen: (signal: ISignalRow) => number;
22090
+
22091
+ /**
22092
+ * Returns the total closed state of a position using cost-basis replay.
22093
+ *
22094
+ * Correctly accounts for DCA entries added between partial closes via averageBuy().
22095
+ * Simple percent summation (sum of _partial[i].percent) is INCORRECT when averageBuy()
22096
+ * is called between partials — this function uses the same cost-basis replay as
22097
+ * toProfitLossDto to compute the true dollar-weighted closed fraction.
22098
+ *
22099
+ * Cost-basis replay:
22100
+ * costBasis = 0
22101
+ * for each partial[i]:
22102
+ * costBasis += (entryCountAtClose[i] - entryCountAtClose[i-1]) × $100
22103
+ * closedDollar += (percent[i] / 100) × costBasis
22104
+ * costBasis ×= (1 - percent[i] / 100)
22105
+ * // then add entries added AFTER the last partial
22106
+ * costBasis += (currentEntryCount - lastPartialEntryCount) × $100
22107
+ *
22108
+ * @param signal - Signal row with _partial and _entry arrays
22109
+ * @returns Object with totalClosedPercent (0–100+) and remainingCostBasis (dollar value still open)
22110
+ */
22111
+ declare const getTotalClosed: (signal: ISignalRow) => {
22112
+ totalClosedPercent: number;
22113
+ remainingCostBasis: number;
22114
+ };
22115
+
22116
+ export { ActionBase, type ActivateScheduledCommit, type ActivateScheduledCommitNotification, type ActivePingContract, type AverageBuyCommit, Backtest, type BacktestStatisticsModel, Breakeven, type BreakevenAvailableNotification, type BreakevenCommit, type BreakevenCommitNotification, type BreakevenContract, type BreakevenData, Cache, type CancelScheduledCommit, type CandleData, type CandleInterval, type ClosePendingCommit, type ColumnConfig, type ColumnModel, Constant, type CriticalErrorNotification, type DoneContract, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, type IActionSchema, type IActivateScheduledCommitRow, type IAggregatedTradeData, type IBidData, type IBreakevenCommitRow, type ICandleData, type ICommitRow, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type ILog, type ILogEntry, type ILogger, type IMarkdownDumpOptions, type INotificationUtils, type IOrderBookData, type IPartialLossCommitRow, type IPartialProfitCommitRow, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IPublicAction, type IPublicCandleData, type IPublicSignalRow, type IReportDumpOptions, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskSignalRow, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalCancelRow, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingParams, type ISizingParamsATR, type ISizingParamsFixedPercentage, type ISizingParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStorageSignalRow, type IStorageUtils, type IStrategyPnL, type IStrategyResult, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IStrategyTickResultWaiting, type ITrailingStopCommitRow, type ITrailingTakeCommitRow, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, type InfoErrorNotification, Live, type LiveStatisticsModel, Log, type LogData, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, type MeasureData, MethodContextService, type MetricStats, Notification, NotificationBacktest, type NotificationData, NotificationLive, type NotificationModel, Partial$1 as Partial, type PartialData, type PartialEvent, type PartialLossAvailableNotification, type PartialLossCommit, type PartialLossCommitNotification, type PartialLossContract, type PartialProfitAvailableNotification, type PartialProfitCommit, type PartialProfitCommitNotification, type PartialProfitContract, type PartialStatisticsModel, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatisticsModel, PersistBase, PersistBreakevenAdapter, PersistCandleAdapter, PersistLogAdapter, PersistMeasureAdapter, PersistNotificationAdapter, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PersistStorageAdapter, PositionSize, type ProgressBacktestContract, 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, Storage, StorageBacktest, type StorageData, StorageLive, Strategy, type StrategyActionType, type StrategyCancelReason, type StrategyCloseReason, type StrategyCommitContract, type StrategyEvent, type StrategyStatisticsModel, type TLogCtor, type TMarkdownBase, type TNotificationUtilsCtor, type TPersistBase, type TPersistBaseCtor, type TReportBase, type TStorageUtilsCtor, type TickEvent, type TrailingStopCommit, type TrailingStopCommitNotification, type TrailingTakeCommit, type TrailingTakeCommitNotification, type ValidationErrorNotification, Walker, type WalkerCompleteContract, type WalkerContract, type WalkerMetric, type SignalData$1 as WalkerSignalData, type WalkerStatisticsModel, addActionSchema, addExchangeSchema, addFrameSchema, addRiskSchema, addSizingSchema, addStrategySchema, addWalkerSchema, alignToInterval, checkCandles, commitActivateScheduled, commitAverageBuy, commitBreakeven, commitCancelScheduled, commitClosePending, commitPartialLoss, commitPartialProfit, commitTrailingStop, commitTrailingTake, dumpMessages, emitters, formatPrice, formatQuantity, get, getActionSchema, getAggregatedTrades, getAveragePrice, getBacktestTimeframe, getBreakeven, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getEffectivePriceOpen, getExchangeSchema, getFrameSchema, getMode, getNextCandles, getOrderBook, getPendingSignal, getRawCandles, getRiskSchema, getScheduledSignal, getSizingSchema, getStrategySchema, getSymbol, getTimestamp, getTotalClosed, getTotalCostClosed, getTotalPercentClosed, getWalkerSchema, hasTradeContext, backtest as lib, listExchangeSchema, listFrameSchema, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenStrategyCommit, listenStrategyCommitOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, roundTicks, set, setColumns, setConfig, setLogger, shutdown, stopStrategy, toProfitLossDto, validate, waitForCandle, warmCandles };