backtest-kit 7.4.0 → 7.6.0

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
@@ -9290,6 +9290,7 @@ declare function getNextCandles(symbol: string, interval: CandleInterval, limit:
9290
9290
  */
9291
9291
  declare function getAggregatedTrades(symbol: string, limit?: number): Promise<IAggregatedTradeData[]>;
9292
9292
 
9293
+ type Dispatch$1<Value extends object = object> = (value: Value) => Value | Promise<Value>;
9293
9294
  /**
9294
9295
  * Returns the latest signal (pending or closed) for the current strategy context.
9295
9296
  *
@@ -9343,27 +9344,505 @@ declare function getLatestSignal(symbol: string): Promise<IPublicSignalRow | nul
9343
9344
  * ```
9344
9345
  */
9345
9346
  declare function getMinutesSinceLatestSignalCreated(symbol: string): Promise<number | null>;
9346
-
9347
9347
  /**
9348
- * Writes a value to memory scoped to the current signal.
9348
+ * Reads the state value scoped to the current active signal.
9349
+ *
9350
+ * Resolves the active pending signal automatically from execution context.
9351
+ * If no pending signal exists, logs a warning and returns the initialValue.
9352
+ *
9353
+ * Automatically detects backtest/live mode from execution context.
9354
+ *
9355
+ * Intended for LLM-driven capitulation strategies that accumulate per-trade
9356
+ * metrics (e.g. peakPercent, minutesOpen) across onActivePing ticks.
9357
+ * Profitable trades endure -0.5–2.5% drawdown and reach peak 2–3%+.
9358
+ * SL trades show peak < 0.15% (Feb08, Feb13) or never go positive (Feb25).
9359
+ * Rule: if minutesOpen >= N and peakPercent < threshold (e.g. 0.3%) — exit.
9360
+ *
9361
+ * @param dto.bucketName - State bucket name
9362
+ * @param dto.initialValue - Default value when no persisted state exists
9363
+ * @returns Promise resolving to current state value, or initialValue if no signal
9364
+ *
9365
+ * @deprecated Better use `createSignalState().getState` with codestyle native syntax
9366
+ *
9367
+ * @example
9368
+ * ```typescript
9369
+ * import { getSignalState } from "backtest-kit";
9370
+ *
9371
+ * const { peakPercent, minutesOpen } = await getSignalState({
9372
+ * bucketName: "trade",
9373
+ * initialValue: { peakPercent: 0, minutesOpen: 0 },
9374
+ * });
9375
+ * if (minutesOpen >= 15 && peakPercent < 0.3) {
9376
+ * await commitMarketClose(symbol); // capitulate — LLM thesis not confirmed
9377
+ * }
9378
+ * ```
9379
+ */
9380
+ declare function getSignalState<Value extends object = object>(dto: {
9381
+ bucketName: string;
9382
+ initialValue: Value;
9383
+ }): Promise<Value>;
9384
+ /**
9385
+ * Updates the state value scoped to the current active signal.
9349
9386
  *
9350
- * Reads symbol from execution context and signalId from the active pending signal.
9387
+ * Resolves the active pending signal automatically from execution context.
9351
9388
  * If no pending signal exists, logs a warning and returns without writing.
9352
9389
  *
9353
9390
  * Automatically detects backtest/live mode from execution context.
9354
9391
  *
9392
+ * Intended for LLM-driven capitulation strategies that accumulate per-trade
9393
+ * metrics (e.g. peakPercent, minutesOpen) across onActivePing ticks.
9394
+ * Profitable trades endure -0.5–2.5% drawdown and reach peak 2–3%+.
9395
+ * SL trades show peak < 0.15% (Feb08, Feb13) or never go positive (Feb25).
9396
+ * Rule: if minutesOpen >= N and peakPercent < threshold (e.g. 0.3%) — exit.
9397
+ *
9398
+ * @param dto.bucketName - State bucket name
9399
+ * @param dto.initialValue - Default value when no persisted state exists
9400
+ * @param dto.dispatch - New value or updater function receiving current value
9401
+ * @returns Promise resolving to updated state value, or initialValue if no signal
9402
+ *
9403
+ * @deprecated Better use `createSignalState().setState` with codestyle native syntax
9404
+ *
9405
+ * @example
9406
+ * ```typescript
9407
+ * import { setSignalState } from "backtest-kit";
9408
+ *
9409
+ * await setSignalState(
9410
+ * dispatch: (s) => ({
9411
+ * peakPercent: Math.max(s.peakPercent, currentUnrealisedPercent),
9412
+ * minutesOpen: s.minutesOpen + 1,
9413
+ * }),
9414
+ * {
9415
+ * bucketName: "trade",
9416
+ * initialValue: { peakPercent: 0, minutesOpen: 0 },
9417
+ * }
9418
+ * );
9419
+ * ```
9420
+ */
9421
+ declare function setSignalState<Value extends object = object>(dispatch: Value | Dispatch$1<Value>, dto: {
9422
+ bucketName: string;
9423
+ initialValue: Value;
9424
+ }): Promise<Value>;
9425
+
9426
+ /**
9427
+ * Reads the session value scoped to the current (symbol, strategy, exchange, frame) context.
9428
+ *
9429
+ * Session data persists across candles within a single run and can survive process
9430
+ * restarts in live mode — useful for caching LLM inference results, intermediate
9431
+ * indicator state, or any cross-candle accumulator that is not tied to a specific signal.
9432
+ *
9433
+ * Automatically detects backtest/live mode from execution context.
9434
+ *
9435
+ * @param symbol - Trading pair symbol
9436
+ * @returns Promise resolving to current session value, or null if not set
9437
+ *
9438
+ * @example
9439
+ * ```typescript
9440
+ * import { getSession } from "backtest-kit";
9441
+ *
9442
+ * const session = await getSession<{ lastLlmSignal: string }>("BTCUSDT");
9443
+ * if (session?.lastLlmSignal === "buy") {
9444
+ * // reuse cached LLM result instead of calling the model again
9445
+ * }
9446
+ * ```
9447
+ */
9448
+ declare function getSessionData<Value extends object = object>(symbol: string): Promise<Value | null>;
9449
+ /**
9450
+ * Writes a session value scoped to the current (symbol, strategy, exchange, frame) context.
9451
+ *
9452
+ * Session data persists across candles within a single run and can survive process
9453
+ * restarts in live mode — useful for caching LLM inference results, intermediate
9454
+ * indicator state, or any cross-candle accumulator that is not tied to a specific signal.
9455
+ *
9456
+ * Pass null to clear the session.
9457
+ *
9458
+ * Automatically detects backtest/live mode from execution context.
9459
+ *
9460
+ * @param symbol - Trading pair symbol
9461
+ * @param value - New value or null to clear
9462
+ * @returns Promise that resolves when the session has been written
9463
+ *
9464
+ * @example
9465
+ * ```typescript
9466
+ * import { setSession } from "backtest-kit";
9467
+ *
9468
+ * await setSession("BTCUSDT", { lastLlmSignal: "buy" });
9469
+ * ```
9470
+ */
9471
+ declare function setSessionData<Value extends object = object>(symbol: string, value: Value | null): Promise<void>;
9472
+
9473
+ /**
9474
+ * Updater function for setState — receives current value and returns the next value.
9475
+ * Used for functional updates to state, e.g. `setState(prev => ({ ...prev, peakPercent: newPeak }))`
9476
+ */
9477
+ type Dispatch<Value extends object = object> = (value: Value) => Value | Promise<Value>;
9478
+ /**
9479
+ * Logical namespace for grouping state buckets within a signal, e.g. "trade" or "metrics".
9480
+ * Used to scope state values for different purposes within the same signal — e.g. "trade" bucket for tracking peakPercent and minutesOpen, "metrics" bucket for tracking other LLM confirmation metrics.
9481
+ */
9482
+ type BucketName = string;
9483
+ /**
9484
+ * Interface for state instance implementations.
9485
+ * Defines the contract for local, persist, and dummy backends.
9486
+ *
9487
+ * Intended use: per-signal mutable state for LLM-driven strategies that track
9488
+ * trade confirmation metrics across the position lifetime — e.g. peak unrealised PnL,
9489
+ * minutes since entry, and capitulation thresholds.
9490
+ *
9491
+ * Example shape:
9492
+ * ```ts
9493
+ * { peakPercent: number; minutesOpen: number }
9494
+ * ```
9495
+ * Profitable trades endure -0.5–2.5% drawdown yet still reach peak 2–3%+.
9496
+ * SL trades either never go positive (Feb25) or show peak < 0.15% (Feb08, Feb13).
9497
+ * Capitulation rule: if position open N minutes and peak < threshold (e.g. 0.3%) —
9498
+ * LLM thesis was not confirmed by market, exit immediately.
9499
+ */
9500
+ interface IStateInstance {
9501
+ /**
9502
+ * Initialize the state instance.
9503
+ * @param initial - Whether this is the first initialization
9504
+ */
9505
+ waitForInit(initial: boolean): Promise<void>;
9506
+ /**
9507
+ * Read the current state value.
9508
+ * @returns Current state value
9509
+ */
9510
+ getState<Value extends object = object>(): Promise<Value>;
9511
+ /**
9512
+ * Update the state value.
9513
+ * @param dispatch - New value or updater function receiving current value
9514
+ * @returns Updated state value
9515
+ */
9516
+ setState<Value extends object = object>(dispatch: Value | Dispatch<Value>): Promise<Value>;
9517
+ /**
9518
+ * Releases any resources held by this instance.
9519
+ */
9520
+ dispose(): Promise<void>;
9521
+ }
9522
+ /**
9523
+ * Constructor type for state instance implementations.
9524
+ * Used for swapping backends via StateBacktestAdapter / StateLiveAdapter.
9525
+ */
9526
+ type TStateInstanceCtor = new (initialValue: object, signalId: string, bucketName: string) => IStateInstance;
9527
+ /**
9528
+ * Public surface of StateBacktestAdapter / StateLiveAdapter — IStateInstance minus waitForInit and dispose.
9529
+ * waitForInit and dispose are managed internally by the adapter.
9530
+ */
9531
+ type TStateAdapter = {
9532
+ [key in Exclude<keyof IStateInstance, "waitForInit" | "dispose">]: any;
9533
+ };
9534
+ /**
9535
+ * Backtest state adapter with pluggable storage backend.
9536
+ *
9537
+ * Features:
9538
+ * - Adapter pattern for swappable state instance implementations
9539
+ * - Default backend: StateLocalInstance (in-memory, no disk persistence)
9540
+ * - Alternative backends: StatePersistInstance, StateDummyInstance
9541
+ * - Convenience methods: useLocal(), usePersist(), useDummy(), useStateAdapter()
9542
+ * - Memoized instances per (signalId, bucketName) pair; cleared via disposeSignal() from StateAdapter
9543
+ *
9544
+ * Primary use case — LLM-driven capitulation rule:
9545
+ * Profitable trades endure -0.5–2.5% drawdown and still reach peak 2–3%+.
9546
+ * SL trades never go positive (Feb25) or show peak < 0.15% (Feb08, Feb13).
9547
+ * Rule: if position open >= N minutes and peakPercent < threshold (e.g. 0.3%),
9548
+ * the LLM thesis was not confirmed by market — exit immediately.
9549
+ * State tracks `{ peakPercent, minutesOpen }` per signal across onActivePing ticks.
9550
+ */
9551
+ declare class StateBacktestAdapter implements TStateAdapter {
9552
+ private StateFactory;
9553
+ private getInstance;
9554
+ /**
9555
+ * Disposes all memoized instances for the given signalId.
9556
+ * Called by StateAdapter when a signal is cancelled or closed.
9557
+ * @param signalId - Signal identifier to dispose
9558
+ */
9559
+ disposeSignal: (signalId: string) => void;
9560
+ /**
9561
+ * Read the current state value for a signal.
9562
+ * @param dto.signalId - Signal identifier
9563
+ * @param dto.bucketName - Bucket name
9564
+ * @param dto.initialValue - Default value when no persisted state exists
9565
+ * @returns Current state value
9566
+ */
9567
+ getState: <Value extends object = object>(dto: {
9568
+ signalId: string;
9569
+ bucketName: BucketName;
9570
+ initialValue: object;
9571
+ }) => Promise<Value>;
9572
+ /**
9573
+ * Update the state value for a signal.
9574
+ * @param dispatch - New value or updater function receiving current value
9575
+ * @param dto.signalId - Signal identifier
9576
+ * @param dto.bucketName - Bucket name
9577
+ * @param dto.initialValue - Default value when no persisted state exists
9578
+ * @returns Updated state value
9579
+ */
9580
+ setState: <Value extends object = object>(dispatch: Value | Dispatch<Value>, dto: {
9581
+ signalId: string;
9582
+ bucketName: BucketName;
9583
+ initialValue: object;
9584
+ }) => Promise<Value>;
9585
+ /**
9586
+ * Switches to in-memory adapter (default).
9587
+ * All data lives in process memory only.
9588
+ */
9589
+ useLocal: () => void;
9590
+ /**
9591
+ * Switches to file-system backed adapter.
9592
+ * Data is persisted to disk via PersistStateAdapter.
9593
+ */
9594
+ usePersist: () => void;
9595
+ /**
9596
+ * Switches to dummy adapter that discards all writes.
9597
+ */
9598
+ useDummy: () => void;
9599
+ /**
9600
+ * Switches to a custom state adapter implementation.
9601
+ * @param Ctor - Constructor for the custom state instance
9602
+ */
9603
+ useStateAdapter: (Ctor: TStateInstanceCtor) => void;
9604
+ /**
9605
+ * Clears the memoized instance cache.
9606
+ * Call this when process.cwd() changes between strategy iterations
9607
+ * so new instances are created with the updated base path.
9608
+ */
9609
+ clear: () => void;
9610
+ }
9611
+ /**
9612
+ * Live trading state adapter with pluggable storage backend.
9613
+ *
9614
+ * Features:
9615
+ * - Adapter pattern for swappable state instance implementations
9616
+ * - Default backend: StatePersistInstance (file-system backed, survives restarts)
9617
+ * - Alternative backends: StateLocalInstance, StateDummyInstance
9618
+ * - Convenience methods: useLocal(), usePersist(), useDummy(), useStateAdapter()
9619
+ * - Memoized instances per (signalId, bucketName) pair; cleared via disposeSignal() from StateAdapter
9620
+ *
9621
+ * Primary use case — LLM-driven capitulation rule:
9622
+ * Profitable trades endure -0.5–2.5% drawdown and still reach peak 2–3%+.
9623
+ * SL trades never go positive (Feb25) or show peak < 0.15% (Feb08, Feb13).
9624
+ * Rule: if position open >= N minutes and peakPercent < threshold (e.g. 0.3%),
9625
+ * the LLM thesis was not confirmed by market — exit immediately.
9626
+ * State persists `{ peakPercent, minutesOpen }` per signal across process restarts.
9627
+ */
9628
+ declare class StateLiveAdapter implements TStateAdapter {
9629
+ private StateFactory;
9630
+ private getInstance;
9631
+ /**
9632
+ * Disposes all memoized instances for the given signalId.
9633
+ * Called by StateAdapter when a signal is cancelled or closed.
9634
+ * @param signalId - Signal identifier to dispose
9635
+ */
9636
+ disposeSignal: (signalId: string) => void;
9637
+ /**
9638
+ * Read the current state value for a signal.
9639
+ * @param dto.signalId - Signal identifier
9640
+ * @param dto.bucketName - Bucket name
9641
+ * @param dto.initialValue - Default value when no persisted state exists
9642
+ * @returns Current state value
9643
+ */
9644
+ getState: <Value extends object = object>(dto: {
9645
+ signalId: string;
9646
+ bucketName: BucketName;
9647
+ initialValue: object;
9648
+ }) => Promise<Value>;
9649
+ /**
9650
+ * Update the state value for a signal.
9651
+ * @param dispatch - New value or updater function receiving current value
9652
+ * @param dto.signalId - Signal identifier
9653
+ * @param dto.bucketName - Bucket name
9654
+ * @param dto.initialValue - Default value when no persisted state exists
9655
+ * @returns Updated state value
9656
+ */
9657
+ setState: <Value extends object = object>(dispatch: Value | Dispatch<Value>, dto: {
9658
+ signalId: string;
9659
+ bucketName: BucketName;
9660
+ initialValue: object;
9661
+ }) => Promise<Value>;
9662
+ /**
9663
+ * Switches to in-memory adapter.
9664
+ * All data lives in process memory only.
9665
+ */
9666
+ useLocal: () => void;
9667
+ /**
9668
+ * Switches to file-system backed adapter (default).
9669
+ * Data is persisted to disk via PersistStateAdapter.
9670
+ */
9671
+ usePersist: () => void;
9672
+ /**
9673
+ * Switches to dummy adapter that discards all writes.
9674
+ */
9675
+ useDummy: () => void;
9676
+ /**
9677
+ * Switches to a custom state adapter implementation.
9678
+ * @param Ctor - Constructor for the custom state instance
9679
+ */
9680
+ useStateAdapter: (Ctor: TStateInstanceCtor) => void;
9681
+ /**
9682
+ * Clears the memoized instance cache.
9683
+ * Call this when process.cwd() changes between strategy iterations
9684
+ * so new instances are created with the updated base path.
9685
+ */
9686
+ clear: () => void;
9687
+ }
9688
+ /**
9689
+ * Main state adapter that manages both backtest and live state storage.
9690
+ *
9691
+ * Features:
9692
+ * - Subscribes to signal lifecycle events (cancelled/closed) to dispose stale instances
9693
+ * - Routes all operations to StateBacktest or StateLive based on dto.backtest
9694
+ * - Singleshot enable pattern prevents duplicate subscriptions
9695
+ * - Cleanup function for proper unsubscription
9696
+ */
9697
+ declare class StateAdapter {
9698
+ /**
9699
+ * Enables state storage by subscribing to signal lifecycle events.
9700
+ * Clears memoized instances in StateBacktest and StateLive when a signal
9701
+ * is cancelled or closed, preventing stale instances from accumulating.
9702
+ * Uses singleshot to ensure one-time subscription.
9703
+ *
9704
+ * @returns Cleanup function that unsubscribes from all emitters
9705
+ */
9706
+ enable: (() => (...args: any[]) => any) & functools_kit.ISingleshotClearable<() => (...args: any[]) => any>;
9707
+ /**
9708
+ * Disables state storage by unsubscribing from signal lifecycle events.
9709
+ * Safe to call multiple times.
9710
+ */
9711
+ disable: () => void;
9712
+ /**
9713
+ * Read the current state value for a signal.
9714
+ * Routes to StateBacktest or StateLive based on dto.backtest.
9715
+ * @param dto.signalId - Signal identifier
9716
+ * @param dto.bucketName - Bucket name
9717
+ * @param dto.initialValue - Default value when no persisted state exists
9718
+ * @param dto.backtest - Flag indicating if the context is backtest or live
9719
+ * @returns Current state value
9720
+ * @throws Error if adapter is not enabled
9721
+ */
9722
+ getState: <Value extends object = object>(dto: {
9723
+ signalId: string;
9724
+ bucketName: BucketName;
9725
+ initialValue: object;
9726
+ backtest: boolean;
9727
+ }) => Promise<Value>;
9728
+ /**
9729
+ * Update the state value for a signal.
9730
+ * Routes to StateBacktest or StateLive based on dto.backtest.
9731
+ * @param dispatch - New value or updater function receiving current value
9732
+ * @param dto.signalId - Signal identifier
9733
+ * @param dto.bucketName - Bucket name
9734
+ * @param dto.initialValue - Default value when no persisted state exists
9735
+ * @param dto.backtest - Flag indicating if the context is backtest or live
9736
+ * @returns Updated state value
9737
+ * @throws Error if adapter is not enabled
9738
+ */
9739
+ setState: <Value extends object = object>(dispatch: Value | Dispatch<Value>, dto: {
9740
+ signalId: string;
9741
+ bucketName: BucketName;
9742
+ initialValue: object;
9743
+ backtest: boolean;
9744
+ }) => Promise<Value>;
9745
+ }
9746
+ /**
9747
+ * Global singleton instance of StateAdapter.
9748
+ * Provides unified state management for backtest and live trading.
9749
+ */
9750
+ declare const State: StateAdapter;
9751
+ /**
9752
+ * Global singleton instance of StateLiveAdapter.
9753
+ * Provides live trading state storage with pluggable backends.
9754
+ */
9755
+ declare const StateLive: StateLiveAdapter;
9756
+ /**
9757
+ * Global singleton instance of StateBacktestAdapter.
9758
+ * Provides backtest state storage with pluggable backends.
9759
+ */
9760
+ declare const StateBacktest: StateBacktestAdapter;
9761
+
9762
+ /**
9763
+ * Parameters for createSignalState — bucket name and default value shape.
9764
+ */
9765
+ interface IStateParams<Value extends object = object> {
9766
+ /** Logical namespace for grouping state buckets within a signal, e.g. "trade" or "metrics". */
9767
+ bucketName: BucketName;
9768
+ /** Default value used when no persisted state exists for the signal. */
9769
+ initialValue: Value;
9770
+ }
9771
+ /**
9772
+ * Reads the current state value for the active pending or scheduled signal.
9773
+ * Resolved from execution context — no signalId argument required.
9774
+ * @returns Current state value
9775
+ * @throws Error if no pending or scheduled signal exists
9776
+ */
9777
+ type GetStateFn<Value extends object = object> = () => Promise<Value>;
9778
+ /**
9779
+ * Updates the state value for the active pending or scheduled signal.
9780
+ * Resolved from execution context — no signalId argument required.
9781
+ * @param dispatch - New value or updater function receiving current value
9782
+ * @returns Updated state value
9783
+ * @throws Error if no pending or scheduled signal exists
9784
+ */
9785
+ type SetStateFn<Value extends object = object> = (dispatch: Value | Dispatch<Value>) => Promise<Value>;
9786
+ /**
9787
+ * Tuple returned by createSignalState — [getState, setState] bound to the bucket.
9788
+ * Both functions resolve the active signal and backtest flag from execution context automatically.
9789
+ */
9790
+ type SignalStateTuple<Value extends object = object> = [GetStateFn<Value>, SetStateFn<Value>];
9791
+ /**
9792
+ * Creates a bound [getState, setState] tuple scoped to a bucket and initial value.
9793
+ *
9794
+ * Both returned functions resolve the active pending or scheduled signal and the
9795
+ * backtest/live flag automatically from execution context — no signalId argument required.
9796
+ *
9797
+ * Automatically detects backtest/live mode from execution context.
9798
+ *
9799
+ * Intended for LLM-driven capitulation strategies that accumulate per-trade
9800
+ * metrics (e.g. peakPercent, minutesOpen) across onActivePing ticks.
9801
+ * Profitable trades endure -0.5–2.5% drawdown and reach peak 2–3%+.
9802
+ * SL trades show peak < 0.15% (Feb08, Feb13) or never go positive (Feb25).
9803
+ * Rule: if minutesOpen >= N and peakPercent < threshold (e.g. 0.3%) — exit.
9804
+ *
9805
+ * @param params.bucketName - Logical namespace for grouping state buckets within a signal
9806
+ * @param params.initialValue - Default value when no persisted state exists
9807
+ * @returns Tuple [getState, setState] bound to the bucket and initial value
9808
+ *
9809
+ * @example
9810
+ * ```typescript
9811
+ * import { createSignalState } from "backtest-kit";
9812
+ *
9813
+ * const [getTradeState, setTradeState] = createSignalState({
9814
+ * bucketName: "trade",
9815
+ * initialValue: { peakPercent: 0, minutesOpen: 0 },
9816
+ * });
9817
+ *
9818
+ * // in onActivePing:
9819
+ * await setTradeState((s) => ({
9820
+ * peakPercent: Math.max(s.peakPercent, currentUnrealisedPercent),
9821
+ * minutesOpen: s.minutesOpen + 1,
9822
+ * }));
9823
+ * const { peakPercent, minutesOpen } = await getTradeState();
9824
+ * if (minutesOpen >= 15 && peakPercent < 0.3) await commitMarketClose(symbol);
9825
+ * ```
9826
+ */
9827
+ declare function createSignalState<Value extends object = object>(params: IStateParams<Value>): SignalStateTuple<Value>;
9828
+
9829
+ /**
9830
+ * Writes a value to memory scoped to the current signal.
9831
+ *
9832
+ * Resolves the active pending or scheduled signal automatically from execution context.
9833
+ * Automatically detects backtest/live mode from execution context.
9834
+ *
9355
9835
  * @param dto.bucketName - Memory bucket name
9356
9836
  * @param dto.memoryId - Unique memory entry identifier
9357
9837
  * @param dto.value - Value to store
9838
+ * @param dto.description - BM25 index string for contextual search
9358
9839
  * @returns Promise that resolves when write is complete
9359
9840
  *
9360
- * @deprecated Better use Memory.writeMemory with manual signalId argument
9361
- *
9362
9841
  * @example
9363
9842
  * ```typescript
9364
9843
  * import { writeMemory } from "backtest-kit";
9365
9844
  *
9366
- * await writeMemory({ bucketName: "my-strategy", memoryId: "context", value: { trend: "up", confidence: 0.9 } });
9845
+ * await writeMemory({ bucketName: "my-strategy", memoryId: "context", value: { trend: "up", confidence: 0.9 }, description: "Signal context at entry" });
9367
9846
  * ```
9368
9847
  */
9369
9848
  declare function writeMemory<T extends object = object>(dto: {
@@ -9375,17 +9854,13 @@ declare function writeMemory<T extends object = object>(dto: {
9375
9854
  /**
9376
9855
  * Reads a value from memory scoped to the current signal.
9377
9856
  *
9378
- * Reads symbol from execution context and signalId from the active pending signal.
9379
- * If no pending signal exists, logs a warning and returns null.
9380
- *
9857
+ * Resolves the active pending or scheduled signal automatically from execution context.
9381
9858
  * Automatically detects backtest/live mode from execution context.
9382
9859
  *
9383
9860
  * @param dto.bucketName - Memory bucket name
9384
9861
  * @param dto.memoryId - Unique memory entry identifier
9385
- * @returns Promise resolving to stored value or null if no signal
9386
- * @throws Error if entry not found within an active signal
9387
- *
9388
- * @deprecated Better use Memory.readMemory with manual signalId argument
9862
+ * @returns Promise resolving to stored value
9863
+ * @throws Error if no pending or scheduled signal exists, or if entry not found
9389
9864
  *
9390
9865
  * @example
9391
9866
  * ```typescript
@@ -9397,20 +9872,17 @@ declare function writeMemory<T extends object = object>(dto: {
9397
9872
  declare function readMemory<T extends object = object>(dto: {
9398
9873
  bucketName: string;
9399
9874
  memoryId: string;
9400
- }): Promise<T | null>;
9875
+ }): Promise<T>;
9401
9876
  /**
9402
9877
  * Searches memory entries for the current signal using BM25 full-text scoring.
9403
9878
  *
9404
- * Reads symbol from execution context and signalId from the active pending signal.
9405
- * If no pending signal exists, logs a warning and returns an empty array.
9406
- *
9879
+ * Resolves the active pending or scheduled signal automatically from execution context.
9407
9880
  * Automatically detects backtest/live mode from execution context.
9408
9881
  *
9409
9882
  * @param dto.bucketName - Memory bucket name
9410
9883
  * @param dto.query - Search query string
9411
- * @returns Promise resolving to matching entries sorted by relevance, or empty array if no signal
9412
- *
9413
- * @deprecated Better use Memory.searchMemory with manual signalId argument
9884
+ * @returns Promise resolving to matching entries sorted by relevance
9885
+ * @throws Error if no pending or scheduled signal exists
9414
9886
  *
9415
9887
  * @example
9416
9888
  * ```typescript
@@ -9430,15 +9902,12 @@ declare function searchMemory<T extends object = object>(dto: {
9430
9902
  /**
9431
9903
  * Lists all memory entries for the current signal.
9432
9904
  *
9433
- * Reads symbol from execution context and signalId from the active pending signal.
9434
- * If no pending signal exists, logs a warning and returns an empty array.
9435
- *
9905
+ * Resolves the active pending or scheduled signal automatically from execution context.
9436
9906
  * Automatically detects backtest/live mode from execution context.
9437
9907
  *
9438
9908
  * @param dto.bucketName - Memory bucket name
9439
- * @returns Promise resolving to all stored entries, or empty array if no signal
9440
- *
9441
- * @deprecated Better use Memory.listMemory with manual signalId argument
9909
+ * @returns Promise resolving to all stored entries
9910
+ * @throws Error if no pending or scheduled signal exists
9442
9911
  *
9443
9912
  * @example
9444
9913
  * ```typescript
@@ -9456,16 +9925,13 @@ declare function listMemory<T extends object = object>(dto: {
9456
9925
  /**
9457
9926
  * Removes a memory entry for the current signal.
9458
9927
  *
9459
- * Reads symbol from execution context and signalId from the active pending signal.
9460
- * If no pending signal exists, logs a warning and returns without removing.
9461
- *
9928
+ * Resolves the active pending or scheduled signal automatically from execution context.
9462
9929
  * Automatically detects backtest/live mode from execution context.
9463
9930
  *
9464
9931
  * @param dto.bucketName - Memory bucket name
9465
9932
  * @param dto.memoryId - Unique memory entry identifier
9466
9933
  * @returns Promise that resolves when removal is complete
9467
- *
9468
- * @deprecated Better use Memory.removeMemory with manual signalId argument
9934
+ * @throws Error if no pending or scheduled signal exists
9469
9935
  *
9470
9936
  * @example
9471
9937
  * ```typescript
@@ -9522,16 +9988,15 @@ interface MessageModel<Role extends MessageRole = MessageRole> {
9522
9988
  /**
9523
9989
  * Dumps the full agent message history scoped to the current signal.
9524
9990
  *
9525
- * Reads signalId from the active pending signal via execution and method context.
9526
- * If no pending signal exists, logs a warning and returns without writing.
9991
+ * Resolves the active pending or scheduled signal automatically from execution context.
9992
+ * Automatically detects backtest/live mode from execution context.
9527
9993
  *
9528
9994
  * @param dto.bucketName - Bucket name grouping dumps by strategy or agent name
9529
9995
  * @param dto.dumpId - Unique identifier for this agent invocation
9530
9996
  * @param dto.messages - Full chat history (system, user, assistant, tool)
9531
9997
  * @param dto.description - Human-readable label describing the agent invocation context; included in the BM25 index for Memory search
9532
9998
  * @returns Promise that resolves when the dump is complete
9533
- *
9534
- * @deprecated Better use Dump.dumpAgentAnswer with manual signalId argument
9999
+ * @throws Error if no pending or scheduled signal exists
9535
10000
  *
9536
10001
  * @example
9537
10002
  * ```typescript
@@ -9549,16 +10014,15 @@ declare function dumpAgentAnswer(dto: {
9549
10014
  /**
9550
10015
  * Dumps a flat key-value record scoped to the current signal.
9551
10016
  *
9552
- * Reads signalId from the active pending signal via execution and method context.
9553
- * If no pending signal exists, logs a warning and returns without writing.
10017
+ * Resolves the active pending or scheduled signal automatically from execution context.
10018
+ * Automatically detects backtest/live mode from execution context.
9554
10019
  *
9555
10020
  * @param dto.bucketName - Bucket name grouping dumps by strategy or agent name
9556
10021
  * @param dto.dumpId - Unique identifier for this dump entry
9557
10022
  * @param dto.record - Arbitrary flat object to persist
9558
10023
  * @param dto.description - Human-readable label describing the record contents; included in the BM25 index for Memory search
9559
10024
  * @returns Promise that resolves when the dump is complete
9560
- *
9561
- * @deprecated Better use Dump.dumpRecord with manual signalId argument
10025
+ * @throws Error if no pending or scheduled signal exists
9562
10026
  *
9563
10027
  * @example
9564
10028
  * ```typescript
@@ -9576,8 +10040,8 @@ declare function dumpRecord(dto: {
9576
10040
  /**
9577
10041
  * Dumps an array of objects as a table scoped to the current signal.
9578
10042
  *
9579
- * Reads signalId from the active pending signal via execution and method context.
9580
- * If no pending signal exists, logs a warning and returns without writing.
10043
+ * Resolves the active pending or scheduled signal automatically from execution context.
10044
+ * Automatically detects backtest/live mode from execution context.
9581
10045
  *
9582
10046
  * Column headers are derived from the union of all keys across all rows.
9583
10047
  *
@@ -9586,8 +10050,7 @@ declare function dumpRecord(dto: {
9586
10050
  * @param dto.rows - Array of arbitrary objects to render as a table
9587
10051
  * @param dto.description - Human-readable label describing the table contents; included in the BM25 index for Memory search
9588
10052
  * @returns Promise that resolves when the dump is complete
9589
- *
9590
- * @deprecated Better use Dump.dumpTable with manual signalId argument
10053
+ * @throws Error if no pending or scheduled signal exists
9591
10054
  *
9592
10055
  * @example
9593
10056
  * ```typescript
@@ -9605,16 +10068,15 @@ declare function dumpTable(dto: {
9605
10068
  /**
9606
10069
  * Dumps raw text content scoped to the current signal.
9607
10070
  *
9608
- * Reads signalId from the active pending signal via execution and method context.
9609
- * If no pending signal exists, logs a warning and returns without writing.
10071
+ * Resolves the active pending or scheduled signal automatically from execution context.
10072
+ * Automatically detects backtest/live mode from execution context.
9610
10073
  *
9611
10074
  * @param dto.bucketName - Bucket name grouping dumps by strategy or agent name
9612
10075
  * @param dto.dumpId - Unique identifier for this dump entry
9613
10076
  * @param dto.content - Arbitrary text content to persist
9614
10077
  * @param dto.description - Human-readable label describing the content; included in the BM25 index for Memory search
9615
10078
  * @returns Promise that resolves when the dump is complete
9616
- *
9617
- * @deprecated Better use Dump.dumpText with manual signalId argument
10079
+ * @throws Error if no pending or scheduled signal exists
9618
10080
  *
9619
10081
  * @example
9620
10082
  * ```typescript
@@ -9632,16 +10094,15 @@ declare function dumpText(dto: {
9632
10094
  /**
9633
10095
  * Dumps an error description scoped to the current signal.
9634
10096
  *
9635
- * Reads signalId from the active pending signal via execution and method context.
9636
- * If no pending signal exists, logs a warning and returns without writing.
10097
+ * Resolves the active pending or scheduled signal automatically from execution context.
10098
+ * Automatically detects backtest/live mode from execution context.
9637
10099
  *
9638
10100
  * @param dto.bucketName - Bucket name grouping dumps by strategy or agent name
9639
10101
  * @param dto.dumpId - Unique identifier for this dump entry
9640
10102
  * @param dto.content - Error message or description to persist
9641
10103
  * @param dto.description - Human-readable label describing the error context; included in the BM25 index for Memory search
9642
10104
  * @returns Promise that resolves when the dump is complete
9643
- *
9644
- * @deprecated Better use Dump.dumpError with manual signalId argument
10105
+ * @throws Error if no pending or scheduled signal exists
9645
10106
  *
9646
10107
  * @example
9647
10108
  * ```typescript
@@ -9659,14 +10120,15 @@ declare function dumpError(dto: {
9659
10120
  /**
9660
10121
  * Dumps an arbitrary nested object as a fenced JSON block scoped to the current signal.
9661
10122
  *
9662
- * Reads signalId from the active pending signal via execution and method context.
9663
- * If no pending signal exists, logs a warning and returns without writing.
10123
+ * Resolves the active pending or scheduled signal automatically from execution context.
10124
+ * Automatically detects backtest/live mode from execution context.
9664
10125
  *
9665
10126
  * @param dto.bucketName - Bucket name grouping dumps by strategy or agent name
9666
10127
  * @param dto.dumpId - Unique identifier for this dump entry
9667
10128
  * @param dto.json - Arbitrary nested object to serialize with JSON.stringify
9668
10129
  * @param dto.description - Human-readable label describing the object contents; included in the BM25 index for Memory search
9669
10130
  * @returns Promise that resolves when the dump is complete
10131
+ * @throws Error if no pending or scheduled signal exists
9670
10132
  *
9671
10133
  * @deprecated Prefer dumpRecord — flat key-value structure maps naturally to markdown tables and SQL storage
9672
10134
  *
@@ -13550,6 +14012,176 @@ declare class PersistRecentUtils {
13550
14012
  * Used by RecentPersistBacktestUtils/RecentPersistLiveUtils for recent signal persistence.
13551
14013
  */
13552
14014
  declare const PersistRecentAdapter: PersistRecentUtils;
14015
+ /**
14016
+ * Type for persisted state entry data.
14017
+ * Wraps an arbitrary JSON-serializable object with a unique id.
14018
+ */
14019
+ type StateData = {
14020
+ id: string;
14021
+ data: object;
14022
+ };
14023
+ /**
14024
+ * Utility class for managing state persistence.
14025
+ *
14026
+ * Features:
14027
+ * - Memoized storage instances per (signalId, bucketName) pair
14028
+ * - Custom adapter support
14029
+ * - Atomic read/write operations
14030
+ *
14031
+ * Storage layout: ./dump/state/<signalId>/<bucketName>.json
14032
+ *
14033
+ * Used by StatePersistInstance for crash-safe state persistence.
14034
+ */
14035
+ declare class PersistStateUtils {
14036
+ private PersistStateFactory;
14037
+ private getStateStorage;
14038
+ /**
14039
+ * Registers a custom persistence adapter.
14040
+ *
14041
+ * @param Ctor - Custom PersistBase constructor
14042
+ */
14043
+ usePersistStateAdapter(Ctor: TPersistBaseCtor<string, StateData>): void;
14044
+ /**
14045
+ * Initializes the storage for a given (signalId, bucketName) pair.
14046
+ *
14047
+ * @param signalId - Signal identifier
14048
+ * @param bucketName - Bucket name
14049
+ * @param initial - Whether this is the first initialization
14050
+ */
14051
+ waitForInit: (signalId: string, bucketName: string, initial: boolean) => Promise<void>;
14052
+ /**
14053
+ * Reads a state entry from persistence storage.
14054
+ *
14055
+ * @param signalId - Signal identifier
14056
+ * @param bucketName - Bucket name
14057
+ * @returns Promise resolving to entry data or null if not found
14058
+ */
14059
+ readStateData: (signalId: string, bucketName: string) => Promise<StateData | null>;
14060
+ /**
14061
+ * Writes a state entry to disk with atomic file writes.
14062
+ *
14063
+ * @param data - Entry data to persist
14064
+ * @param signalId - Signal identifier
14065
+ * @param bucketName - Bucket name
14066
+ */
14067
+ writeStateData: (data: StateData, signalId: string, bucketName: string) => Promise<void>;
14068
+ /**
14069
+ * Switches to a dummy persist adapter that discards all writes.
14070
+ * All future persistence writes will be no-ops.
14071
+ */
14072
+ useDummy: () => void;
14073
+ /**
14074
+ * Switches to the default JSON persist adapter.
14075
+ * All future persistence writes will use JSON storage.
14076
+ */
14077
+ useJson: () => void;
14078
+ /**
14079
+ * Clears the memoized storage cache.
14080
+ * Call this when process.cwd() changes between strategy iterations
14081
+ * so new storage instances are created with the updated base path.
14082
+ */
14083
+ clear: () => void;
14084
+ /**
14085
+ * Disposes of the state adapter and releases any resources.
14086
+ * Call this when a signal is removed to clean up its associated storage.
14087
+ *
14088
+ * @param signalId - Signal identifier
14089
+ * @param bucketName - Bucket name
14090
+ */
14091
+ dispose: (signalId: string, bucketName: string) => void;
14092
+ }
14093
+ /**
14094
+ * Global singleton instance of PersistStateUtils.
14095
+ * Used by StatePersistInstance for crash-safe state persistence.
14096
+ */
14097
+ declare const PersistStateAdapter: PersistStateUtils;
14098
+ /**
14099
+ * Session data structure for session persistence.
14100
+ * Each session is identified by a unique id and contains an arbitrary JSON-serializable data object.
14101
+ */
14102
+ type SessionData = {
14103
+ id: string;
14104
+ data: object | null;
14105
+ };
14106
+ /**
14107
+ * Utility class for managing session persistence.
14108
+ *
14109
+ * Features:
14110
+ * - Memoized storage instances per (strategyName, exchangeName, frameName) key
14111
+ * - Custom adapter support
14112
+ * - Atomic read/write operations
14113
+ *
14114
+ * Storage layout: ./dump/session/<strategyName>/<exchangeName>/<frameName>.json
14115
+ *
14116
+ * Used by SessionPersistInstance for crash-safe session persistence.
14117
+ */
14118
+ declare class PersistSessionUtils {
14119
+ private PersistSessionFactory;
14120
+ private getSessionStorage;
14121
+ /**
14122
+ * Registers a custom persistence adapter.
14123
+ *
14124
+ * @param Ctor - Custom PersistBase constructor
14125
+ */
14126
+ usePersistSessionAdapter(Ctor: TPersistBaseCtor<string, SessionData>): void;
14127
+ /**
14128
+ * Initializes the storage for a given (strategyName, exchangeName, frameName) triple.
14129
+ *
14130
+ * @param strategyName - Strategy identifier
14131
+ * @param exchangeName - Exchange identifier
14132
+ * @param frameName - Frame identifier
14133
+ * @param initial - Whether this is the first initialization
14134
+ */
14135
+ waitForInit: (strategyName: string, exchangeName: string, frameName: string, initial: boolean) => Promise<void>;
14136
+ /**
14137
+ * Reads a session entry from persistence storage.
14138
+ *
14139
+ * @param strategyName - Strategy identifier
14140
+ * @param exchangeName - Exchange identifier
14141
+ * @param frameName - Frame identifier
14142
+ * @returns Promise resolving to entry data or null if not found
14143
+ */
14144
+ readSessionData: (strategyName: string, exchangeName: string, frameName: string) => Promise<SessionData | null>;
14145
+ /**
14146
+ * Writes a session entry to disk with atomic file writes.
14147
+ *
14148
+ * @param data - Entry data to persist
14149
+ * @param strategyName - Strategy identifier
14150
+ * @param exchangeName - Exchange identifier
14151
+ * @param frameName - Frame identifier
14152
+ */
14153
+ writeSessionData: (data: SessionData, strategyName: string, exchangeName: string, frameName: string) => Promise<void>;
14154
+ /**
14155
+ * Switches to a dummy persist adapter that discards all writes.
14156
+ * All future persistence writes will be no-ops.
14157
+ */
14158
+ useDummy: () => void;
14159
+ /**
14160
+ * Switches to the default JSON persist adapter.
14161
+ * All future persistence writes will use JSON storage.
14162
+ */
14163
+ useJson: () => void;
14164
+ /**
14165
+ * Clears the memoized storage cache.
14166
+ * Call this when process.cwd() changes between strategy iterations
14167
+ * so new storage instances are created with the updated base path.
14168
+ */
14169
+ clear: () => void;
14170
+ /**
14171
+ * Disposes of the session adapter and releases any resources.
14172
+ * Call this when a session is removed to clean up its associated storage.
14173
+ *
14174
+ * @param strategyName - Strategy identifier
14175
+ * @param exchangeName - Exchange identifier
14176
+ * @param frameName - Frame identifier
14177
+ */
14178
+ dispose: (strategyName: string, exchangeName: string, frameName: string) => void;
14179
+ }
14180
+ /**
14181
+ * Global singleton instance of PersistSessionUtils.
14182
+ * Used by SessionPersistInstance for crash-safe session persistence.
14183
+ */
14184
+ declare const PersistSessionAdapter: PersistSessionUtils;
13553
14185
 
13554
14186
  /**
13555
14187
  * Configuration interface for selective markdown service enablement.
@@ -14364,48 +14996,278 @@ declare class LogAdapter implements ILog {
14364
14996
  */
14365
14997
  useMemory: () => void;
14366
14998
  /**
14367
- * Switches to dummy log adapter.
14368
- * All future log writes will be no-ops.
14999
+ * Switches to dummy log adapter.
15000
+ * All future log writes will be no-ops.
15001
+ */
15002
+ useDummy: () => void;
15003
+ /**
15004
+ * Switches to JSONL file log adapter.
15005
+ * Log entries will be appended to {dirName}/{fileName}.jsonl.
15006
+ * Reads are performed by parsing all lines from the file.
15007
+ *
15008
+ * @param fileName - Base file name without extension (default: "log")
15009
+ * @param dirName - Directory for the JSONL file (default: ./dump/log)
15010
+ */
15011
+ useJsonl: (fileName?: string, dirName?: string) => void;
15012
+ /**
15013
+ * Clears the cached log instance by resetting to the default in-memory adapter.
15014
+ * Call this when process.cwd() changes between strategy iterations
15015
+ * so a new adapter instance is created with the updated base path.
15016
+ */
15017
+ clear: () => void;
15018
+ }
15019
+ /**
15020
+ * Global singleton instance of LogAdapter.
15021
+ * Provides unified log management with pluggable backends.
15022
+ */
15023
+ declare const Log: LogAdapter;
15024
+
15025
+ /** Callable that restores a previously saved subject snapshot */
15026
+ type RestoreSnapshot = () => void;
15027
+ /**
15028
+ * Manages isolation of global event-bus state between backtest sessions.
15029
+ * Allows temporarily detaching all subject subscriptions so that one session
15030
+ * does not interfere with another, then restoring them afterwards.
15031
+ */
15032
+ declare class SystemUtils {
15033
+ /**
15034
+ * Snapshots the current listener state of every global subject by replacing
15035
+ * their internal `_events` map with an empty object.
15036
+ * @returns A restore function that, when called, puts all original listeners back.
15037
+ */
15038
+ createSnapshot: () => RestoreSnapshot;
15039
+ }
15040
+ declare const System: SystemUtils;
15041
+
15042
+ /**
15043
+ * Interface for session instance implementations.
15044
+ * Defines the contract for local, persist, and dummy backends.
15045
+ *
15046
+ * Intended use: per-(symbol, strategy, exchange, frame) mutable session data
15047
+ * shared across strategy callbacks within a single run — e.g. caching LLM
15048
+ * inference results, intermediate indicator state, or cross-candle accumulators.
15049
+ *
15050
+ * Example shape:
15051
+ * ```ts
15052
+ * { lastLlmSignal: "buy" | "sell" | null; confirmedAt: number }
15053
+ * ```
15054
+ */
15055
+ interface ISessionInstance {
15056
+ /**
15057
+ * Initialize the session instance.
15058
+ * @param initial - Whether this is the first initialization
15059
+ */
15060
+ waitForInit(initial: boolean): Promise<void>;
15061
+ /**
15062
+ * Write a new session value.
15063
+ * @param value - New value or null to clear
15064
+ */
15065
+ setData<Value extends object = object>(value: Value | null): Promise<void>;
15066
+ /**
15067
+ * Read the current session value.
15068
+ * @returns Current session value, or null if not set
15069
+ */
15070
+ getData<Value extends object = object>(): Promise<Value | null>;
15071
+ /**
15072
+ * Releases any resources held by this instance.
15073
+ */
15074
+ dispose(): Promise<void>;
15075
+ }
15076
+ /**
15077
+ * Constructor type for session instance implementations.
15078
+ * Used for swapping backends via SessionBacktestAdapter / SessionLiveAdapter.
15079
+ */
15080
+ type TSessionInstanceCtor = new (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean) => ISessionInstance;
15081
+ /**
15082
+ * Public surface of SessionBacktestAdapter / SessionLiveAdapter — ISessionInstance minus waitForInit and dispose.
15083
+ * waitForInit and dispose are managed internally by the adapter.
15084
+ */
15085
+ type TSessionAdapter = {
15086
+ [key in Exclude<keyof ISessionInstance, "waitForInit" | "dispose">]: any;
15087
+ };
15088
+ /**
15089
+ * Backtest session adapter with pluggable storage backend.
15090
+ *
15091
+ * Features:
15092
+ * - Adapter pattern for swappable session instance implementations
15093
+ * - Default backend: SessionLocalInstance (in-memory, no disk persistence)
15094
+ * - Alternative backends: SessionPersistInstance, SessionDummyInstance
15095
+ * - Convenience methods: useLocal(), usePersist(), useDummy(), useSessionAdapter()
15096
+ * - Memoized instances per (symbol, strategyName, exchangeName, frameName) tuple
15097
+ */
15098
+ declare class SessionBacktestAdapter implements TSessionAdapter {
15099
+ private SessionFactory;
15100
+ private getInstance;
15101
+ /**
15102
+ * Read the current session value for a backtest run.
15103
+ * @param symbol - Trading pair symbol
15104
+ * @param context.strategyName - Strategy identifier
15105
+ * @param context.exchangeName - Exchange identifier
15106
+ * @param context.frameName - Frame identifier
15107
+ * @returns Current session value, or null if not set
15108
+ */
15109
+ getData: <Value extends object = object>(symbol: string, context: {
15110
+ strategyName: StrategyName;
15111
+ exchangeName: ExchangeName;
15112
+ frameName: FrameName;
15113
+ }) => Promise<Value | null>;
15114
+ /**
15115
+ * Update the session value for a backtest run.
15116
+ * @param symbol - Trading pair symbol
15117
+ * @param value - New value or null to clear
15118
+ * @param context.strategyName - Strategy identifier
15119
+ * @param context.exchangeName - Exchange identifier
15120
+ * @param context.frameName - Frame identifier
15121
+ */
15122
+ setData: <Value extends object = object>(symbol: string, value: Value | null, context: {
15123
+ strategyName: StrategyName;
15124
+ exchangeName: ExchangeName;
15125
+ frameName: FrameName;
15126
+ }) => Promise<void>;
15127
+ /**
15128
+ * Switches to in-memory adapter (default).
15129
+ * All data lives in process memory only.
15130
+ */
15131
+ useLocal: () => void;
15132
+ /**
15133
+ * Switches to file-system backed adapter.
15134
+ * Data is persisted to disk via PersistSessionAdapter.
15135
+ */
15136
+ usePersist: () => void;
15137
+ /**
15138
+ * Switches to dummy adapter that discards all writes.
15139
+ */
15140
+ useDummy: () => void;
15141
+ /**
15142
+ * Switches to a custom session adapter implementation.
15143
+ * @param Ctor - Constructor for the custom session instance
15144
+ */
15145
+ useSessionAdapter: (Ctor: TSessionInstanceCtor) => void;
15146
+ /**
15147
+ * Clears the memoized instance cache.
15148
+ * Call this when process.cwd() changes between strategy iterations
15149
+ * so new instances are created with the updated base path.
15150
+ */
15151
+ clear: () => void;
15152
+ }
15153
+ /**
15154
+ * Live trading session adapter with pluggable storage backend.
15155
+ *
15156
+ * Features:
15157
+ * - Adapter pattern for swappable session instance implementations
15158
+ * - Default backend: SessionPersistInstance (file-system backed, survives restarts)
15159
+ * - Alternative backends: SessionLocalInstance, SessionDummyInstance
15160
+ * - Convenience methods: useLocal(), usePersist(), useDummy(), useSessionAdapter()
15161
+ * - Memoized instances per (symbol, strategyName, exchangeName, frameName) tuple
15162
+ */
15163
+ declare class SessionLiveAdapter implements TSessionAdapter {
15164
+ private SessionFactory;
15165
+ private getInstance;
15166
+ /**
15167
+ * Read the current session value for a live run.
15168
+ * @param symbol - Trading pair symbol
15169
+ * @param context.strategyName - Strategy identifier
15170
+ * @param context.exchangeName - Exchange identifier
15171
+ * @param context.frameName - Frame identifier
15172
+ * @returns Current session value, or null if not set
15173
+ */
15174
+ getData: <Value extends object = object>(symbol: string, context: {
15175
+ strategyName: StrategyName;
15176
+ exchangeName: ExchangeName;
15177
+ frameName: FrameName;
15178
+ }) => Promise<Value | null>;
15179
+ /**
15180
+ * Update the session value for a live run.
15181
+ * @param symbol - Trading pair symbol
15182
+ * @param value - New value or null to clear
15183
+ * @param context.strategyName - Strategy identifier
15184
+ * @param context.exchangeName - Exchange identifier
15185
+ * @param context.frameName - Frame identifier
15186
+ */
15187
+ setData: <Value extends object = object>(symbol: string, value: Value | null, context: {
15188
+ strategyName: StrategyName;
15189
+ exchangeName: ExchangeName;
15190
+ frameName: FrameName;
15191
+ }) => Promise<void>;
15192
+ /**
15193
+ * Switches to in-memory adapter.
15194
+ * All data lives in process memory only.
15195
+ */
15196
+ useLocal: () => void;
15197
+ /**
15198
+ * Switches to file-system backed adapter (default).
15199
+ * Data is persisted to disk via PersistSessionAdapter.
15200
+ */
15201
+ usePersist: () => void;
15202
+ /**
15203
+ * Switches to dummy adapter that discards all writes.
14369
15204
  */
14370
15205
  useDummy: () => void;
14371
15206
  /**
14372
- * Switches to JSONL file log adapter.
14373
- * Log entries will be appended to {dirName}/{fileName}.jsonl.
14374
- * Reads are performed by parsing all lines from the file.
14375
- *
14376
- * @param fileName - Base file name without extension (default: "log")
14377
- * @param dirName - Directory for the JSONL file (default: ./dump/log)
15207
+ * Switches to a custom session adapter implementation.
15208
+ * @param Ctor - Constructor for the custom session instance
14378
15209
  */
14379
- useJsonl: (fileName?: string, dirName?: string) => void;
15210
+ useSessionAdapter: (Ctor: TSessionInstanceCtor) => void;
14380
15211
  /**
14381
- * Clears the cached log instance by resetting to the default in-memory adapter.
15212
+ * Clears the memoized instance cache.
14382
15213
  * Call this when process.cwd() changes between strategy iterations
14383
- * so a new adapter instance is created with the updated base path.
15214
+ * so new instances are created with the updated base path.
14384
15215
  */
14385
15216
  clear: () => void;
14386
15217
  }
14387
15218
  /**
14388
- * Global singleton instance of LogAdapter.
14389
- * Provides unified log management with pluggable backends.
14390
- */
14391
- declare const Log: LogAdapter;
14392
-
14393
- /** Callable that restores a previously saved subject snapshot */
14394
- type RestoreSnapshot = () => void;
14395
- /**
14396
- * Manages isolation of global event-bus state between backtest sessions.
14397
- * Allows temporarily detaching all subject subscriptions so that one session
14398
- * does not interfere with another, then restoring them afterwards.
15219
+ * Main session adapter that manages both backtest and live session storage.
15220
+ *
15221
+ * Features:
15222
+ * - Routes all operations to SessionBacktest or SessionLive based on the backtest flag
14399
15223
  */
14400
- declare class SessionUtils {
15224
+ declare class SessionAdapter {
14401
15225
  /**
14402
- * Snapshots the current listener state of every global subject by replacing
14403
- * their internal `_events` map with an empty object.
14404
- * @returns A restore function that, when called, puts all original listeners back.
15226
+ * Read the current session value for a signal.
15227
+ * Routes to SessionBacktest or SessionLive based on backtest.
15228
+ * @param symbol - Trading pair symbol
15229
+ * @param context.strategyName - Strategy identifier
15230
+ * @param context.exchangeName - Exchange identifier
15231
+ * @param context.frameName - Frame identifier
15232
+ * @param backtest - Flag indicating if the context is backtest or live
15233
+ * @returns Current session value, or null if not set
14405
15234
  */
14406
- createSnapshot: () => RestoreSnapshot;
15235
+ getData: <Value extends object = object>(symbol: string, context: {
15236
+ strategyName: StrategyName;
15237
+ exchangeName: ExchangeName;
15238
+ frameName: FrameName;
15239
+ }, backtest: boolean) => Promise<Value | null>;
15240
+ /**
15241
+ * Update the session value for a signal.
15242
+ * Routes to SessionBacktest or SessionLive based on backtest.
15243
+ * @param symbol - Trading pair symbol
15244
+ * @param value - New value or null to clear
15245
+ * @param context.strategyName - Strategy identifier
15246
+ * @param context.exchangeName - Exchange identifier
15247
+ * @param context.frameName - Frame identifier
15248
+ * @param backtest - Flag indicating if the context is backtest or live
15249
+ */
15250
+ setData: <Value extends object = object>(symbol: string, value: Value | null, context: {
15251
+ strategyName: StrategyName;
15252
+ exchangeName: ExchangeName;
15253
+ frameName: FrameName;
15254
+ }, backtest: boolean) => Promise<void>;
14407
15255
  }
14408
- declare const Session: SessionUtils;
15256
+ /**
15257
+ * Global singleton instance of SessionAdapter.
15258
+ * Provides unified session management for backtest and live trading.
15259
+ */
15260
+ declare const Session: SessionAdapter;
15261
+ /**
15262
+ * Global singleton instance of SessionLiveAdapter.
15263
+ * Provides live trading session storage with pluggable backends.
15264
+ */
15265
+ declare const SessionLive: SessionLiveAdapter;
15266
+ /**
15267
+ * Global singleton instance of SessionBacktestAdapter.
15268
+ * Provides backtest session storage with pluggable backends.
15269
+ */
15270
+ declare const SessionBacktest: SessionBacktestAdapter;
14409
15271
 
14410
15272
  /**
14411
15273
  * Type alias for column configuration used in backtest markdown reports.
@@ -22010,50 +22872,47 @@ interface IMemoryInstance {
22010
22872
  }
22011
22873
  /**
22012
22874
  * Constructor type for memory instance implementations.
22013
- * Used for swapping backends via MemoryAdapter.
22875
+ * Used for swapping backends via MemoryBacktestAdapter / MemoryLiveAdapter.
22014
22876
  */
22015
22877
  type TMemoryInstanceCtor = new (signalId: string, bucketName: string) => IMemoryInstance;
22016
22878
  /**
22017
- * Public surface of MemoryAdapter - IMemoryInstance minus waitForInit.
22879
+ * Public surface of MemoryBacktestAdapter / MemoryLiveAdapter — IMemoryInstance minus waitForInit.
22018
22880
  * waitForInit is managed internally by the adapter.
22019
22881
  */
22020
22882
  type TMemoryInstance = Omit<{
22021
22883
  [key in keyof IMemoryInstance]: any;
22022
22884
  }, keyof {
22023
22885
  waitForInit: never;
22886
+ dispose: never;
22024
22887
  }>;
22025
22888
  /**
22026
- * Facade for memory instances scoped per (signalId, bucketName).
22027
- * Manages lazy initialization and instance lifecycle.
22889
+ * Backtest memory adapter with pluggable storage backend.
22028
22890
  *
22029
22891
  * Features:
22030
- * - Memoized instances per (signalId, bucketName) pair
22031
- * - Swappable backend via useLocal(), usePersist(), useDummy()
22032
- * - Default backend: MemoryPersistInstance (in-memory BM25 + persist storage)
22892
+ * - Adapter pattern for swappable memory instance implementations
22893
+ * - Default backend: MemoryLocalInstance (in-memory BM25, no disk persistence)
22894
+ * - Alternative backends: MemoryPersistInstance, MemoryDummyInstance
22895
+ * - Convenience methods: useLocal(), usePersist(), useDummy(), useMemoryAdapter()
22896
+ * - Memoized instances per (signalId, bucketName) pair; cleared via disposeSignal() from MemoryAdapter
22897
+ *
22898
+ * Use this adapter for backtest memory storage.
22033
22899
  */
22034
- declare class MemoryAdapter implements TMemoryInstance {
22900
+ declare class MemoryBacktestAdapter implements TMemoryInstance {
22035
22901
  private MemoryFactory;
22036
22902
  private getInstance;
22037
22903
  /**
22038
- * Activates the adapter by subscribing to signal lifecycle events.
22039
- * Clears memoized instances for a signalId when it is cancelled or closed,
22040
- * preventing stale instances from accumulating in memory.
22041
- * Idempotent — subsequent calls return the same subscription handle.
22042
- * Must be called before any memory method is used.
22043
- */
22044
- enable: (() => (...args: any[]) => any) & functools_kit.ISingleshotClearable<() => (...args: any[]) => any>;
22045
- /**
22046
- * Deactivates the adapter by unsubscribing from signal lifecycle events.
22047
- * No-op if enable() was never called.
22904
+ * Disposes all memoized instances for the given signalId.
22905
+ * Called by MemoryAdapter when a signal is cancelled or closed.
22906
+ * @param signalId - Signal identifier to dispose
22048
22907
  */
22049
- disable: () => void;
22908
+ disposeSignal: (signalId: string) => void;
22050
22909
  /**
22051
22910
  * Write a value to memory.
22052
22911
  * @param dto.memoryId - Unique entry identifier
22053
22912
  * @param dto.value - Value to store
22054
22913
  * @param dto.signalId - Signal identifier
22055
22914
  * @param dto.bucketName - Bucket name
22056
- * @param dto.description - Optional BM25 index string; defaults to JSON.stringify(value)
22915
+ * @param dto.description - BM25 index string; defaults to JSON.stringify(value)
22057
22916
  */
22058
22917
  writeMemory: <T extends object = object>(dto: {
22059
22918
  memoryId: string;
@@ -22130,23 +22989,262 @@ declare class MemoryAdapter implements TMemoryInstance {
22130
22989
  * Switches to dummy adapter that discards all writes.
22131
22990
  */
22132
22991
  useDummy: () => void;
22992
+ /**
22993
+ * Switches to a custom memory adapter implementation.
22994
+ * @param Ctor - Constructor for the custom memory instance
22995
+ */
22996
+ useMemoryAdapter: (Ctor: TMemoryInstanceCtor) => void;
22997
+ /**
22998
+ * Clears the memoized instance cache.
22999
+ * Call this when process.cwd() changes between strategy iterations
23000
+ * so new instances are created with the updated base path.
23001
+ */
23002
+ clear: () => void;
23003
+ }
23004
+ /**
23005
+ * Live trading memory adapter with pluggable storage backend.
23006
+ *
23007
+ * Features:
23008
+ * - Adapter pattern for swappable memory instance implementations
23009
+ * - Default backend: MemoryPersistInstance (file-system backed, survives restarts)
23010
+ * - Alternative backends: MemoryLocalInstance, MemoryDummyInstance
23011
+ * - Convenience methods: useLocal(), usePersist(), useDummy(), useMemoryAdapter()
23012
+ * - Memoized instances per (signalId, bucketName) pair; cleared via disposeSignal() from MemoryAdapter
23013
+ *
23014
+ * Use this adapter for live trading memory storage.
23015
+ */
23016
+ declare class MemoryLiveAdapter implements TMemoryInstance {
23017
+ private MemoryFactory;
23018
+ private getInstance;
23019
+ /**
23020
+ * Disposes all memoized instances for the given signalId.
23021
+ * Called by MemoryAdapter when a signal is cancelled or closed.
23022
+ * @param signalId - Signal identifier to dispose
23023
+ */
23024
+ disposeSignal: (signalId: string) => void;
23025
+ /**
23026
+ * Write a value to memory.
23027
+ * @param dto.memoryId - Unique entry identifier
23028
+ * @param dto.value - Value to store
23029
+ * @param dto.signalId - Signal identifier
23030
+ * @param dto.bucketName - Bucket name
23031
+ * @param dto.description - BM25 index string; defaults to JSON.stringify(value)
23032
+ */
23033
+ writeMemory: <T extends object = object>(dto: {
23034
+ memoryId: string;
23035
+ value: T;
23036
+ signalId: string;
23037
+ bucketName: string;
23038
+ description: string;
23039
+ }) => Promise<void>;
23040
+ /**
23041
+ * Search memory using BM25 full-text scoring.
23042
+ * @param dto.query - Search query string
23043
+ * @param dto.signalId - Signal identifier
23044
+ * @param dto.bucketName - Bucket name
23045
+ * @returns Matching entries sorted by relevance score
23046
+ */
23047
+ searchMemory: <T extends object = object>(dto: {
23048
+ query: string;
23049
+ signalId: string;
23050
+ bucketName: string;
23051
+ settings?: SearchSettings;
23052
+ }) => Promise<{
23053
+ memoryId: string;
23054
+ score: number;
23055
+ content: T;
23056
+ }[]>;
23057
+ /**
23058
+ * List all entries in memory.
23059
+ * @param dto.signalId - Signal identifier
23060
+ * @param dto.bucketName - Bucket name
23061
+ * @returns Array of all stored entries
23062
+ */
23063
+ listMemory: <T extends object = object>(dto: {
23064
+ signalId: string;
23065
+ bucketName: string;
23066
+ }) => Promise<{
23067
+ memoryId: string;
23068
+ content: T;
23069
+ }[]>;
23070
+ /**
23071
+ * Remove an entry from memory.
23072
+ * @param dto.memoryId - Unique entry identifier
23073
+ * @param dto.signalId - Signal identifier
23074
+ * @param dto.bucketName - Bucket name
23075
+ */
23076
+ removeMemory: (dto: {
23077
+ memoryId: string;
23078
+ signalId: string;
23079
+ bucketName: string;
23080
+ }) => Promise<void>;
23081
+ /**
23082
+ * Read a single entry from memory.
23083
+ * @param dto.memoryId - Unique entry identifier
23084
+ * @param dto.signalId - Signal identifier
23085
+ * @param dto.bucketName - Bucket name
23086
+ * @returns Entry value
23087
+ * @throws Error if entry not found
23088
+ */
23089
+ readMemory: <T extends object = object>(dto: {
23090
+ memoryId: string;
23091
+ signalId: string;
23092
+ bucketName: string;
23093
+ }) => Promise<T>;
23094
+ /**
23095
+ * Switches to in-memory BM25 adapter.
23096
+ * All data lives in process memory only.
23097
+ */
23098
+ useLocal: () => void;
23099
+ /**
23100
+ * Switches to file-system backed adapter (default).
23101
+ * Data is persisted to ./dump/memory/<signalId>/<bucketName>/.
23102
+ */
23103
+ usePersist: () => void;
23104
+ /**
23105
+ * Switches to dummy adapter that discards all writes.
23106
+ */
23107
+ useDummy: () => void;
23108
+ /**
23109
+ * Switches to a custom memory adapter implementation.
23110
+ * @param Ctor - Constructor for the custom memory instance
23111
+ */
23112
+ useMemoryAdapter: (Ctor: TMemoryInstanceCtor) => void;
22133
23113
  /**
22134
23114
  * Clears the memoized instance cache.
22135
23115
  * Call this when process.cwd() changes between strategy iterations
22136
23116
  * so new instances are created with the updated base path.
22137
23117
  */
22138
23118
  clear: () => void;
23119
+ }
23120
+ /**
23121
+ * Main memory adapter that manages both backtest and live memory storage.
23122
+ *
23123
+ * Features:
23124
+ * - Subscribes to signal lifecycle events (cancelled/closed) to dispose stale instances
23125
+ * - Routes all operations to MemoryBacktest or MemoryLive based on dto.backtest
23126
+ * - Singleshot enable pattern prevents duplicate subscriptions
23127
+ * - Cleanup function for proper unsubscription
23128
+ */
23129
+ declare class MemoryAdapter {
23130
+ /**
23131
+ * Enables memory storage by subscribing to signal lifecycle events.
23132
+ * Clears memoized instances in MemoryBacktest and MemoryLive when a signal
23133
+ * is cancelled or closed, preventing stale instances from accumulating.
23134
+ * Uses singleshot to ensure one-time subscription.
23135
+ *
23136
+ * @returns Cleanup function that unsubscribes from all emitters
23137
+ */
23138
+ enable: (() => (...args: any[]) => any) & functools_kit.ISingleshotClearable<() => (...args: any[]) => any>;
23139
+ /**
23140
+ * Disables memory storage by unsubscribing from signal lifecycle events.
23141
+ * Safe to call multiple times.
23142
+ */
23143
+ disable: () => void;
23144
+ /**
23145
+ * Write a value to memory.
23146
+ * Routes to MemoryBacktest or MemoryLive based on dto.backtest.
23147
+ * @param dto.memoryId - Unique entry identifier
23148
+ * @param dto.value - Value to store
23149
+ * @param dto.signalId - Signal identifier
23150
+ * @param dto.bucketName - Bucket name
23151
+ * @param dto.description - BM25 index string; defaults to JSON.stringify(value)
23152
+ * @param dto.backtest - Flag indicating if the context is backtest or live
23153
+ */
23154
+ writeMemory: <T extends object = object>(dto: {
23155
+ memoryId: string;
23156
+ value: T;
23157
+ signalId: string;
23158
+ bucketName: string;
23159
+ description: string;
23160
+ backtest: boolean;
23161
+ }) => Promise<void>;
23162
+ /**
23163
+ * Search memory using BM25 full-text scoring.
23164
+ * Routes to MemoryBacktest or MemoryLive based on dto.backtest.
23165
+ * @param dto.query - Search query string
23166
+ * @param dto.signalId - Signal identifier
23167
+ * @param dto.bucketName - Bucket name
23168
+ * @param dto.backtest - Flag indicating if the context is backtest or live
23169
+ * @returns Matching entries sorted by relevance score
23170
+ */
23171
+ searchMemory: <T extends object = object>(dto: {
23172
+ query: string;
23173
+ signalId: string;
23174
+ bucketName: string;
23175
+ settings?: SearchSettings;
23176
+ backtest: boolean;
23177
+ }) => Promise<{
23178
+ memoryId: string;
23179
+ score: number;
23180
+ content: T;
23181
+ }[]>;
23182
+ /**
23183
+ * List all entries in memory.
23184
+ * Routes to MemoryBacktest or MemoryLive based on dto.backtest.
23185
+ * @param dto.signalId - Signal identifier
23186
+ * @param dto.bucketName - Bucket name
23187
+ * @param dto.backtest - Flag indicating if the context is backtest or live
23188
+ * @returns Array of all stored entries
23189
+ */
23190
+ listMemory: <T extends object = object>(dto: {
23191
+ signalId: string;
23192
+ bucketName: string;
23193
+ backtest: boolean;
23194
+ }) => Promise<{
23195
+ memoryId: string;
23196
+ content: T;
23197
+ }[]>;
23198
+ /**
23199
+ * Remove an entry from memory.
23200
+ * Routes to MemoryBacktest or MemoryLive based on dto.backtest.
23201
+ * @param dto.memoryId - Unique entry identifier
23202
+ * @param dto.signalId - Signal identifier
23203
+ * @param dto.bucketName - Bucket name
23204
+ * @param dto.backtest - Flag indicating if the context is backtest or live
23205
+ */
23206
+ removeMemory: (dto: {
23207
+ memoryId: string;
23208
+ signalId: string;
23209
+ bucketName: string;
23210
+ backtest: boolean;
23211
+ }) => Promise<void>;
22139
23212
  /**
22140
- * Releases resources held by this adapter.
22141
- * Delegates to disable() to unsubscribe from signal lifecycle events.
23213
+ * Read a single entry from memory.
23214
+ * Routes to MemoryBacktest or MemoryLive based on dto.backtest.
23215
+ * @param dto.memoryId - Unique entry identifier
23216
+ * @param dto.signalId - Signal identifier
23217
+ * @param dto.bucketName - Bucket name
23218
+ * @param dto.backtest - Flag indicating if the context is backtest or live
23219
+ * @returns Entry value
23220
+ * @throws Error if entry not found
22142
23221
  */
22143
- dispose: () => void;
23222
+ readMemory: <T extends object = object>(dto: {
23223
+ memoryId: string;
23224
+ signalId: string;
23225
+ bucketName: string;
23226
+ backtest: boolean;
23227
+ }) => Promise<T>;
22144
23228
  }
23229
+ /**
23230
+ * Global singleton instance of MemoryAdapter.
23231
+ * Provides unified memory management for backtest and live trading.
23232
+ */
22145
23233
  declare const Memory: MemoryAdapter;
23234
+ /**
23235
+ * Global singleton instance of MemoryLiveAdapter.
23236
+ * Provides live trading memory storage with pluggable backends.
23237
+ */
23238
+ declare const MemoryLive: MemoryLiveAdapter;
23239
+ /**
23240
+ * Global singleton instance of MemoryBacktestAdapter.
23241
+ * Provides backtest memory storage with pluggable backends.
23242
+ */
23243
+ declare const MemoryBacktest: MemoryBacktestAdapter;
22146
23244
 
22147
23245
  /**
22148
23246
  * Context required to identify a dump entry.
22149
- * Passed only through DumpAdapter - instances receive signalId and bucketName via constructor.
23247
+ * Passed only through DumpAdapter - instances receive signalId, bucketName, and backtest via constructor.
22150
23248
  */
22151
23249
  interface IDumpContext {
22152
23250
  /** Signal identifier - scopes the dump to a specific trade */
@@ -22157,6 +23255,8 @@ interface IDumpContext {
22157
23255
  dumpId: string;
22158
23256
  /** Human-readable label describing the dump contents; included in the BM25 index for Memory search and rendered in Markdown output */
22159
23257
  description: string;
23258
+ /** Flag indicating if the context is backtest or live; routed to Memory.writeMemory */
23259
+ backtest: boolean;
22160
23260
  }
22161
23261
  /**
22162
23262
  * Interface for dump instance implementations.
@@ -22217,7 +23317,7 @@ interface IDumpInstance {
22217
23317
  * Constructor type for dump instance implementations.
22218
23318
  * Used for swapping backends via DumpAdapter.useDumpAdapter().
22219
23319
  */
22220
- type TDumpInstanceCtor = new (signalId: string, bucketName: string) => IDumpInstance;
23320
+ type TDumpInstanceCtor = new (signalId: string, bucketName: string, backtest: boolean) => IDumpInstance;
22221
23321
  /**
22222
23322
  * Facade for dump instances with swappable backend.
22223
23323
  * Default backend: DumpMarkdownInstance.
@@ -32944,4 +34044,4 @@ declare const getTotalClosed: (signal: Signal) => {
32944
34044
  remainingCostBasis: number;
32945
34045
  };
32946
34046
 
32947
- export { ActionBase, type ActivateScheduledCommit, type ActivateScheduledCommitNotification, type ActivePingContract, type AverageBuyCommit, type AverageBuyCommitNotification, Backtest, type BacktestStatisticsModel, Breakeven, type BreakevenAvailableNotification, type BreakevenCommit, type BreakevenCommitNotification, type BreakevenContract, type BreakevenData, type BreakevenEvent, type BreakevenStatisticsModel, Broker, type BrokerAverageBuyPayload, BrokerBase, type BrokerBreakevenPayload, type BrokerPartialLossPayload, type BrokerPartialProfitPayload, type BrokerSignalClosePayload, type BrokerSignalOpenPayload, type BrokerTrailingStopPayload, type BrokerTrailingTakePayload, Cache, type CancelScheduledCommit, type CancelScheduledCommitNotification, type CandleData, type CandleInterval, type ClosePendingCommit, type ClosePendingCommitNotification, type ColumnConfig, type ColumnModel, type CommitPayload, Constant, type CriticalErrorNotification, type DoneContract, Dump, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, HighestProfit, type HighestProfitContract, type HighestProfitEvent, type HighestProfitStatisticsModel, type IActionSchema, type IActivateScheduledCommitRow, type IAggregatedTradeData, type IBidData, type IBreakevenCommitRow, type IBroker, type ICandleData, type ICommitRow, type IDumpContext, type IDumpInstance, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type ILog, type ILogEntry, type ILogger, type IMarkdownDumpOptions, type IMemoryInstance, type INotificationUtils, type IOrderBookData, type IPartialLossCommitRow, type IPartialProfitCommitRow, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IPublicAction, type IPublicCandleData, type IPublicSignalRow, type IRecentUtils, type IReportDumpOptions, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskSignalRow, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalCancelRow, type IScheduledSignalRow, type ISignalDto, type ISignalIntervalDto, 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 IdlePingContract, type InfoErrorNotification, Interval, type IntervalData, Live, type LiveStatisticsModel, Log, type LogData, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, MarkdownWriter, MaxDrawdown, type MaxDrawdownContract, type MaxDrawdownEvent, type MaxDrawdownStatisticsModel, type MeasureData, Memory, type MemoryData, type MessageModel, type MessageRole, type MessageToolCall, 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, PersistIntervalAdapter, PersistLogAdapter, PersistMeasureAdapter, PersistMemoryAdapter, PersistNotificationAdapter, PersistPartialAdapter, PersistRecentAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PersistStorageAdapter, Position, PositionSize, type ProgressBacktestContract, type ProgressWalkerContract, Recent, RecentBacktest, type RecentData, RecentLive, Reflect, Report, ReportBase, type ReportName, ReportWriter, Risk, type RiskContract, type RiskData, type RiskEvent, type RiskRejectionNotification, type RiskStatisticsModel, Schedule, type ScheduleData, type SchedulePingContract, type ScheduleStatisticsModel, type ScheduledEvent, Session, type SignalCancelledNotification, type SignalCloseContract, type SignalClosedNotification, type SignalData, type SignalInfoContract, type SignalInfoNotification, type SignalInterval, type SignalOpenContract, type SignalOpenedNotification, type SignalScheduledNotification, type SignalSyncCloseNotification, type SignalSyncContract, type SignalSyncOpenNotification, Storage, StorageBacktest, type StorageData, StorageLive, Strategy, type StrategyActionType, type StrategyCancelReason, type StrategyCloseReason, type StrategyCommitContract, type StrategyEvent, type StrategyStatisticsModel, Sync, type SyncEvent, type SyncStatisticsModel, type TBrokerCtor, type TDumpInstanceCtor, type TLogCtor, type TMarkdownBase, type TMemoryInstanceCtor, type TNotificationUtilsCtor, type TPersistBase, type TPersistBaseCtor, type TRecentUtilsCtor, 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, commitPartialLossCost, commitPartialProfit, commitPartialProfitCost, commitSignalNotify, commitTrailingStop, commitTrailingStopCost, commitTrailingTake, commitTrailingTakeCost, dumpAgentAnswer, dumpError, dumpJson, dumpRecord, dumpTable, dumpText, emitters, formatPrice, formatQuantity, get, getActionSchema, getAggregatedTrades, getAveragePrice, getBacktestTimeframe, getBreakeven, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getEffectivePriceOpen, getExchangeSchema, getFrameSchema, getLatestSignal, getMaxDrawdownDistancePnlCost, getMaxDrawdownDistancePnlPercentage, getMinutesSinceLatestSignalCreated, getMode, getNextCandles, getOrderBook, getPendingSignal, getPositionActiveMinutes, getPositionCountdownMinutes, getPositionDrawdownMinutes, getPositionEffectivePrice, getPositionEntries, getPositionEntryOverlap, getPositionEstimateMinutes, getPositionHighestMaxDrawdownPnlCost, getPositionHighestMaxDrawdownPnlPercentage, getPositionHighestPnlCost, getPositionHighestPnlPercentage, getPositionHighestProfitBreakeven, getPositionHighestProfitDistancePnlCost, getPositionHighestProfitDistancePnlPercentage, getPositionHighestProfitMinutes, getPositionHighestProfitPrice, getPositionHighestProfitTimestamp, getPositionInvestedCost, getPositionInvestedCount, getPositionLevels, getPositionMaxDrawdownMinutes, getPositionMaxDrawdownPnlCost, getPositionMaxDrawdownPnlPercentage, getPositionMaxDrawdownPrice, getPositionMaxDrawdownTimestamp, getPositionPartialOverlap, getPositionPartials, getPositionPnlCost, getPositionPnlPercent, getPositionWaitingMinutes, getRawCandles, getRiskSchema, getScheduledSignal, getSizingSchema, getStrategySchema, getSymbol, getTimestamp, getTotalClosed, getTotalCostClosed, getTotalPercentClosed, getWalkerSchema, hasNoPendingSignal, hasNoScheduledSignal, hasTradeContext, investedCostToPercent, backtest as lib, listExchangeSchema, listFrameSchema, listMemory, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenHighestProfit, listenHighestProfitOnce, listenIdlePing, listenIdlePingOnce, listenMaxDrawdown, listenMaxDrawdownOnce, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalNotify, listenSignalNotifyOnce, listenSignalOnce, listenStrategyCommit, listenStrategyCommitOnce, listenSync, listenSyncOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, percentDiff, percentToCloseCost, percentValue, readMemory, removeMemory, roundTicks, runInMockContext, searchMemory, set, setColumns, setConfig, setLogger, shutdown, slPercentShiftToPrice, slPriceToPercentShift, stopStrategy, toProfitLossDto, tpPercentShiftToPrice, tpPriceToPercentShift, validate, validateCommonSignal, validatePendingSignal, validateScheduledSignal, validateSignal, waitForCandle, warmCandles, writeMemory };
34047
+ export { ActionBase, type ActivateScheduledCommit, type ActivateScheduledCommitNotification, type ActivePingContract, type AverageBuyCommit, type AverageBuyCommitNotification, Backtest, type BacktestStatisticsModel, Breakeven, type BreakevenAvailableNotification, type BreakevenCommit, type BreakevenCommitNotification, type BreakevenContract, type BreakevenData, type BreakevenEvent, type BreakevenStatisticsModel, Broker, type BrokerAverageBuyPayload, BrokerBase, type BrokerBreakevenPayload, type BrokerPartialLossPayload, type BrokerPartialProfitPayload, type BrokerSignalClosePayload, type BrokerSignalOpenPayload, type BrokerTrailingStopPayload, type BrokerTrailingTakePayload, Cache, type CancelScheduledCommit, type CancelScheduledCommitNotification, type CandleData, type CandleInterval, type ClosePendingCommit, type ClosePendingCommitNotification, type ColumnConfig, type ColumnModel, type CommitPayload, Constant, type CriticalErrorNotification, type DoneContract, Dump, type EntityId, Exchange, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type HeatmapStatisticsModel, HighestProfit, type HighestProfitContract, type HighestProfitEvent, type HighestProfitStatisticsModel, type IActionSchema, type IActivateScheduledCommitRow, type IAggregatedTradeData, type IBidData, type IBreakevenCommitRow, type IBroker, type ICandleData, type ICommitRow, type IDumpContext, type IDumpInstance, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type ILog, type ILogEntry, type ILogger, type IMarkdownDumpOptions, type IMemoryInstance, type INotificationUtils, type IOrderBookData, type IPartialLossCommitRow, type IPartialProfitCommitRow, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IPublicAction, type IPublicCandleData, type IPublicSignalRow, type IRecentUtils, type IReportDumpOptions, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskSignalRow, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalCancelRow, type IScheduledSignalRow, type ISessionInstance, type ISignalDto, type ISignalIntervalDto, 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 IStateInstance, 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 IdlePingContract, type InfoErrorNotification, Interval, type IntervalData, Live, type LiveStatisticsModel, Log, type LogData, Markdown, MarkdownFileBase, MarkdownFolderBase, type MarkdownName, MarkdownWriter, MaxDrawdown, type MaxDrawdownContract, type MaxDrawdownEvent, type MaxDrawdownStatisticsModel, type MeasureData, Memory, MemoryBacktest, MemoryBacktestAdapter, type MemoryData, MemoryLive, MemoryLiveAdapter, type MessageModel, type MessageRole, type MessageToolCall, 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, PersistIntervalAdapter, PersistLogAdapter, PersistMeasureAdapter, PersistMemoryAdapter, PersistNotificationAdapter, PersistPartialAdapter, PersistRecentAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSessionAdapter, PersistSignalAdapter, PersistStateAdapter, PersistStorageAdapter, Position, PositionSize, type ProgressBacktestContract, type ProgressWalkerContract, Recent, RecentBacktest, type RecentData, RecentLive, Reflect, Report, ReportBase, type ReportName, ReportWriter, Risk, type RiskContract, type RiskData, type RiskEvent, type RiskRejectionNotification, type RiskStatisticsModel, Schedule, type ScheduleData, type SchedulePingContract, type ScheduleStatisticsModel, type ScheduledEvent, Session, SessionBacktest, type SessionData, SessionLive, type SignalCancelledNotification, type SignalCloseContract, type SignalClosedNotification, type SignalData, type SignalInfoContract, type SignalInfoNotification, type SignalInterval, type SignalOpenContract, type SignalOpenedNotification, type SignalScheduledNotification, type SignalSyncCloseNotification, type SignalSyncContract, type SignalSyncOpenNotification, State, StateBacktest, StateBacktestAdapter, type StateData, StateLive, StateLiveAdapter, Storage, StorageBacktest, type StorageData, StorageLive, Strategy, type StrategyActionType, type StrategyCancelReason, type StrategyCloseReason, type StrategyCommitContract, type StrategyEvent, type StrategyStatisticsModel, Sync, type SyncEvent, type SyncStatisticsModel, System, type TBrokerCtor, type TDumpInstanceCtor, type TLogCtor, type TMarkdownBase, type TMemoryInstanceCtor, type TNotificationUtilsCtor, type TPersistBase, type TPersistBaseCtor, type TRecentUtilsCtor, type TReportBase, type TSessionInstanceCtor, type TStateInstanceCtor, 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, commitPartialLossCost, commitPartialProfit, commitPartialProfitCost, commitSignalNotify, commitTrailingStop, commitTrailingStopCost, commitTrailingTake, commitTrailingTakeCost, createSignalState, dumpAgentAnswer, dumpError, dumpJson, dumpRecord, dumpTable, dumpText, emitters, formatPrice, formatQuantity, get, getActionSchema, getAggregatedTrades, getAveragePrice, getBacktestTimeframe, getBreakeven, getCandles, getColumns, getConfig, getContext, getDate, getDefaultColumns, getDefaultConfig, getEffectivePriceOpen, getExchangeSchema, getFrameSchema, getLatestSignal, getMaxDrawdownDistancePnlCost, getMaxDrawdownDistancePnlPercentage, getMinutesSinceLatestSignalCreated, getMode, getNextCandles, getOrderBook, getPendingSignal, getPositionActiveMinutes, getPositionCountdownMinutes, getPositionDrawdownMinutes, getPositionEffectivePrice, getPositionEntries, getPositionEntryOverlap, getPositionEstimateMinutes, getPositionHighestMaxDrawdownPnlCost, getPositionHighestMaxDrawdownPnlPercentage, getPositionHighestPnlCost, getPositionHighestPnlPercentage, getPositionHighestProfitBreakeven, getPositionHighestProfitDistancePnlCost, getPositionHighestProfitDistancePnlPercentage, getPositionHighestProfitMinutes, getPositionHighestProfitPrice, getPositionHighestProfitTimestamp, getPositionInvestedCost, getPositionInvestedCount, getPositionLevels, getPositionMaxDrawdownMinutes, getPositionMaxDrawdownPnlCost, getPositionMaxDrawdownPnlPercentage, getPositionMaxDrawdownPrice, getPositionMaxDrawdownTimestamp, getPositionPartialOverlap, getPositionPartials, getPositionPnlCost, getPositionPnlPercent, getPositionWaitingMinutes, getRawCandles, getRiskSchema, getScheduledSignal, getSessionData, getSignalState, getSizingSchema, getStrategySchema, getSymbol, getTimestamp, getTotalClosed, getTotalCostClosed, getTotalPercentClosed, getWalkerSchema, hasNoPendingSignal, hasNoScheduledSignal, hasTradeContext, investedCostToPercent, backtest as lib, listExchangeSchema, listFrameSchema, listMemory, listRiskSchema, listSizingSchema, listStrategySchema, listWalkerSchema, listenActivePing, listenActivePingOnce, listenBacktestProgress, listenBreakevenAvailable, listenBreakevenAvailableOnce, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenHighestProfit, listenHighestProfitOnce, listenIdlePing, listenIdlePingOnce, listenMaxDrawdown, listenMaxDrawdownOnce, listenPartialLossAvailable, listenPartialLossAvailableOnce, listenPartialProfitAvailable, listenPartialProfitAvailableOnce, listenPerformance, listenRisk, listenRiskOnce, listenSchedulePing, listenSchedulePingOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalNotify, listenSignalNotifyOnce, listenSignalOnce, listenStrategyCommit, listenStrategyCommitOnce, listenSync, listenSyncOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, overrideActionSchema, overrideExchangeSchema, overrideFrameSchema, overrideRiskSchema, overrideSizingSchema, overrideStrategySchema, overrideWalkerSchema, parseArgs, percentDiff, percentToCloseCost, percentValue, readMemory, removeMemory, roundTicks, runInMockContext, searchMemory, set, setColumns, setConfig, setLogger, setSessionData, setSignalState, shutdown, slPercentShiftToPrice, slPriceToPercentShift, stopStrategy, toProfitLossDto, tpPercentShiftToPrice, tpPriceToPercentShift, validate, validateCommonSignal, validatePendingSignal, validateScheduledSignal, validateSignal, waitForCandle, warmCandles, writeMemory };