backtest-kit 1.3.2 → 1.4.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.
Files changed (5) hide show
  1. package/README.md +841 -6
  2. package/build/index.cjs +3349 -183
  3. package/build/index.mjs +3339 -184
  4. package/package.json +3 -2
  5. package/types.d.ts +2260 -122
package/types.d.ts CHANGED
@@ -570,6 +570,162 @@ interface IRisk {
570
570
  */
571
571
  type RiskName = string;
572
572
 
573
+ /**
574
+ * Profit or loss level milestone in percentage points.
575
+ * Represents 10%, 20%, 30%, ..., 100% profit or loss thresholds.
576
+ *
577
+ * Used to track when a signal reaches specific profit/loss milestones.
578
+ * Each level is emitted only once per signal (deduplication via Set).
579
+ *
580
+ * @example
581
+ * ```typescript
582
+ * const level: PartialLevel = 50; // 50% profit or loss milestone
583
+ * ```
584
+ */
585
+ type PartialLevel = 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100;
586
+ /**
587
+ * Serializable partial data for persistence layer.
588
+ * Converts Sets to arrays for JSON serialization.
589
+ *
590
+ * Stored in PersistPartialAdapter as Record<signalId, IPartialData>.
591
+ * Loaded on initialization and converted back to IPartialState.
592
+ */
593
+ interface IPartialData {
594
+ /**
595
+ * Array of profit levels that have been reached for this signal.
596
+ * Serialized form of IPartialState.profitLevels Set.
597
+ */
598
+ profitLevels: PartialLevel[];
599
+ /**
600
+ * Array of loss levels that have been reached for this signal.
601
+ * Serialized form of IPartialState.lossLevels Set.
602
+ */
603
+ lossLevels: PartialLevel[];
604
+ }
605
+ /**
606
+ * Partial profit/loss tracking interface.
607
+ * Implemented by ClientPartial and PartialConnectionService.
608
+ *
609
+ * Tracks profit/loss level milestones for active trading signals.
610
+ * Emits events when signals reach 10%, 20%, 30%, etc profit or loss.
611
+ *
612
+ * @example
613
+ * ```typescript
614
+ * import { ClientPartial } from "./client/ClientPartial";
615
+ *
616
+ * const partial = new ClientPartial({
617
+ * logger: loggerService,
618
+ * onProfit: (symbol, data, price, level, backtest, timestamp) => {
619
+ * console.log(`Signal ${data.id} reached ${level}% profit`);
620
+ * },
621
+ * onLoss: (symbol, data, price, level, backtest, timestamp) => {
622
+ * console.log(`Signal ${data.id} reached ${level}% loss`);
623
+ * }
624
+ * });
625
+ *
626
+ * await partial.waitForInit("BTCUSDT");
627
+ *
628
+ * // During signal monitoring
629
+ * await partial.profit("BTCUSDT", signal, 51000, 15.5, false, new Date());
630
+ * // Emits event when reaching 10% profit milestone
631
+ *
632
+ * // When signal closes
633
+ * await partial.clear("BTCUSDT", signal, 52000);
634
+ * ```
635
+ */
636
+ interface IPartial {
637
+ /**
638
+ * Processes profit state and emits events for new profit levels reached.
639
+ *
640
+ * Called by ClientStrategy during signal monitoring when revenuePercent > 0.
641
+ * Checks which profit levels (10%, 20%, 30%, etc) have been reached
642
+ * and emits events for new levels only (Set-based deduplication).
643
+ *
644
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
645
+ * @param data - Signal row data
646
+ * @param currentPrice - Current market price
647
+ * @param revenuePercent - Current profit percentage (positive value)
648
+ * @param backtest - True if backtest mode, false if live mode
649
+ * @param when - Event timestamp (current time for live, candle time for backtest)
650
+ * @returns Promise that resolves when profit processing is complete
651
+ *
652
+ * @example
653
+ * ```typescript
654
+ * // Signal opened at $50000, current price $51500
655
+ * // Revenue: 3% profit
656
+ * await partial.profit("BTCUSDT", signal, 51500, 3.0, false, new Date());
657
+ * // No events emitted (below 10% threshold)
658
+ *
659
+ * // Price rises to $55000
660
+ * // Revenue: 10% profit
661
+ * await partial.profit("BTCUSDT", signal, 55000, 10.0, false, new Date());
662
+ * // Emits partialProfitSubject event for 10% level
663
+ *
664
+ * // Price rises to $61000
665
+ * // Revenue: 22% profit
666
+ * await partial.profit("BTCUSDT", signal, 61000, 22.0, false, new Date());
667
+ * // Emits events for 20% level only (10% already emitted)
668
+ * ```
669
+ */
670
+ profit(symbol: string, data: ISignalRow, currentPrice: number, revenuePercent: number, backtest: boolean, when: Date): Promise<void>;
671
+ /**
672
+ * Processes loss state and emits events for new loss levels reached.
673
+ *
674
+ * Called by ClientStrategy during signal monitoring when revenuePercent < 0.
675
+ * Checks which loss levels (10%, 20%, 30%, etc) have been reached
676
+ * and emits events for new levels only (Set-based deduplication).
677
+ *
678
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
679
+ * @param data - Signal row data
680
+ * @param currentPrice - Current market price
681
+ * @param lossPercent - Current loss percentage (negative value)
682
+ * @param backtest - True if backtest mode, false if live mode
683
+ * @param when - Event timestamp (current time for live, candle time for backtest)
684
+ * @returns Promise that resolves when loss processing is complete
685
+ *
686
+ * @example
687
+ * ```typescript
688
+ * // Signal opened at $50000, current price $48000
689
+ * // Loss: -4% loss
690
+ * await partial.loss("BTCUSDT", signal, 48000, -4.0, false, new Date());
691
+ * // No events emitted (below -10% threshold)
692
+ *
693
+ * // Price drops to $45000
694
+ * // Loss: -10% loss
695
+ * await partial.loss("BTCUSDT", signal, 45000, -10.0, false, new Date());
696
+ * // Emits partialLossSubject event for 10% level
697
+ *
698
+ * // Price drops to $39000
699
+ * // Loss: -22% loss
700
+ * await partial.loss("BTCUSDT", signal, 39000, -22.0, false, new Date());
701
+ * // Emits events for 20% level only (10% already emitted)
702
+ * ```
703
+ */
704
+ loss(symbol: string, data: ISignalRow, currentPrice: number, lossPercent: number, backtest: boolean, when: Date): Promise<void>;
705
+ /**
706
+ * Clears partial profit/loss state when signal closes.
707
+ *
708
+ * Called by ClientStrategy when signal completes (TP/SL/time_expired).
709
+ * Removes signal state from memory and persists changes to disk.
710
+ * Cleans up memoized ClientPartial instance in PartialConnectionService.
711
+ *
712
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
713
+ * @param data - Signal row data
714
+ * @param priceClose - Final closing price
715
+ * @returns Promise that resolves when clear is complete
716
+ *
717
+ * @example
718
+ * ```typescript
719
+ * // Signal closes at take profit
720
+ * await partial.clear("BTCUSDT", signal, 52000);
721
+ * // State removed from _states Map
722
+ * // Persisted to disk without this signal's data
723
+ * // Memoized instance cleared from getPartial cache
724
+ * ```
725
+ */
726
+ clear(symbol: string, data: ISignalRow, priceClose: number): Promise<void>;
727
+ }
728
+
573
729
  /**
574
730
  * Signal generation interval for throttling.
575
731
  * Enforces minimum time between getSignal calls.
@@ -648,6 +804,10 @@ interface IStrategyCallbacks {
648
804
  onCancel: (symbol: string, data: IScheduledSignalRow, currentPrice: number, backtest: boolean) => void;
649
805
  /** Called when signal is written to persist storage (for testing) */
650
806
  onWrite: (symbol: string, data: ISignalRow | null, backtest: boolean) => void;
807
+ /** Called when signal is in partial profit state (price moved favorably but not reached TP yet) */
808
+ onPartialProfit: (symbol: string, data: ISignalRow, currentPrice: number, revenuePercent: number, backtest: boolean) => void;
809
+ /** Called when signal is in partial loss state (price moved against position but not hit SL yet) */
810
+ onPartialLoss: (symbol: string, data: ISignalRow, currentPrice: number, lossPercent: number, backtest: boolean) => void;
651
811
  }
652
812
  /**
653
813
  * Strategy schema registered via addStrategy().
@@ -1009,13 +1169,13 @@ declare class BacktestMarkdownService {
1009
1169
  * Delegates to ReportStorage.dump().
1010
1170
  *
1011
1171
  * @param strategyName - Strategy name to save report for
1012
- * @param path - Directory path to save report (default: "./logs/backtest")
1172
+ * @param path - Directory path to save report (default: "./dump/backtest")
1013
1173
  *
1014
1174
  * @example
1015
1175
  * ```typescript
1016
1176
  * const service = new BacktestMarkdownService();
1017
1177
  *
1018
- * // Save to default path: ./logs/backtest/my-strategy.md
1178
+ * // Save to default path: ./dump/backtest/my-strategy.md
1019
1179
  * await service.dump("my-strategy");
1020
1180
  *
1021
1181
  * // Save to custom path: ./custom/path/my-strategy.md
@@ -1333,6 +1493,418 @@ interface ISizing {
1333
1493
  */
1334
1494
  type SizingName = string;
1335
1495
 
1496
+ /**
1497
+ * Message role type for LLM conversation context.
1498
+ * Defines the sender of a message in a chat-based interaction.
1499
+ */
1500
+ type MessageRole = "assistant" | "system" | "user";
1501
+ /**
1502
+ * Message model for LLM conversation history.
1503
+ * Used in Optimizer to build prompts and maintain conversation context.
1504
+ */
1505
+ interface MessageModel {
1506
+ /**
1507
+ * The sender of the message.
1508
+ * - "system": System instructions and context
1509
+ * - "user": User input and questions
1510
+ * - "assistant": LLM responses
1511
+ */
1512
+ role: MessageRole;
1513
+ /**
1514
+ * The text content of the message.
1515
+ * Contains the actual message text sent or received.
1516
+ */
1517
+ content: string;
1518
+ }
1519
+
1520
+ /**
1521
+ * Unique identifier for data rows in optimizer sources.
1522
+ * Can be either a string or numeric ID.
1523
+ */
1524
+ type RowId = string | number;
1525
+ /**
1526
+ * Time range configuration for optimizer training or testing periods.
1527
+ * Used to define date boundaries for data collection.
1528
+ */
1529
+ interface IOptimizerRange {
1530
+ /**
1531
+ * Optional description of this time range.
1532
+ * Example: "Bull market period 2024-Q1"
1533
+ */
1534
+ note?: string;
1535
+ /**
1536
+ * Start date of the range (inclusive).
1537
+ */
1538
+ startDate: Date;
1539
+ /**
1540
+ * End date of the range (inclusive).
1541
+ */
1542
+ endDate: Date;
1543
+ }
1544
+ /**
1545
+ * Base interface for optimizer data sources.
1546
+ * All data fetched from sources must have a unique ID for deduplication.
1547
+ */
1548
+ interface IOptimizerData {
1549
+ /**
1550
+ * Unique identifier for this data row.
1551
+ * Used for deduplication when paginating data sources.
1552
+ */
1553
+ id: RowId;
1554
+ }
1555
+ /**
1556
+ * Filter arguments for data source queries without pagination.
1557
+ * Used internally to filter data by symbol and time range.
1558
+ */
1559
+ interface IOptimizerFilterArgs {
1560
+ /**
1561
+ * Trading pair symbol (e.g., "BTCUSDT").
1562
+ */
1563
+ symbol: string;
1564
+ /**
1565
+ * Start date of the data range (inclusive).
1566
+ */
1567
+ startDate: Date;
1568
+ /**
1569
+ * End date of the data range (inclusive).
1570
+ */
1571
+ endDate: Date;
1572
+ }
1573
+ /**
1574
+ * Fetch arguments for paginated data source queries.
1575
+ * Extends filter arguments with pagination parameters.
1576
+ */
1577
+ interface IOptimizerFetchArgs extends IOptimizerFilterArgs {
1578
+ /**
1579
+ * Maximum number of records to fetch per request.
1580
+ * Default: 25 (ITERATION_LIMIT)
1581
+ */
1582
+ limit: number;
1583
+ /**
1584
+ * Number of records to skip from the beginning.
1585
+ * Used for pagination (offset = page * limit).
1586
+ */
1587
+ offset: number;
1588
+ }
1589
+ /**
1590
+ * Data source function for fetching optimizer training data.
1591
+ * Must support pagination and return data with unique IDs.
1592
+ *
1593
+ * @param args - Fetch arguments including symbol, dates, limit, offset
1594
+ * @returns Array of data rows or Promise resolving to data array
1595
+ */
1596
+ interface IOptimizerSourceFn<Data extends IOptimizerData = any> {
1597
+ (args: IOptimizerFetchArgs): Data[] | Promise<Data[]>;
1598
+ }
1599
+ /**
1600
+ * Generated strategy data with LLM conversation history.
1601
+ * Contains the full context used to generate a trading strategy.
1602
+ */
1603
+ interface IOptimizerStrategy {
1604
+ /**
1605
+ * Trading pair symbol this strategy was generated for.
1606
+ */
1607
+ symbol: string;
1608
+ /**
1609
+ * Unique name taken from data source.
1610
+ * Used in callbacks and logging.
1611
+ */
1612
+ name: string;
1613
+ /**
1614
+ * LLM conversation history used to generate the strategy.
1615
+ * Contains user prompts and assistant responses for each data source.
1616
+ */
1617
+ messages: MessageModel[];
1618
+ /**
1619
+ * Generated strategy prompt/description.
1620
+ * Output from getPrompt() function, used as strategy logic.
1621
+ */
1622
+ strategy: string;
1623
+ }
1624
+ /**
1625
+ * Data source configuration with custom message formatters.
1626
+ * Defines how to fetch data and format it for LLM conversation.
1627
+ */
1628
+ interface IOptimizerSource<Data extends IOptimizerData = any> {
1629
+ /**
1630
+ * Optional description of this data source.
1631
+ * Example: "Historical backtest results for training"
1632
+ */
1633
+ note?: string;
1634
+ /**
1635
+ * Unique name identifying this data source.
1636
+ * Used in callbacks and logging.
1637
+ */
1638
+ name: string;
1639
+ /**
1640
+ * Function to fetch data from this source.
1641
+ * Must support pagination via limit/offset.
1642
+ */
1643
+ fetch: IOptimizerSourceFn<Data>;
1644
+ /**
1645
+ * Optional custom formatter for user messages.
1646
+ * If not provided, uses default template from OptimizerTemplateService.
1647
+ *
1648
+ * @param symbol - Trading pair symbol
1649
+ * @param data - Fetched data array
1650
+ * @param name - Source name
1651
+ * @returns Formatted user message content
1652
+ */
1653
+ user?: (symbol: string, data: Data[], name: string) => string | Promise<string>;
1654
+ /**
1655
+ * Optional custom formatter for assistant messages.
1656
+ * If not provided, uses default template from OptimizerTemplateService.
1657
+ *
1658
+ * @param symbol - Trading pair symbol
1659
+ * @param data - Fetched data array
1660
+ * @param name - Source name
1661
+ * @returns Formatted assistant message content
1662
+ */
1663
+ assistant?: (symbol: string, data: Data[], name: string) => string | Promise<string>;
1664
+ }
1665
+ /**
1666
+ * Union type for data source configuration.
1667
+ * Can be either a simple fetch function or a full source configuration object.
1668
+ */
1669
+ type Source<Data extends IOptimizerData = any> = IOptimizerSourceFn<Data> | IOptimizerSource<Data>;
1670
+ /**
1671
+ * Lifecycle callbacks for optimizer events.
1672
+ * Provides hooks for monitoring and validating optimizer operations.
1673
+ */
1674
+ interface IOptimizerCallbacks {
1675
+ /**
1676
+ * Called after strategy data is generated for all train ranges.
1677
+ * Useful for logging or validating the generated strategies.
1678
+ *
1679
+ * @param symbol - Trading pair symbol
1680
+ * @param strategyData - Array of generated strategies with their messages
1681
+ */
1682
+ onData?: (symbol: string, strategyData: IOptimizerStrategy[]) => void | Promise<void>;
1683
+ /**
1684
+ * Called after strategy code is generated.
1685
+ * Useful for logging or validating the generated code.
1686
+ *
1687
+ * @param symbol - Trading pair symbol
1688
+ * @param code - Generated strategy code
1689
+ */
1690
+ onCode?: (symbol: string, code: string) => void | Promise<void>;
1691
+ /**
1692
+ * Called after strategy code is dumped to file.
1693
+ * Useful for logging or performing additional actions after file write.
1694
+ *
1695
+ * @param symbol - Trading pair symbol
1696
+ * @param filepath - Path where the file was saved
1697
+ */
1698
+ onDump?: (symbol: string, filepath: string) => void | Promise<void>;
1699
+ /**
1700
+ * Called after data is fetched from a source.
1701
+ * Useful for logging or validating the fetched data.
1702
+ *
1703
+ * @param symbol - Trading pair symbol
1704
+ * @param sourceName - Name of the data source
1705
+ * @param data - Array of fetched data
1706
+ * @param startDate - Start date of the data range
1707
+ * @param endDate - End date of the data range
1708
+ */
1709
+ onSourceData?: <Data extends IOptimizerData = any>(symbol: string, sourceName: string, data: Data[], startDate: Date, endDate: Date) => void | Promise<void>;
1710
+ }
1711
+ /**
1712
+ * Template interface for generating code snippets and LLM messages.
1713
+ * Each method returns TypeScript/JavaScript code as a string.
1714
+ */
1715
+ interface IOptimizerTemplate {
1716
+ /**
1717
+ * Generates the top banner with imports and initialization.
1718
+ *
1719
+ * @param symbol - Trading pair symbol
1720
+ * @returns Generated import statements and setup code
1721
+ */
1722
+ getTopBanner(symbol: string): string | Promise<string>;
1723
+ /**
1724
+ * Generates default user message content for LLM conversation.
1725
+ *
1726
+ * @param symbol - Trading pair symbol
1727
+ * @param data - Data array from source
1728
+ * @param name - Source name
1729
+ * @returns Formatted user message content
1730
+ */
1731
+ getUserMessage<Data extends IOptimizerData = any>(symbol: string, data: Data[], name: string): string | Promise<string>;
1732
+ /**
1733
+ * Generates default assistant message content for LLM conversation.
1734
+ *
1735
+ * @param symbol - Trading pair symbol
1736
+ * @param data - Data array from source
1737
+ * @param name - Source name
1738
+ * @returns Formatted assistant message content
1739
+ */
1740
+ getAssistantMessage<Data extends IOptimizerData = any>(symbol: string, data: Data[], name: string): string | Promise<string>;
1741
+ /**
1742
+ * Generates Walker configuration code.
1743
+ *
1744
+ * @param walkerName - Unique walker identifier
1745
+ * @param exchangeName - Exchange name to use
1746
+ * @param frameName - Frame name for testing
1747
+ * @param strategies - Array of strategy names to compare
1748
+ * @returns Generated addWalker() call
1749
+ */
1750
+ getWalkerTemplate(walkerName: string, exchangeName: string, frameName: string, strategies: string[]): string | Promise<string>;
1751
+ /**
1752
+ * Generates Exchange configuration code.
1753
+ *
1754
+ * @param symbol - Trading pair symbol
1755
+ * @param exchangeName - Unique exchange identifier
1756
+ * @returns Generated addExchange() call with CCXT integration
1757
+ */
1758
+ getExchangeTemplate(symbol: string, exchangeName: string): string | Promise<string>;
1759
+ /**
1760
+ * Generates Frame (timeframe) configuration code.
1761
+ *
1762
+ * @param symbol - Trading pair symbol
1763
+ * @param frameName - Unique frame identifier
1764
+ * @param interval - Candle interval (e.g., "1m", "5m")
1765
+ * @param startDate - Frame start date
1766
+ * @param endDate - Frame end date
1767
+ * @returns Generated addFrame() call
1768
+ */
1769
+ getFrameTemplate(symbol: string, frameName: string, interval: CandleInterval, startDate: Date, endDate: Date): string | Promise<string>;
1770
+ /**
1771
+ * Generates Strategy configuration code with LLM integration.
1772
+ *
1773
+ * @param strategyName - Unique strategy identifier
1774
+ * @param interval - Signal throttling interval (e.g., "5m")
1775
+ * @param prompt - Strategy logic prompt from getPrompt()
1776
+ * @returns Generated addStrategy() call with getSignal() function
1777
+ */
1778
+ getStrategyTemplate(strategyName: string, interval: string, prompt: string): string | Promise<string>;
1779
+ /**
1780
+ * Generates launcher code to run Walker and listen to events.
1781
+ *
1782
+ * @param symbol - Trading pair symbol
1783
+ * @param walkerName - Walker name to launch
1784
+ * @returns Generated Walker.background() call with event listeners
1785
+ */
1786
+ getLauncherTemplate(symbol: string, walkerName: string): string | Promise<string>;
1787
+ /**
1788
+ * Generates text() helper function for LLM text generation.
1789
+ *
1790
+ * @param symbol - Trading pair symbol
1791
+ * @returns Generated async text() function using Ollama
1792
+ */
1793
+ getTextTemplate(symbol: string): string | Promise<string>;
1794
+ /**
1795
+ * Generates json() helper function for structured LLM output.
1796
+ *
1797
+ * @param symbol - Trading pair symbol
1798
+ * @returns Generated async json() function with signal schema
1799
+ */
1800
+ getJsonTemplate(symbol: string): string | Promise<string>;
1801
+ /**
1802
+ * Generates dumpJson() helper function for debug output.
1803
+ *
1804
+ * @param symbol - Trading pair symbol
1805
+ * @returns Generated async dumpJson() function for file logging
1806
+ */
1807
+ getJsonDumpTemplate: (symbol: string) => string | Promise<string>;
1808
+ }
1809
+ /**
1810
+ * Schema configuration for optimizer registration.
1811
+ * Defines how to collect data, generate strategies, and create executable code.
1812
+ */
1813
+ interface IOptimizerSchema {
1814
+ /**
1815
+ * Optional description of this optimizer configuration.
1816
+ */
1817
+ note?: string;
1818
+ /**
1819
+ * Unique identifier for this optimizer.
1820
+ * Used to retrieve optimizer instance from registry.
1821
+ */
1822
+ optimizerName: OptimizerName;
1823
+ /**
1824
+ * Array of training time ranges.
1825
+ * Each range generates a separate strategy variant for comparison.
1826
+ */
1827
+ rangeTrain: IOptimizerRange[];
1828
+ /**
1829
+ * Testing time range for strategy validation.
1830
+ * Used in generated Walker to evaluate strategy performance.
1831
+ */
1832
+ rangeTest: IOptimizerRange;
1833
+ /**
1834
+ * Array of data sources for strategy generation.
1835
+ * Each source contributes to the LLM conversation context.
1836
+ */
1837
+ source: Source[];
1838
+ /**
1839
+ * Function to generate strategy prompt from conversation history.
1840
+ * Called after all sources are processed for each training range.
1841
+ *
1842
+ * @param symbol - Trading pair symbol
1843
+ * @param messages - Complete conversation history with all sources
1844
+ * @returns Strategy prompt/logic description
1845
+ */
1846
+ getPrompt: (symbol: string, messages: MessageModel[]) => string | Promise<string>;
1847
+ /**
1848
+ * Optional custom template overrides.
1849
+ * If not provided, uses defaults from OptimizerTemplateService.
1850
+ */
1851
+ template?: Partial<IOptimizerTemplate>;
1852
+ /**
1853
+ * Optional lifecycle callbacks for monitoring.
1854
+ */
1855
+ callbacks?: Partial<IOptimizerCallbacks>;
1856
+ }
1857
+ /**
1858
+ * Internal parameters for ClientOptimizer instantiation.
1859
+ * Extends schema with resolved dependencies (logger, complete template).
1860
+ */
1861
+ interface IOptimizerParams extends IOptimizerSchema {
1862
+ /**
1863
+ * Logger instance for debug and info messages.
1864
+ * Injected by OptimizerConnectionService.
1865
+ */
1866
+ logger: ILogger;
1867
+ /**
1868
+ * Complete template implementation with all methods.
1869
+ * Merged from schema.template and OptimizerTemplateService defaults.
1870
+ */
1871
+ template: IOptimizerTemplate;
1872
+ }
1873
+ /**
1874
+ * Optimizer client interface for strategy generation and code export.
1875
+ * Implemented by ClientOptimizer class.
1876
+ */
1877
+ interface IOptimizer {
1878
+ /**
1879
+ * Fetches data from all sources and generates strategy metadata.
1880
+ * Processes each training range and builds LLM conversation history.
1881
+ *
1882
+ * @param symbol - Trading pair symbol
1883
+ * @returns Array of generated strategies with conversation context
1884
+ */
1885
+ getData(symbol: string): Promise<IOptimizerStrategy[]>;
1886
+ /**
1887
+ * Generates complete executable strategy code.
1888
+ * Includes imports, helpers, strategies, walker, and launcher.
1889
+ *
1890
+ * @param symbol - Trading pair symbol
1891
+ * @returns Generated TypeScript/JavaScript code as string
1892
+ */
1893
+ getCode(symbol: string): Promise<string>;
1894
+ /**
1895
+ * Generates and saves strategy code to file.
1896
+ * Creates directory if needed, writes .mjs file.
1897
+ *
1898
+ * @param symbol - Trading pair symbol
1899
+ * @param path - Output directory path (default: "./")
1900
+ */
1901
+ dump(symbol: string, path?: string): Promise<void>;
1902
+ }
1903
+ /**
1904
+ * Unique string identifier for registered optimizers.
1905
+ */
1906
+ type OptimizerName = string;
1907
+
1336
1908
  /**
1337
1909
  * Registers a trading strategy in the framework.
1338
1910
  *
@@ -1588,7 +2160,95 @@ declare function addSizing(sizingSchema: ISizingSchema): void;
1588
2160
  * ```
1589
2161
  */
1590
2162
  declare function addRisk(riskSchema: IRiskSchema): void;
1591
-
2163
+ /**
2164
+ * Registers an optimizer configuration in the framework.
2165
+ *
2166
+ * The optimizer generates trading strategies by:
2167
+ * - Collecting data from multiple sources across training periods
2168
+ * - Building LLM conversation history with fetched data
2169
+ * - Generating strategy prompts using getPrompt()
2170
+ * - Creating executable backtest code with templates
2171
+ *
2172
+ * The optimizer produces a complete .mjs file containing:
2173
+ * - Exchange, Frame, Strategy, and Walker configurations
2174
+ * - Multi-timeframe analysis logic
2175
+ * - LLM integration for signal generation
2176
+ * - Event listeners for progress tracking
2177
+ *
2178
+ * @param optimizerSchema - Optimizer configuration object
2179
+ * @param optimizerSchema.optimizerName - Unique optimizer identifier
2180
+ * @param optimizerSchema.rangeTrain - Array of training time ranges (each generates a strategy variant)
2181
+ * @param optimizerSchema.rangeTest - Testing time range for strategy validation
2182
+ * @param optimizerSchema.source - Array of data sources (functions or source objects with custom formatters)
2183
+ * @param optimizerSchema.getPrompt - Function to generate strategy prompt from conversation history
2184
+ * @param optimizerSchema.template - Optional custom template overrides (top banner, helpers, strategy logic, etc.)
2185
+ * @param optimizerSchema.callbacks - Optional lifecycle callbacks (onData, onCode, onDump, onSourceData)
2186
+ *
2187
+ * @example
2188
+ * ```typescript
2189
+ * // Basic optimizer with single data source
2190
+ * addOptimizer({
2191
+ * optimizerName: "llm-strategy-generator",
2192
+ * rangeTrain: [
2193
+ * {
2194
+ * note: "Bull market period",
2195
+ * startDate: new Date("2024-01-01"),
2196
+ * endDate: new Date("2024-01-31"),
2197
+ * },
2198
+ * {
2199
+ * note: "Bear market period",
2200
+ * startDate: new Date("2024-02-01"),
2201
+ * endDate: new Date("2024-02-28"),
2202
+ * },
2203
+ * ],
2204
+ * rangeTest: {
2205
+ * note: "Validation period",
2206
+ * startDate: new Date("2024-03-01"),
2207
+ * endDate: new Date("2024-03-31"),
2208
+ * },
2209
+ * source: [
2210
+ * {
2211
+ * name: "historical-backtests",
2212
+ * fetch: async ({ symbol, startDate, endDate, limit, offset }) => {
2213
+ * // Fetch historical backtest results from database
2214
+ * return await db.backtests.find({
2215
+ * symbol,
2216
+ * date: { $gte: startDate, $lte: endDate },
2217
+ * })
2218
+ * .skip(offset)
2219
+ * .limit(limit);
2220
+ * },
2221
+ * user: async (symbol, data, name) => {
2222
+ * return `Analyze these ${data.length} backtest results for ${symbol}:\n${JSON.stringify(data)}`;
2223
+ * },
2224
+ * assistant: async (symbol, data, name) => {
2225
+ * return "Historical data analyzed successfully";
2226
+ * },
2227
+ * },
2228
+ * ],
2229
+ * getPrompt: async (symbol, messages) => {
2230
+ * // Generate strategy prompt from conversation
2231
+ * return `"Analyze ${symbol} using RSI and MACD. Enter LONG when RSI < 30 and MACD crosses above signal."`;
2232
+ * },
2233
+ * callbacks: {
2234
+ * onData: (symbol, strategyData) => {
2235
+ * console.log(`Generated ${strategyData.length} strategies for ${symbol}`);
2236
+ * },
2237
+ * onCode: (symbol, code) => {
2238
+ * console.log(`Generated ${code.length} characters of code for ${symbol}`);
2239
+ * },
2240
+ * onDump: (symbol, filepath) => {
2241
+ * console.log(`Saved strategy to ${filepath}`);
2242
+ * },
2243
+ * onSourceData: (symbol, sourceName, data, startDate, endDate) => {
2244
+ * console.log(`Fetched ${data.length} rows from ${sourceName} for ${symbol}`);
2245
+ * },
2246
+ * },
2247
+ * });
2248
+ * ```
2249
+ */
2250
+ declare function addOptimizer(optimizerSchema: IOptimizerSchema): void;
2251
+
1592
2252
  /**
1593
2253
  * Returns a list of all registered exchange schemas.
1594
2254
  *
@@ -1768,6 +2428,43 @@ declare function listSizings(): Promise<ISizingSchema[]>;
1768
2428
  * ```
1769
2429
  */
1770
2430
  declare function listRisks(): Promise<IRiskSchema[]>;
2431
+ /**
2432
+ * Returns a list of all registered optimizer schemas.
2433
+ *
2434
+ * Retrieves all optimizers that have been registered via addOptimizer().
2435
+ * Useful for debugging, documentation, or building dynamic UIs.
2436
+ *
2437
+ * @returns Array of optimizer schemas with their configurations
2438
+ *
2439
+ * @example
2440
+ * ```typescript
2441
+ * import { listOptimizers, addOptimizer } from "backtest-kit";
2442
+ *
2443
+ * addOptimizer({
2444
+ * optimizerName: "llm-strategy-generator",
2445
+ * note: "Generates trading strategies using LLM",
2446
+ * rangeTrain: [
2447
+ * {
2448
+ * note: "Training period 1",
2449
+ * startDate: new Date("2024-01-01"),
2450
+ * endDate: new Date("2024-01-31"),
2451
+ * },
2452
+ * ],
2453
+ * rangeTest: {
2454
+ * note: "Testing period",
2455
+ * startDate: new Date("2024-02-01"),
2456
+ * endDate: new Date("2024-02-28"),
2457
+ * },
2458
+ * source: [],
2459
+ * getPrompt: async (symbol, messages) => "Generate strategy",
2460
+ * });
2461
+ *
2462
+ * const optimizers = listOptimizers();
2463
+ * console.log(optimizers);
2464
+ * // [{ optimizerName: "llm-strategy-generator", note: "Generates...", ... }]
2465
+ * ```
2466
+ */
2467
+ declare function listOptimizers(): Promise<IOptimizerSchema[]>;
1771
2468
 
1772
2469
  /**
1773
2470
  * Contract for background execution completion events.
@@ -1807,15 +2504,15 @@ interface DoneContract {
1807
2504
  *
1808
2505
  * @example
1809
2506
  * ```typescript
1810
- * import { listenProgress } from "backtest-kit";
2507
+ * import { listenBacktestProgress } from "backtest-kit";
1811
2508
  *
1812
- * listenProgress((event) => {
2509
+ * listenBacktestProgress((event) => {
1813
2510
  * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
1814
2511
  * console.log(`Processed: ${event.processedFrames} / ${event.totalFrames}`);
1815
2512
  * });
1816
2513
  * ```
1817
2514
  */
1818
- interface ProgressContract {
2515
+ interface ProgressBacktestContract {
1819
2516
  /** exchangeName - Name of the exchange used in execution */
1820
2517
  exchangeName: string;
1821
2518
  /** strategyName - Name of the strategy being executed */
@@ -1830,6 +2527,39 @@ interface ProgressContract {
1830
2527
  progress: number;
1831
2528
  }
1832
2529
 
2530
+ /**
2531
+ * Contract for walker progress events.
2532
+ *
2533
+ * Emitted during Walker.background() execution to track progress.
2534
+ * Contains information about total strategies, processed strategies, and completion percentage.
2535
+ *
2536
+ * @example
2537
+ * ```typescript
2538
+ * import { listenWalkerProgress } from "backtest-kit";
2539
+ *
2540
+ * listenWalkerProgress((event) => {
2541
+ * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
2542
+ * console.log(`Processed: ${event.processedStrategies} / ${event.totalStrategies}`);
2543
+ * });
2544
+ * ```
2545
+ */
2546
+ interface ProgressWalkerContract {
2547
+ /** walkerName - Name of the walker being executed */
2548
+ walkerName: string;
2549
+ /** exchangeName - Name of the exchange used in execution */
2550
+ exchangeName: string;
2551
+ /** frameName - Name of the frame being used */
2552
+ frameName: string;
2553
+ /** symbol - Trading symbol (e.g., "BTCUSDT") */
2554
+ symbol: string;
2555
+ /** totalStrategies - Total number of strategies to process */
2556
+ totalStrategies: number;
2557
+ /** processedStrategies - Number of strategies processed so far */
2558
+ processedStrategies: number;
2559
+ /** progress - Completion percentage from 0.0 to 1.0 */
2560
+ progress: number;
2561
+ }
2562
+
1833
2563
  /**
1834
2564
  * Performance metric types tracked by the system.
1835
2565
  *
@@ -1908,6 +2638,180 @@ interface WalkerContract {
1908
2638
  totalStrategies: number;
1909
2639
  }
1910
2640
 
2641
+ /**
2642
+ * Contract for partial profit level events.
2643
+ *
2644
+ * Emitted by partialProfitSubject when a signal reaches a profit level milestone (10%, 20%, 30%, etc).
2645
+ * Used for tracking partial take-profit execution and monitoring strategy performance.
2646
+ *
2647
+ * Events are emitted only once per level per signal (Set-based deduplication in ClientPartial).
2648
+ * Multiple levels can be emitted in a single tick if price jumps significantly.
2649
+ *
2650
+ * Consumers:
2651
+ * - PartialMarkdownService: Accumulates events for report generation
2652
+ * - User callbacks via listenPartialProfit() / listenPartialProfitOnce()
2653
+ *
2654
+ * @example
2655
+ * ```typescript
2656
+ * import { listenPartialProfit } from "backtest-kit";
2657
+ *
2658
+ * // Listen to all partial profit events
2659
+ * listenPartialProfit((event) => {
2660
+ * console.log(`[${event.backtest ? "Backtest" : "Live"}] Signal ${event.data.id} reached ${event.level}% profit`);
2661
+ * console.log(`Symbol: ${event.symbol}, Price: ${event.currentPrice}`);
2662
+ * console.log(`Position: ${event.data.position}, Entry: ${event.data.priceOpen}`);
2663
+ * });
2664
+ *
2665
+ * // Wait for first 50% profit level
2666
+ * listenPartialProfitOnce(
2667
+ * (event) => event.level === 50,
2668
+ * (event) => console.log("50% profit reached:", event.data.id)
2669
+ * );
2670
+ * ```
2671
+ */
2672
+ interface PartialProfitContract {
2673
+ /**
2674
+ * Trading pair symbol (e.g., "BTCUSDT").
2675
+ * Identifies which market this profit event belongs to.
2676
+ */
2677
+ symbol: string;
2678
+ /**
2679
+ * Complete signal row data.
2680
+ * Contains all signal information: id, position, priceOpen, priceTakeProfit, priceStopLoss, etc.
2681
+ */
2682
+ data: ISignalRow;
2683
+ /**
2684
+ * Current market price at which this profit level was reached.
2685
+ * Used to calculate actual profit percentage.
2686
+ */
2687
+ currentPrice: number;
2688
+ /**
2689
+ * Profit level milestone reached (10, 20, 30, 40, 50, 60, 70, 80, 90, or 100).
2690
+ * Represents percentage profit relative to entry price.
2691
+ *
2692
+ * @example
2693
+ * ```typescript
2694
+ * // If entry was $50000 and level is 20:
2695
+ * // currentPrice >= $60000 (20% profit)
2696
+ * ```
2697
+ */
2698
+ level: PartialLevel;
2699
+ /**
2700
+ * Execution mode flag.
2701
+ * - true: Event from backtest execution (historical candle data)
2702
+ * - false: Event from live trading (real-time tick)
2703
+ */
2704
+ backtest: boolean;
2705
+ /**
2706
+ * Event timestamp in milliseconds since Unix epoch.
2707
+ *
2708
+ * Timing semantics:
2709
+ * - Live mode: when.getTime() at the moment profit level was detected
2710
+ * - Backtest mode: candle.timestamp of the candle that triggered the level
2711
+ *
2712
+ * @example
2713
+ * ```typescript
2714
+ * const eventDate = new Date(event.timestamp);
2715
+ * console.log(`Profit reached at: ${eventDate.toISOString()}`);
2716
+ * ```
2717
+ */
2718
+ timestamp: number;
2719
+ }
2720
+
2721
+ /**
2722
+ * Contract for partial loss level events.
2723
+ *
2724
+ * Emitted by partialLossSubject when a signal reaches a loss level milestone (-10%, -20%, -30%, etc).
2725
+ * Used for tracking partial stop-loss execution and monitoring strategy drawdown.
2726
+ *
2727
+ * Events are emitted only once per level per signal (Set-based deduplication in ClientPartial).
2728
+ * Multiple levels can be emitted in a single tick if price drops significantly.
2729
+ *
2730
+ * Consumers:
2731
+ * - PartialMarkdownService: Accumulates events for report generation
2732
+ * - User callbacks via listenPartialLoss() / listenPartialLossOnce()
2733
+ *
2734
+ * @example
2735
+ * ```typescript
2736
+ * import { listenPartialLoss } from "backtest-kit";
2737
+ *
2738
+ * // Listen to all partial loss events
2739
+ * listenPartialLoss((event) => {
2740
+ * console.log(`[${event.backtest ? "Backtest" : "Live"}] Signal ${event.data.id} reached -${event.level}% loss`);
2741
+ * console.log(`Symbol: ${event.symbol}, Price: ${event.currentPrice}`);
2742
+ * console.log(`Position: ${event.data.position}, Entry: ${event.data.priceOpen}`);
2743
+ *
2744
+ * // Alert on significant loss
2745
+ * if (event.level >= 30 && !event.backtest) {
2746
+ * console.warn("HIGH LOSS ALERT:", event.data.id);
2747
+ * }
2748
+ * });
2749
+ *
2750
+ * // Wait for first 20% loss level
2751
+ * listenPartialLossOnce(
2752
+ * (event) => event.level === 20,
2753
+ * (event) => console.log("20% loss reached:", event.data.id)
2754
+ * );
2755
+ * ```
2756
+ */
2757
+ interface PartialLossContract {
2758
+ /**
2759
+ * Trading pair symbol (e.g., "BTCUSDT").
2760
+ * Identifies which market this loss event belongs to.
2761
+ */
2762
+ symbol: string;
2763
+ /**
2764
+ * Complete signal row data.
2765
+ * Contains all signal information: id, position, priceOpen, priceTakeProfit, priceStopLoss, etc.
2766
+ */
2767
+ data: ISignalRow;
2768
+ /**
2769
+ * Current market price at which this loss level was reached.
2770
+ * Used to calculate actual loss percentage.
2771
+ */
2772
+ currentPrice: number;
2773
+ /**
2774
+ * Loss level milestone reached (10, 20, 30, 40, 50, 60, 70, 80, 90, or 100).
2775
+ * Represents percentage loss relative to entry price (absolute value).
2776
+ *
2777
+ * Note: Stored as positive number, but represents negative loss.
2778
+ * level=20 means -20% loss from entry price.
2779
+ *
2780
+ * @example
2781
+ * ```typescript
2782
+ * // If entry was $50000 and level is 20:
2783
+ * // currentPrice <= $40000 (-20% loss)
2784
+ * // Level is stored as 20, not -20
2785
+ * ```
2786
+ */
2787
+ level: PartialLevel;
2788
+ /**
2789
+ * Execution mode flag.
2790
+ * - true: Event from backtest execution (historical candle data)
2791
+ * - false: Event from live trading (real-time tick)
2792
+ */
2793
+ backtest: boolean;
2794
+ /**
2795
+ * Event timestamp in milliseconds since Unix epoch.
2796
+ *
2797
+ * Timing semantics:
2798
+ * - Live mode: when.getTime() at the moment loss level was detected
2799
+ * - Backtest mode: candle.timestamp of the candle that triggered the level
2800
+ *
2801
+ * @example
2802
+ * ```typescript
2803
+ * const eventDate = new Date(event.timestamp);
2804
+ * console.log(`Loss reached at: ${eventDate.toISOString()}`);
2805
+ *
2806
+ * // Calculate time in loss
2807
+ * const entryTime = event.data.pendingAt;
2808
+ * const timeInLoss = event.timestamp - entryTime;
2809
+ * console.log(`In loss for ${timeInLoss / 1000 / 60} minutes`);
2810
+ * ```
2811
+ */
2812
+ timestamp: number;
2813
+ }
2814
+
1911
2815
  /**
1912
2816
  * Subscribes to all signal events with queued async processing.
1913
2817
  *
@@ -2254,9 +3158,9 @@ declare function listenDoneWalkerOnce(filterFn: (event: DoneContract) => boolean
2254
3158
  *
2255
3159
  * @example
2256
3160
  * ```typescript
2257
- * import { listenProgress, Backtest } from "backtest-kit";
3161
+ * import { listenBacktestProgress, Backtest } from "backtest-kit";
2258
3162
  *
2259
- * const unsubscribe = listenProgress((event) => {
3163
+ * const unsubscribe = listenBacktestProgress((event) => {
2260
3164
  * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
2261
3165
  * console.log(`${event.processedFrames} / ${event.totalFrames} frames`);
2262
3166
  * console.log(`Strategy: ${event.strategyName}, Symbol: ${event.symbol}`);
@@ -2272,7 +3176,38 @@ declare function listenDoneWalkerOnce(filterFn: (event: DoneContract) => boolean
2272
3176
  * unsubscribe();
2273
3177
  * ```
2274
3178
  */
2275
- declare function listenProgress(fn: (event: ProgressContract) => void): () => void;
3179
+ declare function listenBacktestProgress(fn: (event: ProgressBacktestContract) => void): () => void;
3180
+ /**
3181
+ * Subscribes to walker progress events with queued async processing.
3182
+ *
3183
+ * Emits during Walker.run() execution after each strategy completes.
3184
+ * Events are processed sequentially in order received, even if callback is async.
3185
+ * Uses queued wrapper to prevent concurrent execution of the callback.
3186
+ *
3187
+ * @param fn - Callback function to handle walker progress events
3188
+ * @returns Unsubscribe function to stop listening to events
3189
+ *
3190
+ * @example
3191
+ * ```typescript
3192
+ * import { listenWalkerProgress, Walker } from "backtest-kit";
3193
+ *
3194
+ * const unsubscribe = listenWalkerProgress((event) => {
3195
+ * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
3196
+ * console.log(`${event.processedStrategies} / ${event.totalStrategies} strategies`);
3197
+ * console.log(`Walker: ${event.walkerName}, Symbol: ${event.symbol}`);
3198
+ * });
3199
+ *
3200
+ * Walker.run("BTCUSDT", {
3201
+ * walkerName: "my-walker",
3202
+ * exchangeName: "binance",
3203
+ * frameName: "1d-backtest"
3204
+ * });
3205
+ *
3206
+ * // Later: stop listening
3207
+ * unsubscribe();
3208
+ * ```
3209
+ */
3210
+ declare function listenWalkerProgress(fn: (event: ProgressWalkerContract) => void): () => void;
2276
3211
  /**
2277
3212
  * Subscribes to performance metric events with queued async processing.
2278
3213
  *
@@ -2434,6 +3369,118 @@ declare function listenWalkerComplete(fn: (event: IWalkerResults) => void): () =
2434
3369
  * ```
2435
3370
  */
2436
3371
  declare function listenValidation(fn: (error: Error) => void): () => void;
3372
+ /**
3373
+ * Subscribes to partial profit level events with queued async processing.
3374
+ *
3375
+ * Emits when a signal reaches a profit level milestone (10%, 20%, 30%, etc).
3376
+ * Events are processed sequentially in order received, even if callback is async.
3377
+ * Uses queued wrapper to prevent concurrent execution of the callback.
3378
+ *
3379
+ * @param fn - Callback function to handle partial profit events
3380
+ * @returns Unsubscribe function to stop listening to events
3381
+ *
3382
+ * @example
3383
+ * ```typescript
3384
+ * import { listenPartialProfit } from "./function/event";
3385
+ *
3386
+ * const unsubscribe = listenPartialProfit((event) => {
3387
+ * console.log(`Signal ${event.data.id} reached ${event.level}% profit`);
3388
+ * console.log(`Symbol: ${event.symbol}, Price: ${event.currentPrice}`);
3389
+ * console.log(`Mode: ${event.backtest ? "Backtest" : "Live"}`);
3390
+ * });
3391
+ *
3392
+ * // Later: stop listening
3393
+ * unsubscribe();
3394
+ * ```
3395
+ */
3396
+ declare function listenPartialProfit(fn: (event: PartialProfitContract) => void): () => void;
3397
+ /**
3398
+ * Subscribes to filtered partial profit level events with one-time execution.
3399
+ *
3400
+ * Listens for events matching the filter predicate, then executes callback once
3401
+ * and automatically unsubscribes. Useful for waiting for specific profit conditions.
3402
+ *
3403
+ * @param filterFn - Predicate to filter which events trigger the callback
3404
+ * @param fn - Callback function to handle the filtered event (called only once)
3405
+ * @returns Unsubscribe function to cancel the listener before it fires
3406
+ *
3407
+ * @example
3408
+ * ```typescript
3409
+ * import { listenPartialProfitOnce } from "./function/event";
3410
+ *
3411
+ * // Wait for first 50% profit level on any signal
3412
+ * listenPartialProfitOnce(
3413
+ * (event) => event.level === 50,
3414
+ * (event) => console.log("50% profit reached:", event.data.id)
3415
+ * );
3416
+ *
3417
+ * // Wait for 30% profit on BTCUSDT
3418
+ * const cancel = listenPartialProfitOnce(
3419
+ * (event) => event.symbol === "BTCUSDT" && event.level === 30,
3420
+ * (event) => console.log("BTCUSDT hit 30% profit")
3421
+ * );
3422
+ *
3423
+ * // Cancel if needed before event fires
3424
+ * cancel();
3425
+ * ```
3426
+ */
3427
+ declare function listenPartialProfitOnce(filterFn: (event: PartialProfitContract) => boolean, fn: (event: PartialProfitContract) => void): () => void;
3428
+ /**
3429
+ * Subscribes to partial loss level events with queued async processing.
3430
+ *
3431
+ * Emits when a signal reaches a loss level milestone (10%, 20%, 30%, etc).
3432
+ * Events are processed sequentially in order received, even if callback is async.
3433
+ * Uses queued wrapper to prevent concurrent execution of the callback.
3434
+ *
3435
+ * @param fn - Callback function to handle partial loss events
3436
+ * @returns Unsubscribe function to stop listening to events
3437
+ *
3438
+ * @example
3439
+ * ```typescript
3440
+ * import { listenPartialLoss } from "./function/event";
3441
+ *
3442
+ * const unsubscribe = listenPartialLoss((event) => {
3443
+ * console.log(`Signal ${event.data.id} reached ${event.level}% loss`);
3444
+ * console.log(`Symbol: ${event.symbol}, Price: ${event.currentPrice}`);
3445
+ * console.log(`Mode: ${event.backtest ? "Backtest" : "Live"}`);
3446
+ * });
3447
+ *
3448
+ * // Later: stop listening
3449
+ * unsubscribe();
3450
+ * ```
3451
+ */
3452
+ declare function listenPartialLoss(fn: (event: PartialLossContract) => void): () => void;
3453
+ /**
3454
+ * Subscribes to filtered partial loss level events with one-time execution.
3455
+ *
3456
+ * Listens for events matching the filter predicate, then executes callback once
3457
+ * and automatically unsubscribes. Useful for waiting for specific loss conditions.
3458
+ *
3459
+ * @param filterFn - Predicate to filter which events trigger the callback
3460
+ * @param fn - Callback function to handle the filtered event (called only once)
3461
+ * @returns Unsubscribe function to cancel the listener before it fires
3462
+ *
3463
+ * @example
3464
+ * ```typescript
3465
+ * import { listenPartialLossOnce } from "./function/event";
3466
+ *
3467
+ * // Wait for first 20% loss level on any signal
3468
+ * listenPartialLossOnce(
3469
+ * (event) => event.level === 20,
3470
+ * (event) => console.log("20% loss reached:", event.data.id)
3471
+ * );
3472
+ *
3473
+ * // Wait for 10% loss on ETHUSDT in live mode
3474
+ * const cancel = listenPartialLossOnce(
3475
+ * (event) => event.symbol === "ETHUSDT" && event.level === 10 && !event.backtest,
3476
+ * (event) => console.log("ETHUSDT hit 10% loss in live mode")
3477
+ * );
3478
+ *
3479
+ * // Cancel if needed before event fires
3480
+ * cancel();
3481
+ * ```
3482
+ */
3483
+ declare function listenPartialLossOnce(filterFn: (event: PartialLossContract) => boolean, fn: (event: PartialLossContract) => void): () => void;
2437
3484
 
2438
3485
  /**
2439
3486
  * Fetches historical candle data from the registered exchange.
@@ -2770,13 +3817,13 @@ declare class LiveMarkdownService {
2770
3817
  * Delegates to ReportStorage.dump().
2771
3818
  *
2772
3819
  * @param strategyName - Strategy name to save report for
2773
- * @param path - Directory path to save report (default: "./logs/live")
3820
+ * @param path - Directory path to save report (default: "./dump/live")
2774
3821
  *
2775
3822
  * @example
2776
3823
  * ```typescript
2777
3824
  * const service = new LiveMarkdownService();
2778
3825
  *
2779
- * // Save to default path: ./logs/live/my-strategy.md
3826
+ * // Save to default path: ./dump/live/my-strategy.md
2780
3827
  * await service.dump("my-strategy");
2781
3828
  *
2782
3829
  * // Save to custom path: ./custom/path/my-strategy.md
@@ -2963,13 +4010,13 @@ declare class ScheduleMarkdownService {
2963
4010
  * Delegates to ReportStorage.dump().
2964
4011
  *
2965
4012
  * @param strategyName - Strategy name to save report for
2966
- * @param path - Directory path to save report (default: "./logs/schedule")
4013
+ * @param path - Directory path to save report (default: "./dump/schedule")
2967
4014
  *
2968
4015
  * @example
2969
4016
  * ```typescript
2970
4017
  * const service = new ScheduleMarkdownService();
2971
4018
  *
2972
- * // Save to default path: ./logs/schedule/my-strategy.md
4019
+ * // Save to default path: ./dump/schedule/my-strategy.md
2973
4020
  * await service.dump("my-strategy");
2974
4021
  *
2975
4022
  * // Save to custom path: ./custom/path/my-strategy.md
@@ -3134,7 +4181,7 @@ declare class PerformanceMarkdownService {
3134
4181
  *
3135
4182
  * @example
3136
4183
  * ```typescript
3137
- * // Save to default path: ./logs/performance/my-strategy.md
4184
+ * // Save to default path: ./dump/performance/my-strategy.md
3138
4185
  * await performanceService.dump("my-strategy");
3139
4186
  *
3140
4187
  * // Save to custom path
@@ -3184,116 +4231,300 @@ declare class WalkerMarkdownService {
3184
4231
  * Memoized function to get or create ReportStorage for a walker.
3185
4232
  * Each walker gets its own isolated storage instance.
3186
4233
  */
3187
- private getStorage;
4234
+ private getStorage;
4235
+ /**
4236
+ * Processes walker progress events and accumulates strategy results.
4237
+ * Should be called from walkerEmitter.
4238
+ *
4239
+ * @param data - Walker contract from walker execution
4240
+ *
4241
+ * @example
4242
+ * ```typescript
4243
+ * const service = new WalkerMarkdownService();
4244
+ * walkerEmitter.subscribe((data) => service.tick(data));
4245
+ * ```
4246
+ */
4247
+ private tick;
4248
+ /**
4249
+ * Gets walker results data from all strategy results.
4250
+ * Delegates to ReportStorage.getData().
4251
+ *
4252
+ * @param walkerName - Walker name to get data for
4253
+ * @param symbol - Trading symbol
4254
+ * @param metric - Metric being optimized
4255
+ * @param context - Context with exchangeName and frameName
4256
+ * @returns Walker results data object with all metrics
4257
+ *
4258
+ * @example
4259
+ * ```typescript
4260
+ * const service = new WalkerMarkdownService();
4261
+ * const results = await service.getData("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" });
4262
+ * console.log(results.bestStrategy, results.bestMetric);
4263
+ * ```
4264
+ */
4265
+ getData: (walkerName: WalkerName, symbol: string, metric: WalkerMetric, context: {
4266
+ exchangeName: string;
4267
+ frameName: string;
4268
+ }) => Promise<IWalkerResults>;
4269
+ /**
4270
+ * Generates markdown report with all strategy results for a walker.
4271
+ * Delegates to ReportStorage.getReport().
4272
+ *
4273
+ * @param walkerName - Walker name to generate report for
4274
+ * @param symbol - Trading symbol
4275
+ * @param metric - Metric being optimized
4276
+ * @param context - Context with exchangeName and frameName
4277
+ * @returns Markdown formatted report string
4278
+ *
4279
+ * @example
4280
+ * ```typescript
4281
+ * const service = new WalkerMarkdownService();
4282
+ * const markdown = await service.getReport("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" });
4283
+ * console.log(markdown);
4284
+ * ```
4285
+ */
4286
+ getReport: (walkerName: WalkerName, symbol: string, metric: WalkerMetric, context: {
4287
+ exchangeName: string;
4288
+ frameName: string;
4289
+ }) => Promise<string>;
4290
+ /**
4291
+ * Saves walker report to disk.
4292
+ * Creates directory if it doesn't exist.
4293
+ * Delegates to ReportStorage.dump().
4294
+ *
4295
+ * @param walkerName - Walker name to save report for
4296
+ * @param symbol - Trading symbol
4297
+ * @param metric - Metric being optimized
4298
+ * @param context - Context with exchangeName and frameName
4299
+ * @param path - Directory path to save report (default: "./dump/walker")
4300
+ *
4301
+ * @example
4302
+ * ```typescript
4303
+ * const service = new WalkerMarkdownService();
4304
+ *
4305
+ * // Save to default path: ./dump/walker/my-walker.md
4306
+ * await service.dump("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" });
4307
+ *
4308
+ * // Save to custom path: ./custom/path/my-walker.md
4309
+ * await service.dump("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" }, "./custom/path");
4310
+ * ```
4311
+ */
4312
+ dump: (walkerName: WalkerName, symbol: string, metric: WalkerMetric, context: {
4313
+ exchangeName: string;
4314
+ frameName: string;
4315
+ }, path?: string) => Promise<void>;
4316
+ /**
4317
+ * Clears accumulated result data from storage.
4318
+ * If walkerName is provided, clears only that walker's data.
4319
+ * If walkerName is omitted, clears all walkers' data.
4320
+ *
4321
+ * @param walkerName - Optional walker name to clear specific walker data
4322
+ *
4323
+ * @example
4324
+ * ```typescript
4325
+ * const service = new WalkerMarkdownService();
4326
+ *
4327
+ * // Clear specific walker data
4328
+ * await service.clear("my-walker");
4329
+ *
4330
+ * // Clear all walkers' data
4331
+ * await service.clear();
4332
+ * ```
4333
+ */
4334
+ clear: (walkerName?: WalkerName) => Promise<void>;
4335
+ /**
4336
+ * Initializes the service by subscribing to walker events.
4337
+ * Uses singleshot to ensure initialization happens only once.
4338
+ * Automatically called on first use.
4339
+ *
4340
+ * @example
4341
+ * ```typescript
4342
+ * const service = new WalkerMarkdownService();
4343
+ * await service.init(); // Subscribe to walker events
4344
+ * ```
4345
+ */
4346
+ protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
4347
+ }
4348
+
4349
+ /**
4350
+ * Unified partial profit/loss event data for report generation.
4351
+ * Contains all information about profit and loss level milestones.
4352
+ */
4353
+ interface PartialEvent {
4354
+ /** Event timestamp in milliseconds */
4355
+ timestamp: number;
4356
+ /** Event action type (profit or loss) */
4357
+ action: "profit" | "loss";
4358
+ /** Trading pair symbol */
4359
+ symbol: string;
4360
+ /** Signal ID */
4361
+ signalId: string;
4362
+ /** Position type */
4363
+ position: string;
4364
+ /** Current market price */
4365
+ currentPrice: number;
4366
+ /** Profit/loss level reached (10, 20, 30, etc) */
4367
+ level: PartialLevel;
4368
+ /** True if backtest mode, false if live mode */
4369
+ backtest: boolean;
4370
+ }
4371
+ /**
4372
+ * Statistical data calculated from partial profit/loss events.
4373
+ *
4374
+ * Provides metrics for partial profit/loss milestone tracking.
4375
+ *
4376
+ * @example
4377
+ * ```typescript
4378
+ * const stats = await Partial.getData("my-strategy");
4379
+ *
4380
+ * console.log(`Total events: ${stats.totalEvents}`);
4381
+ * console.log(`Profit events: ${stats.totalProfit}`);
4382
+ * console.log(`Loss events: ${stats.totalLoss}`);
4383
+ * ```
4384
+ */
4385
+ interface PartialStatistics {
4386
+ /** Array of all profit/loss events with full details */
4387
+ eventList: PartialEvent[];
4388
+ /** Total number of all events (includes profit, loss) */
4389
+ totalEvents: number;
4390
+ /** Total number of profit events */
4391
+ totalProfit: number;
4392
+ /** Total number of loss events */
4393
+ totalLoss: number;
4394
+ }
4395
+ /**
4396
+ * Service for generating and saving partial profit/loss markdown reports.
4397
+ *
4398
+ * Features:
4399
+ * - Listens to partial profit and loss events via partialProfitSubject/partialLossSubject
4400
+ * - Accumulates all events (profit, loss) per symbol
4401
+ * - Generates markdown tables with detailed event information
4402
+ * - Provides statistics (total profit/loss events)
4403
+ * - Saves reports to disk in dump/partial/{symbol}.md
4404
+ *
4405
+ * @example
4406
+ * ```typescript
4407
+ * const service = new PartialMarkdownService();
4408
+ *
4409
+ * // Service automatically subscribes to subjects on init
4410
+ * // No manual callback setup needed
4411
+ *
4412
+ * // Later: generate and save report
4413
+ * await service.dump("BTCUSDT");
4414
+ * ```
4415
+ */
4416
+ declare class PartialMarkdownService {
4417
+ /** Logger service for debug output */
4418
+ private readonly loggerService;
4419
+ /**
4420
+ * Memoized function to get or create ReportStorage for a symbol.
4421
+ * Each symbol gets its own isolated storage instance.
4422
+ */
4423
+ private getStorage;
4424
+ /**
4425
+ * Processes profit events and accumulates them.
4426
+ * Should be called from partialProfitSubject subscription.
4427
+ *
4428
+ * @param data - Profit event data
4429
+ *
4430
+ * @example
4431
+ * ```typescript
4432
+ * const service = new PartialMarkdownService();
4433
+ * // Service automatically subscribes in init()
4434
+ * ```
4435
+ */
4436
+ private tickProfit;
3188
4437
  /**
3189
- * Processes walker progress events and accumulates strategy results.
3190
- * Should be called from walkerEmitter.
4438
+ * Processes loss events and accumulates them.
4439
+ * Should be called from partialLossSubject subscription.
3191
4440
  *
3192
- * @param data - Walker contract from walker execution
4441
+ * @param data - Loss event data
3193
4442
  *
3194
4443
  * @example
3195
4444
  * ```typescript
3196
- * const service = new WalkerMarkdownService();
3197
- * walkerEmitter.subscribe((data) => service.tick(data));
4445
+ * const service = new PartialMarkdownService();
4446
+ * // Service automatically subscribes in init()
3198
4447
  * ```
3199
4448
  */
3200
- private tick;
4449
+ private tickLoss;
3201
4450
  /**
3202
- * Gets walker results data from all strategy results.
4451
+ * Gets statistical data from all partial profit/loss events for a symbol.
3203
4452
  * Delegates to ReportStorage.getData().
3204
4453
  *
3205
- * @param walkerName - Walker name to get data for
3206
- * @param symbol - Trading symbol
3207
- * @param metric - Metric being optimized
3208
- * @param context - Context with exchangeName and frameName
3209
- * @returns Walker results data object with all metrics
4454
+ * @param symbol - Trading pair symbol to get data for
4455
+ * @returns Statistical data object with all metrics
3210
4456
  *
3211
4457
  * @example
3212
4458
  * ```typescript
3213
- * const service = new WalkerMarkdownService();
3214
- * const results = await service.getData("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" });
3215
- * console.log(results.bestStrategy, results.bestMetric);
4459
+ * const service = new PartialMarkdownService();
4460
+ * const stats = await service.getData("BTCUSDT");
4461
+ * console.log(stats.totalProfit, stats.totalLoss);
3216
4462
  * ```
3217
4463
  */
3218
- getData: (walkerName: WalkerName, symbol: string, metric: WalkerMetric, context: {
3219
- exchangeName: string;
3220
- frameName: string;
3221
- }) => Promise<IWalkerResults>;
4464
+ getData: (symbol: string) => Promise<PartialStatistics>;
3222
4465
  /**
3223
- * Generates markdown report with all strategy results for a walker.
4466
+ * Generates markdown report with all partial events for a symbol.
3224
4467
  * Delegates to ReportStorage.getReport().
3225
4468
  *
3226
- * @param walkerName - Walker name to generate report for
3227
- * @param symbol - Trading symbol
3228
- * @param metric - Metric being optimized
3229
- * @param context - Context with exchangeName and frameName
3230
- * @returns Markdown formatted report string
4469
+ * @param symbol - Trading pair symbol to generate report for
4470
+ * @returns Markdown formatted report string with table of all events
3231
4471
  *
3232
4472
  * @example
3233
4473
  * ```typescript
3234
- * const service = new WalkerMarkdownService();
3235
- * const markdown = await service.getReport("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" });
4474
+ * const service = new PartialMarkdownService();
4475
+ * const markdown = await service.getReport("BTCUSDT");
3236
4476
  * console.log(markdown);
3237
4477
  * ```
3238
4478
  */
3239
- getReport: (walkerName: WalkerName, symbol: string, metric: WalkerMetric, context: {
3240
- exchangeName: string;
3241
- frameName: string;
3242
- }) => Promise<string>;
4479
+ getReport: (symbol: string) => Promise<string>;
3243
4480
  /**
3244
- * Saves walker report to disk.
4481
+ * Saves symbol report to disk.
3245
4482
  * Creates directory if it doesn't exist.
3246
4483
  * Delegates to ReportStorage.dump().
3247
4484
  *
3248
- * @param walkerName - Walker name to save report for
3249
- * @param symbol - Trading symbol
3250
- * @param metric - Metric being optimized
3251
- * @param context - Context with exchangeName and frameName
3252
- * @param path - Directory path to save report (default: "./logs/walker")
4485
+ * @param symbol - Trading pair symbol to save report for
4486
+ * @param path - Directory path to save report (default: "./dump/partial")
3253
4487
  *
3254
4488
  * @example
3255
4489
  * ```typescript
3256
- * const service = new WalkerMarkdownService();
4490
+ * const service = new PartialMarkdownService();
3257
4491
  *
3258
- * // Save to default path: ./logs/walker/my-walker.md
3259
- * await service.dump("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" });
4492
+ * // Save to default path: ./dump/partial/BTCUSDT.md
4493
+ * await service.dump("BTCUSDT");
3260
4494
  *
3261
- * // Save to custom path: ./custom/path/my-walker.md
3262
- * await service.dump("my-walker", "BTCUSDT", "sharpeRatio", { exchangeName: "binance", frameName: "1d" }, "./custom/path");
4495
+ * // Save to custom path: ./custom/path/BTCUSDT.md
4496
+ * await service.dump("BTCUSDT", "./custom/path");
3263
4497
  * ```
3264
4498
  */
3265
- dump: (walkerName: WalkerName, symbol: string, metric: WalkerMetric, context: {
3266
- exchangeName: string;
3267
- frameName: string;
3268
- }, path?: string) => Promise<void>;
4499
+ dump: (symbol: string, path?: string) => Promise<void>;
3269
4500
  /**
3270
- * Clears accumulated result data from storage.
3271
- * If walkerName is provided, clears only that walker's data.
3272
- * If walkerName is omitted, clears all walkers' data.
4501
+ * Clears accumulated event data from storage.
4502
+ * If symbol is provided, clears only that symbol's data.
4503
+ * If symbol is omitted, clears all symbols' data.
3273
4504
  *
3274
- * @param walkerName - Optional walker name to clear specific walker data
4505
+ * @param symbol - Optional symbol to clear specific symbol data
3275
4506
  *
3276
4507
  * @example
3277
4508
  * ```typescript
3278
- * const service = new WalkerMarkdownService();
4509
+ * const service = new PartialMarkdownService();
3279
4510
  *
3280
- * // Clear specific walker data
3281
- * await service.clear("my-walker");
4511
+ * // Clear specific symbol data
4512
+ * await service.clear("BTCUSDT");
3282
4513
  *
3283
- * // Clear all walkers' data
4514
+ * // Clear all symbols' data
3284
4515
  * await service.clear();
3285
4516
  * ```
3286
4517
  */
3287
- clear: (walkerName?: WalkerName) => Promise<void>;
4518
+ clear: (symbol?: string) => Promise<void>;
3288
4519
  /**
3289
- * Initializes the service by subscribing to walker events.
4520
+ * Initializes the service by subscribing to partial profit/loss events.
3290
4521
  * Uses singleshot to ensure initialization happens only once.
3291
4522
  * Automatically called on first use.
3292
4523
  *
3293
4524
  * @example
3294
4525
  * ```typescript
3295
- * const service = new WalkerMarkdownService();
3296
- * await service.init(); // Subscribe to walker events
4526
+ * const service = new PartialMarkdownService();
4527
+ * await service.init(); // Subscribe to profit/loss events
3297
4528
  * ```
3298
4529
  */
3299
4530
  protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
@@ -3600,6 +4831,154 @@ declare class PersistRiskUtils {
3600
4831
  * ```
3601
4832
  */
3602
4833
  declare const PersistRiskAdapter: PersistRiskUtils;
4834
+ /**
4835
+ * Type for persisted scheduled signal data.
4836
+ * Contains nullable scheduled signal for atomic updates.
4837
+ */
4838
+ type ScheduleData = IScheduledSignalRow | null;
4839
+ /**
4840
+ * Utility class for managing scheduled signal persistence.
4841
+ *
4842
+ * Features:
4843
+ * - Memoized storage instances per strategy
4844
+ * - Custom adapter support
4845
+ * - Atomic read/write operations for scheduled signals
4846
+ * - Crash-safe scheduled signal state management
4847
+ *
4848
+ * Used by ClientStrategy for live mode persistence of scheduled signals (_scheduledSignal).
4849
+ */
4850
+ declare class PersistScheduleUtils {
4851
+ private PersistScheduleFactory;
4852
+ private getScheduleStorage;
4853
+ /**
4854
+ * Registers a custom persistence adapter.
4855
+ *
4856
+ * @param Ctor - Custom PersistBase constructor
4857
+ *
4858
+ * @example
4859
+ * ```typescript
4860
+ * class RedisPersist extends PersistBase {
4861
+ * async readValue(id) { return JSON.parse(await redis.get(id)); }
4862
+ * async writeValue(id, entity) { await redis.set(id, JSON.stringify(entity)); }
4863
+ * }
4864
+ * PersistScheduleAdapter.usePersistScheduleAdapter(RedisPersist);
4865
+ * ```
4866
+ */
4867
+ usePersistScheduleAdapter(Ctor: TPersistBaseCtor<StrategyName, ScheduleData>): void;
4868
+ /**
4869
+ * Reads persisted scheduled signal data for a strategy and symbol.
4870
+ *
4871
+ * Called by ClientStrategy.waitForInit() to restore scheduled signal state.
4872
+ * Returns null if no scheduled signal exists.
4873
+ *
4874
+ * @param strategyName - Strategy identifier
4875
+ * @param symbol - Trading pair symbol
4876
+ * @returns Promise resolving to scheduled signal or null
4877
+ */
4878
+ readScheduleData: (strategyName: StrategyName, symbol: string) => Promise<IScheduledSignalRow | null>;
4879
+ /**
4880
+ * Writes scheduled signal data to disk with atomic file writes.
4881
+ *
4882
+ * Called by ClientStrategy.setScheduledSignal() to persist state.
4883
+ * Uses atomic writes to prevent corruption on crashes.
4884
+ *
4885
+ * @param scheduledSignalRow - Scheduled signal data (null to clear)
4886
+ * @param strategyName - Strategy identifier
4887
+ * @param symbol - Trading pair symbol
4888
+ * @returns Promise that resolves when write is complete
4889
+ */
4890
+ writeScheduleData: (scheduledSignalRow: IScheduledSignalRow | null, strategyName: StrategyName, symbol: string) => Promise<void>;
4891
+ }
4892
+ /**
4893
+ * Global singleton instance of PersistScheduleUtils.
4894
+ * Used by ClientStrategy for scheduled signal persistence.
4895
+ *
4896
+ * @example
4897
+ * ```typescript
4898
+ * // Custom adapter
4899
+ * PersistScheduleAdapter.usePersistScheduleAdapter(RedisPersist);
4900
+ *
4901
+ * // Read scheduled signal
4902
+ * const scheduled = await PersistScheduleAdapter.readScheduleData("my-strategy", "BTCUSDT");
4903
+ *
4904
+ * // Write scheduled signal
4905
+ * await PersistScheduleAdapter.writeScheduleData(scheduled, "my-strategy", "BTCUSDT");
4906
+ * ```
4907
+ */
4908
+ declare const PersistScheduleAdapter: PersistScheduleUtils;
4909
+ /**
4910
+ * Type for persisted partial data.
4911
+ * Stores profit and loss levels as arrays for JSON serialization.
4912
+ */
4913
+ type PartialData = Record<string, IPartialData>;
4914
+ /**
4915
+ * Utility class for managing partial profit/loss levels persistence.
4916
+ *
4917
+ * Features:
4918
+ * - Memoized storage instances per symbol
4919
+ * - Custom adapter support
4920
+ * - Atomic read/write operations for partial data
4921
+ * - Crash-safe partial state management
4922
+ *
4923
+ * Used by ClientPartial for live mode persistence of profit/loss levels.
4924
+ */
4925
+ declare class PersistPartialUtils {
4926
+ private PersistPartialFactory;
4927
+ private getPartialStorage;
4928
+ /**
4929
+ * Registers a custom persistence adapter.
4930
+ *
4931
+ * @param Ctor - Custom PersistBase constructor
4932
+ *
4933
+ * @example
4934
+ * ```typescript
4935
+ * class RedisPersist extends PersistBase {
4936
+ * async readValue(id) { return JSON.parse(await redis.get(id)); }
4937
+ * async writeValue(id, entity) { await redis.set(id, JSON.stringify(entity)); }
4938
+ * }
4939
+ * PersistPartialAdapter.usePersistPartialAdapter(RedisPersist);
4940
+ * ```
4941
+ */
4942
+ usePersistPartialAdapter(Ctor: TPersistBaseCtor<string, PartialData>): void;
4943
+ /**
4944
+ * Reads persisted partial data for a symbol.
4945
+ *
4946
+ * Called by ClientPartial.waitForInit() to restore state.
4947
+ * Returns empty object if no partial data exists.
4948
+ *
4949
+ * @param symbol - Trading pair symbol
4950
+ * @returns Promise resolving to partial data record
4951
+ */
4952
+ readPartialData: (symbol: string) => Promise<PartialData>;
4953
+ /**
4954
+ * Writes partial data to disk with atomic file writes.
4955
+ *
4956
+ * Called by ClientPartial after profit/loss level changes to persist state.
4957
+ * Uses atomic writes to prevent corruption on crashes.
4958
+ *
4959
+ * @param partialData - Record of signal IDs to partial data
4960
+ * @param symbol - Trading pair symbol
4961
+ * @returns Promise that resolves when write is complete
4962
+ */
4963
+ writePartialData: (partialData: PartialData, symbol: string) => Promise<void>;
4964
+ }
4965
+ /**
4966
+ * Global singleton instance of PersistPartialUtils.
4967
+ * Used by ClientPartial for partial profit/loss levels persistence.
4968
+ *
4969
+ * @example
4970
+ * ```typescript
4971
+ * // Custom adapter
4972
+ * PersistPartialAdapter.usePersistPartialAdapter(RedisPersist);
4973
+ *
4974
+ * // Read partial data
4975
+ * const partialData = await PersistPartialAdapter.readPartialData("BTCUSDT");
4976
+ *
4977
+ * // Write partial data
4978
+ * await PersistPartialAdapter.writePartialData(partialData, "BTCUSDT");
4979
+ * ```
4980
+ */
4981
+ declare const PersistPartialAdapter: PersistPartialUtils;
3603
4982
 
3604
4983
  /**
3605
4984
  * Utility class for backtest operations.
@@ -3689,11 +5068,11 @@ declare class BacktestUtils {
3689
5068
  * Saves strategy report to disk.
3690
5069
  *
3691
5070
  * @param strategyName - Strategy name to save report for
3692
- * @param path - Optional directory path to save report (default: "./logs/backtest")
5071
+ * @param path - Optional directory path to save report (default: "./dump/backtest")
3693
5072
  *
3694
5073
  * @example
3695
5074
  * ```typescript
3696
- * // Save to default path: ./logs/backtest/my-strategy.md
5075
+ * // Save to default path: ./dump/backtest/my-strategy.md
3697
5076
  * await Backtest.dump("my-strategy");
3698
5077
  *
3699
5078
  * // Save to custom path: ./custom/path/my-strategy.md
@@ -3821,11 +5200,11 @@ declare class LiveUtils {
3821
5200
  * Saves strategy report to disk.
3822
5201
  *
3823
5202
  * @param strategyName - Strategy name to save report for
3824
- * @param path - Optional directory path to save report (default: "./logs/live")
5203
+ * @param path - Optional directory path to save report (default: "./dump/live")
3825
5204
  *
3826
5205
  * @example
3827
5206
  * ```typescript
3828
- * // Save to default path: ./logs/live/my-strategy.md
5207
+ * // Save to default path: ./dump/live/my-strategy.md
3829
5208
  * await Live.dump("my-strategy");
3830
5209
  *
3831
5210
  * // Save to custom path: ./custom/path/my-strategy.md
@@ -3907,11 +5286,11 @@ declare class ScheduleUtils {
3907
5286
  * Saves strategy report to disk.
3908
5287
  *
3909
5288
  * @param strategyName - Strategy name to save report for
3910
- * @param path - Optional directory path to save report (default: "./logs/schedule")
5289
+ * @param path - Optional directory path to save report (default: "./dump/schedule")
3911
5290
  *
3912
5291
  * @example
3913
5292
  * ```typescript
3914
- * // Save to default path: ./logs/schedule/my-strategy.md
5293
+ * // Save to default path: ./dump/schedule/my-strategy.md
3915
5294
  * await Schedule.dump("my-strategy");
3916
5295
  *
3917
5296
  * // Save to custom path: ./custom/path/my-strategy.md
@@ -3919,23 +5298,6 @@ declare class ScheduleUtils {
3919
5298
  * ```
3920
5299
  */
3921
5300
  dump: (strategyName: StrategyName, path?: string) => Promise<void>;
3922
- /**
3923
- * Clears accumulated scheduled signal data from storage.
3924
- * If strategyName is provided, clears only that strategy's data.
3925
- * If strategyName is omitted, clears all strategies' data.
3926
- *
3927
- * @param strategyName - Optional strategy name to clear specific strategy data
3928
- *
3929
- * @example
3930
- * ```typescript
3931
- * // Clear specific strategy data
3932
- * await Schedule.clear("my-strategy");
3933
- *
3934
- * // Clear all strategies' data
3935
- * await Schedule.clear();
3936
- * ```
3937
- */
3938
- clear: (strategyName?: StrategyName) => Promise<void>;
3939
5301
  }
3940
5302
  /**
3941
5303
  * Singleton instance of ScheduleUtils for convenient scheduled signals reporting.
@@ -4037,14 +5399,14 @@ declare class Performance {
4037
5399
  * Saves performance report to disk.
4038
5400
  *
4039
5401
  * Creates directory if it doesn't exist.
4040
- * Default path: ./logs/performance/{strategyName}.md
5402
+ * Default path: ./dump/performance/{strategyName}.md
4041
5403
  *
4042
5404
  * @param strategyName - Strategy name to save report for
4043
5405
  * @param path - Optional custom directory path
4044
5406
  *
4045
5407
  * @example
4046
5408
  * ```typescript
4047
- * // Save to default path: ./logs/performance/my-strategy.md
5409
+ * // Save to default path: ./dump/performance/my-strategy.md
4048
5410
  * await Performance.dump("my-strategy");
4049
5411
  *
4050
5412
  * // Save to custom path: ./reports/perf/my-strategy.md
@@ -4154,11 +5516,11 @@ declare class WalkerUtils {
4154
5516
  *
4155
5517
  * @param symbol - Trading symbol
4156
5518
  * @param walkerName - Walker name to save report for
4157
- * @param path - Optional directory path to save report (default: "./logs/walker")
5519
+ * @param path - Optional directory path to save report (default: "./dump/walker")
4158
5520
  *
4159
5521
  * @example
4160
5522
  * ```typescript
4161
- * // Save to default path: ./logs/walker/my-walker.md
5523
+ * // Save to default path: ./dump/walker/my-walker.md
4162
5524
  * await Walker.dump("BTCUSDT", "my-walker");
4163
5525
  *
4164
5526
  * // Save to custom path: ./custom/path/my-walker.md
@@ -4265,11 +5627,11 @@ declare class HeatUtils {
4265
5627
  * Default filename: {strategyName}.md
4266
5628
  *
4267
5629
  * @param strategyName - Strategy name to save heatmap report for
4268
- * @param path - Optional directory path to save report (default: "./logs/heatmap")
5630
+ * @param path - Optional directory path to save report (default: "./dump/heatmap")
4269
5631
  *
4270
5632
  * @example
4271
5633
  * ```typescript
4272
- * // Save to default path: ./logs/heatmap/my-strategy.md
5634
+ * // Save to default path: ./dump/heatmap/my-strategy.md
4273
5635
  * await Heat.dump("my-strategy");
4274
5636
  *
4275
5637
  * // Save to custom path: ./reports/my-strategy.md
@@ -4371,25 +5733,247 @@ declare class PositionSizeUtils {
4371
5733
  * @returns Promise resolving to calculated position size
4372
5734
  * @throws Error if sizing schema method is not "kelly-criterion"
4373
5735
  */
4374
- static kellyCriterion: (symbol: string, accountBalance: number, priceOpen: number, winRate: number, winLossRatio: number, context: {
4375
- sizingName: SizingName;
4376
- }) => Promise<number>;
5736
+ static kellyCriterion: (symbol: string, accountBalance: number, priceOpen: number, winRate: number, winLossRatio: number, context: {
5737
+ sizingName: SizingName;
5738
+ }) => Promise<number>;
5739
+ /**
5740
+ * Calculates position size using ATR-based method.
5741
+ *
5742
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
5743
+ * @param accountBalance - Current account balance
5744
+ * @param priceOpen - Planned entry price
5745
+ * @param atr - Current ATR value
5746
+ * @param context - Execution context with sizing name
5747
+ * @returns Promise resolving to calculated position size
5748
+ * @throws Error if sizing schema method is not "atr-based"
5749
+ */
5750
+ static atrBased: (symbol: string, accountBalance: number, priceOpen: number, atr: number, context: {
5751
+ sizingName: SizingName;
5752
+ }) => Promise<number>;
5753
+ }
5754
+ declare const PositionSize: typeof PositionSizeUtils;
5755
+
5756
+ /**
5757
+ * Public API utilities for optimizer operations.
5758
+ * Provides high-level methods for strategy generation and code export.
5759
+ *
5760
+ * Usage:
5761
+ * ```typescript
5762
+ * import { Optimizer } from "backtest-kit";
5763
+ *
5764
+ * // Get strategy data
5765
+ * const strategies = await Optimizer.getData("BTCUSDT", {
5766
+ * optimizerName: "my-optimizer"
5767
+ * });
5768
+ *
5769
+ * // Generate code
5770
+ * const code = await Optimizer.getCode("BTCUSDT", {
5771
+ * optimizerName: "my-optimizer"
5772
+ * });
5773
+ *
5774
+ * // Save to file
5775
+ * await Optimizer.dump("BTCUSDT", {
5776
+ * optimizerName: "my-optimizer"
5777
+ * }, "./output");
5778
+ * ```
5779
+ */
5780
+ declare class OptimizerUtils {
5781
+ /**
5782
+ * Fetches data from all sources and generates strategy metadata.
5783
+ * Processes each training range and builds LLM conversation history.
5784
+ *
5785
+ * @param symbol - Trading pair symbol
5786
+ * @param context - Context with optimizerName
5787
+ * @returns Array of generated strategies with conversation context
5788
+ * @throws Error if optimizer not found
5789
+ */
5790
+ getData: (symbol: string, context: {
5791
+ optimizerName: OptimizerName;
5792
+ }) => Promise<IOptimizerStrategy[]>;
5793
+ /**
5794
+ * Generates complete executable strategy code.
5795
+ * Includes imports, helpers, strategies, walker, and launcher.
5796
+ *
5797
+ * @param symbol - Trading pair symbol
5798
+ * @param context - Context with optimizerName
5799
+ * @returns Generated TypeScript/JavaScript code as string
5800
+ * @throws Error if optimizer not found
5801
+ */
5802
+ getCode: (symbol: string, context: {
5803
+ optimizerName: OptimizerName;
5804
+ }) => Promise<string>;
5805
+ /**
5806
+ * Generates and saves strategy code to file.
5807
+ * Creates directory if needed, writes .mjs file.
5808
+ *
5809
+ * Format: `{optimizerName}_{symbol}.mjs`
5810
+ *
5811
+ * @param symbol - Trading pair symbol
5812
+ * @param context - Context with optimizerName
5813
+ * @param path - Output directory path (default: "./")
5814
+ * @throws Error if optimizer not found or file write fails
5815
+ */
5816
+ dump: (symbol: string, context: {
5817
+ optimizerName: string;
5818
+ }, path?: string) => Promise<void>;
5819
+ }
5820
+ /**
5821
+ * Singleton instance of OptimizerUtils.
5822
+ * Public API for optimizer operations.
5823
+ *
5824
+ * @example
5825
+ * ```typescript
5826
+ * import { Optimizer } from "backtest-kit";
5827
+ *
5828
+ * await Optimizer.dump("BTCUSDT", { optimizerName: "my-optimizer" });
5829
+ * ```
5830
+ */
5831
+ declare const Optimizer: OptimizerUtils;
5832
+
5833
+ /**
5834
+ * Utility class for accessing partial profit/loss reports and statistics.
5835
+ *
5836
+ * Provides static-like methods (via singleton instance) to retrieve data
5837
+ * accumulated by PartialMarkdownService from partial profit/loss events.
5838
+ *
5839
+ * Features:
5840
+ * - Statistical data extraction (total profit/loss events count)
5841
+ * - Markdown report generation with event tables
5842
+ * - File export to disk
5843
+ *
5844
+ * Data source:
5845
+ * - PartialMarkdownService listens to partialProfitSubject/partialLossSubject
5846
+ * - Accumulates events in ReportStorage (max 250 events per symbol)
5847
+ * - Events include: timestamp, action, symbol, signalId, position, level, price, mode
5848
+ *
5849
+ * @example
5850
+ * ```typescript
5851
+ * import { Partial } from "./classes/Partial";
5852
+ *
5853
+ * // Get statistical data for BTCUSDT
5854
+ * const stats = await Partial.getData("BTCUSDT");
5855
+ * console.log(`Total events: ${stats.totalEvents}`);
5856
+ * console.log(`Profit events: ${stats.totalProfit}`);
5857
+ * console.log(`Loss events: ${stats.totalLoss}`);
5858
+ *
5859
+ * // Generate markdown report
5860
+ * const markdown = await Partial.getReport("BTCUSDT");
5861
+ * console.log(markdown); // Formatted table with all events
5862
+ *
5863
+ * // Export report to file
5864
+ * await Partial.dump("BTCUSDT"); // Saves to ./dump/partial/BTCUSDT.md
5865
+ * await Partial.dump("BTCUSDT", "./custom/path"); // Custom directory
5866
+ * ```
5867
+ */
5868
+ declare class PartialUtils {
5869
+ /**
5870
+ * Retrieves statistical data from accumulated partial profit/loss events.
5871
+ *
5872
+ * Delegates to PartialMarkdownService.getData() which reads from ReportStorage.
5873
+ * Returns aggregated metrics calculated from all profit and loss events.
5874
+ *
5875
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
5876
+ * @returns Promise resolving to PartialStatistics object with counts and event list
5877
+ *
5878
+ * @example
5879
+ * ```typescript
5880
+ * const stats = await Partial.getData("BTCUSDT");
5881
+ *
5882
+ * console.log(`Total events: ${stats.totalEvents}`);
5883
+ * console.log(`Profit events: ${stats.totalProfit} (${(stats.totalProfit / stats.totalEvents * 100).toFixed(1)}%)`);
5884
+ * console.log(`Loss events: ${stats.totalLoss} (${(stats.totalLoss / stats.totalEvents * 100).toFixed(1)}%)`);
5885
+ *
5886
+ * // Iterate through all events
5887
+ * for (const event of stats.eventList) {
5888
+ * console.log(`${event.action.toUpperCase()}: Signal ${event.signalId} reached ${event.level}%`);
5889
+ * }
5890
+ * ```
5891
+ */
5892
+ getData: (symbol: string) => Promise<PartialStatistics>;
5893
+ /**
5894
+ * Generates markdown report with all partial profit/loss events for a symbol.
5895
+ *
5896
+ * Creates formatted table containing:
5897
+ * - Action (PROFIT/LOSS)
5898
+ * - Symbol
5899
+ * - Signal ID
5900
+ * - Position (LONG/SHORT)
5901
+ * - Level % (+10%, -20%, etc)
5902
+ * - Current Price
5903
+ * - Timestamp (ISO 8601)
5904
+ * - Mode (Backtest/Live)
5905
+ *
5906
+ * Also includes summary statistics at the end.
5907
+ *
5908
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
5909
+ * @returns Promise resolving to markdown formatted report string
5910
+ *
5911
+ * @example
5912
+ * ```typescript
5913
+ * const markdown = await Partial.getReport("BTCUSDT");
5914
+ * console.log(markdown);
5915
+ *
5916
+ * // Output:
5917
+ * // # Partial Profit/Loss Report: BTCUSDT
5918
+ * //
5919
+ * // | Action | Symbol | Signal ID | Position | Level % | Current Price | Timestamp | Mode |
5920
+ * // | --- | --- | --- | --- | --- | --- | --- | --- |
5921
+ * // | PROFIT | BTCUSDT | abc123 | LONG | +10% | 51500.00000000 USD | 2024-01-15T10:30:00.000Z | Backtest |
5922
+ * // | LOSS | BTCUSDT | abc123 | LONG | -10% | 49000.00000000 USD | 2024-01-15T11:00:00.000Z | Backtest |
5923
+ * //
5924
+ * // **Total events:** 2
5925
+ * // **Profit events:** 1
5926
+ * // **Loss events:** 1
5927
+ * ```
5928
+ */
5929
+ getReport: (symbol: string) => Promise<string>;
4377
5930
  /**
4378
- * Calculates position size using ATR-based method.
5931
+ * Generates and saves markdown report to file.
5932
+ *
5933
+ * Creates directory if it doesn't exist.
5934
+ * Filename format: {symbol}.md (e.g., "BTCUSDT.md")
5935
+ *
5936
+ * Delegates to PartialMarkdownService.dump() which:
5937
+ * 1. Generates markdown report via getReport()
5938
+ * 2. Creates output directory (recursive mkdir)
5939
+ * 3. Writes file with UTF-8 encoding
5940
+ * 4. Logs success/failure to console
4379
5941
  *
4380
5942
  * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
4381
- * @param accountBalance - Current account balance
4382
- * @param priceOpen - Planned entry price
4383
- * @param atr - Current ATR value
4384
- * @param context - Execution context with sizing name
4385
- * @returns Promise resolving to calculated position size
4386
- * @throws Error if sizing schema method is not "atr-based"
5943
+ * @param path - Output directory path (default: "./dump/partial")
5944
+ * @returns Promise that resolves when file is written
5945
+ *
5946
+ * @example
5947
+ * ```typescript
5948
+ * // Save to default path: ./dump/partial/BTCUSDT.md
5949
+ * await Partial.dump("BTCUSDT");
5950
+ *
5951
+ * // Save to custom path: ./reports/partial/BTCUSDT.md
5952
+ * await Partial.dump("BTCUSDT", "./reports/partial");
5953
+ *
5954
+ * // After multiple symbols backtested, export all reports
5955
+ * for (const symbol of ["BTCUSDT", "ETHUSDT", "BNBUSDT"]) {
5956
+ * await Partial.dump(symbol, "./backtest-results");
5957
+ * }
5958
+ * ```
4387
5959
  */
4388
- static atrBased: (symbol: string, accountBalance: number, priceOpen: number, atr: number, context: {
4389
- sizingName: SizingName;
4390
- }) => Promise<number>;
5960
+ dump: (symbol: string, path?: string) => Promise<void>;
4391
5961
  }
4392
- declare const PositionSize: typeof PositionSizeUtils;
5962
+ /**
5963
+ * Global singleton instance of PartialUtils.
5964
+ * Provides static-like access to partial profit/loss reporting methods.
5965
+ *
5966
+ * @example
5967
+ * ```typescript
5968
+ * import { Partial } from "backtest-kit";
5969
+ *
5970
+ * // Usage same as PartialUtils methods
5971
+ * const stats = await Partial.getData("BTCUSDT");
5972
+ * const report = await Partial.getReport("BTCUSDT");
5973
+ * await Partial.dump("BTCUSDT");
5974
+ * ```
5975
+ */
5976
+ declare const Partial$1: PartialUtils;
4393
5977
 
4394
5978
  /**
4395
5979
  * Global signal emitter for all trading events (live + backtest).
@@ -4430,7 +6014,12 @@ declare const doneWalkerSubject: Subject<DoneContract>;
4430
6014
  * Progress emitter for backtest execution progress.
4431
6015
  * Emits progress updates during backtest execution.
4432
6016
  */
4433
- declare const progressEmitter: Subject<ProgressContract>;
6017
+ declare const progressBacktestEmitter: Subject<ProgressBacktestContract>;
6018
+ /**
6019
+ * Progress emitter for walker execution progress.
6020
+ * Emits progress updates during walker execution.
6021
+ */
6022
+ declare const progressWalkerEmitter: Subject<ProgressWalkerContract>;
4434
6023
  /**
4435
6024
  * Performance emitter for execution metrics.
4436
6025
  * Emits performance metrics for profiling and bottleneck detection.
@@ -4456,13 +6045,26 @@ declare const walkerStopSubject: Subject<string>;
4456
6045
  * Emits when risk validation functions throw errors during signal checking.
4457
6046
  */
4458
6047
  declare const validationSubject: Subject<Error>;
6048
+ /**
6049
+ * Partial profit emitter for profit level milestones.
6050
+ * Emits when a signal reaches a profit level (10%, 20%, 30%, etc).
6051
+ */
6052
+ declare const partialProfitSubject: Subject<PartialProfitContract>;
6053
+ /**
6054
+ * Partial loss emitter for loss level milestones.
6055
+ * Emits when a signal reaches a loss level (10%, 20%, 30%, etc).
6056
+ */
6057
+ declare const partialLossSubject: Subject<PartialLossContract>;
4459
6058
 
4460
6059
  declare const emitters_doneBacktestSubject: typeof doneBacktestSubject;
4461
6060
  declare const emitters_doneLiveSubject: typeof doneLiveSubject;
4462
6061
  declare const emitters_doneWalkerSubject: typeof doneWalkerSubject;
4463
6062
  declare const emitters_errorEmitter: typeof errorEmitter;
6063
+ declare const emitters_partialLossSubject: typeof partialLossSubject;
6064
+ declare const emitters_partialProfitSubject: typeof partialProfitSubject;
4464
6065
  declare const emitters_performanceEmitter: typeof performanceEmitter;
4465
- declare const emitters_progressEmitter: typeof progressEmitter;
6066
+ declare const emitters_progressBacktestEmitter: typeof progressBacktestEmitter;
6067
+ declare const emitters_progressWalkerEmitter: typeof progressWalkerEmitter;
4466
6068
  declare const emitters_signalBacktestEmitter: typeof signalBacktestEmitter;
4467
6069
  declare const emitters_signalEmitter: typeof signalEmitter;
4468
6070
  declare const emitters_signalLiveEmitter: typeof signalLiveEmitter;
@@ -4471,7 +6073,7 @@ declare const emitters_walkerCompleteSubject: typeof walkerCompleteSubject;
4471
6073
  declare const emitters_walkerEmitter: typeof walkerEmitter;
4472
6074
  declare const emitters_walkerStopSubject: typeof walkerStopSubject;
4473
6075
  declare namespace emitters {
4474
- export { emitters_doneBacktestSubject as doneBacktestSubject, emitters_doneLiveSubject as doneLiveSubject, emitters_doneWalkerSubject as doneWalkerSubject, emitters_errorEmitter as errorEmitter, emitters_performanceEmitter as performanceEmitter, emitters_progressEmitter as progressEmitter, emitters_signalBacktestEmitter as signalBacktestEmitter, emitters_signalEmitter as signalEmitter, emitters_signalLiveEmitter as signalLiveEmitter, emitters_validationSubject as validationSubject, emitters_walkerCompleteSubject as walkerCompleteSubject, emitters_walkerEmitter as walkerEmitter, emitters_walkerStopSubject as walkerStopSubject };
6076
+ export { emitters_doneBacktestSubject as doneBacktestSubject, emitters_doneLiveSubject as doneLiveSubject, emitters_doneWalkerSubject as doneWalkerSubject, emitters_errorEmitter as errorEmitter, emitters_partialLossSubject as partialLossSubject, emitters_partialProfitSubject as partialProfitSubject, emitters_performanceEmitter as performanceEmitter, emitters_progressBacktestEmitter as progressBacktestEmitter, emitters_progressWalkerEmitter as progressWalkerEmitter, emitters_signalBacktestEmitter as signalBacktestEmitter, emitters_signalEmitter as signalEmitter, emitters_signalLiveEmitter as signalLiveEmitter, emitters_validationSubject as validationSubject, emitters_walkerCompleteSubject as walkerCompleteSubject, emitters_walkerEmitter as walkerEmitter, emitters_walkerStopSubject as walkerStopSubject };
4475
6077
  }
4476
6078
 
4477
6079
  /**
@@ -4723,6 +6325,7 @@ declare class StrategyConnectionService implements IStrategy {
4723
6325
  private readonly riskConnectionService;
4724
6326
  private readonly exchangeConnectionService;
4725
6327
  private readonly methodContextService;
6328
+ private readonly partialConnectionService;
4726
6329
  /**
4727
6330
  * Retrieves memoized ClientStrategy instance for given strategy name.
4728
6331
  *
@@ -6078,13 +7681,13 @@ declare class HeatMarkdownService {
6078
7681
  * Default filename: {strategyName}.md
6079
7682
  *
6080
7683
  * @param strategyName - Strategy name to save heatmap report for
6081
- * @param path - Optional directory path to save report (default: "./logs/heatmap")
7684
+ * @param path - Optional directory path to save report (default: "./dump/heatmap")
6082
7685
  *
6083
7686
  * @example
6084
7687
  * ```typescript
6085
7688
  * const service = new HeatMarkdownService();
6086
7689
  *
6087
- * // Save to default path: ./logs/heatmap/my-strategy.md
7690
+ * // Save to default path: ./dump/heatmap/my-strategy.md
6088
7691
  * await service.dump("my-strategy");
6089
7692
  *
6090
7693
  * // Save to custom path: ./reports/my-strategy.md
@@ -6355,19 +7958,549 @@ declare class RiskValidationService {
6355
7958
  list: () => Promise<IRiskSchema[]>;
6356
7959
  }
6357
7960
 
7961
+ /**
7962
+ * Default template service for generating optimizer code snippets.
7963
+ * Implements all IOptimizerTemplate methods with Ollama LLM integration.
7964
+ *
7965
+ * Features:
7966
+ * - Multi-timeframe analysis (1m, 5m, 15m, 1h)
7967
+ * - JSON structured output for signals
7968
+ * - Debug logging to ./dump/strategy
7969
+ * - CCXT exchange integration
7970
+ * - Walker-based strategy comparison
7971
+ *
7972
+ * Can be partially overridden in optimizer schema configuration.
7973
+ */
7974
+ declare class OptimizerTemplateService implements IOptimizerTemplate {
7975
+ private readonly loggerService;
7976
+ /**
7977
+ * Generates the top banner with imports and constants.
7978
+ *
7979
+ * @param symbol - Trading pair symbol
7980
+ * @returns Shebang, imports, and WARN_KB constant
7981
+ */
7982
+ getTopBanner: (symbol: string) => Promise<string>;
7983
+ /**
7984
+ * Generates default user message for LLM conversation.
7985
+ * Simple prompt to read and acknowledge data.
7986
+ *
7987
+ * @param symbol - Trading pair symbol
7988
+ * @param data - Fetched data array
7989
+ * @param name - Source name
7990
+ * @returns User message with JSON data
7991
+ */
7992
+ getUserMessage: (symbol: string, data: IOptimizerData[], name: string) => Promise<string>;
7993
+ /**
7994
+ * Generates default assistant message for LLM conversation.
7995
+ * Simple acknowledgment response.
7996
+ *
7997
+ * @param symbol - Trading pair symbol
7998
+ * @param data - Fetched data array
7999
+ * @param name - Source name
8000
+ * @returns Assistant acknowledgment message
8001
+ */
8002
+ getAssistantMessage: (symbol: string, data: IOptimizerData[], name: string) => Promise<string>;
8003
+ /**
8004
+ * Generates Walker configuration code.
8005
+ * Compares multiple strategies on test frame.
8006
+ *
8007
+ * @param walkerName - Unique walker identifier
8008
+ * @param exchangeName - Exchange to use for backtesting
8009
+ * @param frameName - Test frame name
8010
+ * @param strategies - Array of strategy names to compare
8011
+ * @returns Generated addWalker() call
8012
+ */
8013
+ getWalkerTemplate: (walkerName: string, exchangeName: string, frameName: string, strategies: string[]) => Promise<string>;
8014
+ /**
8015
+ * Generates Strategy configuration with LLM integration.
8016
+ * Includes multi-timeframe analysis and signal generation.
8017
+ *
8018
+ * @param strategyName - Unique strategy identifier
8019
+ * @param interval - Signal throttling interval (e.g., "5m")
8020
+ * @param prompt - Strategy logic from getPrompt()
8021
+ * @returns Generated addStrategy() call with getSignal() function
8022
+ */
8023
+ getStrategyTemplate: (strategyName: string, interval: string, prompt: string) => Promise<string>;
8024
+ /**
8025
+ * Generates Exchange configuration code.
8026
+ * Uses CCXT Binance with standard formatters.
8027
+ *
8028
+ * @param symbol - Trading pair symbol (unused, for consistency)
8029
+ * @param exchangeName - Unique exchange identifier
8030
+ * @returns Generated addExchange() call with CCXT integration
8031
+ */
8032
+ getExchangeTemplate: (symbol: string, exchangeName: ExchangeName) => Promise<string>;
8033
+ /**
8034
+ * Generates Frame (timeframe) configuration code.
8035
+ *
8036
+ * @param symbol - Trading pair symbol (unused, for consistency)
8037
+ * @param frameName - Unique frame identifier
8038
+ * @param interval - Candle interval (e.g., "1m")
8039
+ * @param startDate - Frame start date
8040
+ * @param endDate - Frame end date
8041
+ * @returns Generated addFrame() call
8042
+ */
8043
+ getFrameTemplate: (symbol: string, frameName: string, interval: CandleInterval, startDate: Date, endDate: Date) => Promise<string>;
8044
+ /**
8045
+ * Generates launcher code to run Walker with event listeners.
8046
+ * Includes progress tracking and completion handlers.
8047
+ *
8048
+ * @param symbol - Trading pair symbol
8049
+ * @param walkerName - Walker name to launch
8050
+ * @returns Generated Walker.background() call with listeners
8051
+ */
8052
+ getLauncherTemplate: (symbol: string, walkerName: string) => Promise<string>;
8053
+ /**
8054
+ * Generates dumpJson() helper function for debug output.
8055
+ * Saves LLM conversations and results to ./dump/strategy/{resultId}/
8056
+ *
8057
+ * @param symbol - Trading pair symbol (unused, for consistency)
8058
+ * @returns Generated async dumpJson() function
8059
+ */
8060
+ getJsonDumpTemplate: (symbol: string) => Promise<string>;
8061
+ /**
8062
+ * Generates text() helper for LLM text generation.
8063
+ * Uses Ollama gpt-oss:20b model for market analysis.
8064
+ *
8065
+ * @param symbol - Trading pair symbol (used in prompt)
8066
+ * @returns Generated async text() function
8067
+ */
8068
+ getTextTemplate: (symbol: string) => Promise<string>;
8069
+ /**
8070
+ * Generates json() helper for structured LLM output.
8071
+ * Uses Ollama with JSON schema for trading signals.
8072
+ *
8073
+ * Signal schema:
8074
+ * - position: "wait" | "long" | "short"
8075
+ * - note: strategy explanation
8076
+ * - priceOpen: entry price
8077
+ * - priceTakeProfit: target price
8078
+ * - priceStopLoss: stop price
8079
+ * - minuteEstimatedTime: expected duration (max 360 min)
8080
+ *
8081
+ * @param symbol - Trading pair symbol (unused, for consistency)
8082
+ * @returns Generated async json() function with signal schema
8083
+ */
8084
+ getJsonTemplate: (symbol: string) => Promise<string>;
8085
+ }
8086
+
8087
+ /**
8088
+ * Service for managing optimizer schema registration and retrieval.
8089
+ * Provides validation and registry management for optimizer configurations.
8090
+ *
8091
+ * Uses ToolRegistry for immutable schema storage.
8092
+ */
8093
+ declare class OptimizerSchemaService {
8094
+ readonly loggerService: LoggerService;
8095
+ private _registry;
8096
+ /**
8097
+ * Registers a new optimizer schema.
8098
+ * Validates required fields before registration.
8099
+ *
8100
+ * @param key - Unique optimizer name
8101
+ * @param value - Optimizer schema configuration
8102
+ * @throws Error if schema validation fails
8103
+ */
8104
+ register: (key: OptimizerName, value: IOptimizerSchema) => void;
8105
+ /**
8106
+ * Validates optimizer schema structure.
8107
+ * Checks required fields: optimizerName, rangeTrain, source, getPrompt.
8108
+ *
8109
+ * @param optimizerSchema - Schema to validate
8110
+ * @throws Error if validation fails
8111
+ */
8112
+ private validateShallow;
8113
+ /**
8114
+ * Partially overrides an existing optimizer schema.
8115
+ * Merges provided values with existing schema.
8116
+ *
8117
+ * @param key - Optimizer name to override
8118
+ * @param value - Partial schema values to merge
8119
+ * @returns Updated complete schema
8120
+ * @throws Error if optimizer not found
8121
+ */
8122
+ override: (key: OptimizerName, value: Partial<IOptimizerSchema>) => IOptimizerSchema;
8123
+ /**
8124
+ * Retrieves optimizer schema by name.
8125
+ *
8126
+ * @param key - Optimizer name
8127
+ * @returns Complete optimizer schema
8128
+ * @throws Error if optimizer not found
8129
+ */
8130
+ get: (key: OptimizerName) => IOptimizerSchema;
8131
+ }
8132
+
8133
+ /**
8134
+ * Service for validating optimizer existence and managing optimizer registry.
8135
+ * Maintains a Map of registered optimizers for validation purposes.
8136
+ *
8137
+ * Uses memoization for efficient repeated validation checks.
8138
+ */
8139
+ declare class OptimizerValidationService {
8140
+ private readonly loggerService;
8141
+ private _optimizerMap;
8142
+ /**
8143
+ * Adds optimizer to validation registry.
8144
+ * Prevents duplicate optimizer names.
8145
+ *
8146
+ * @param optimizerName - Unique optimizer identifier
8147
+ * @param optimizerSchema - Complete optimizer schema
8148
+ * @throws Error if optimizer with same name already exists
8149
+ */
8150
+ addOptimizer: (optimizerName: OptimizerName, optimizerSchema: IOptimizerSchema) => void;
8151
+ /**
8152
+ * Validates that optimizer exists in registry.
8153
+ * Memoized for performance on repeated checks.
8154
+ *
8155
+ * @param optimizerName - Optimizer name to validate
8156
+ * @param source - Source method name for error messages
8157
+ * @throws Error if optimizer not found
8158
+ */
8159
+ validate: (optimizerName: OptimizerName, source: string) => void;
8160
+ /**
8161
+ * Lists all registered optimizer schemas.
8162
+ *
8163
+ * @returns Array of all optimizer schemas
8164
+ */
8165
+ list: () => Promise<IOptimizerSchema[]>;
8166
+ }
8167
+
8168
+ /**
8169
+ * Client implementation for optimizer operations.
8170
+ *
8171
+ * Features:
8172
+ * - Data collection from multiple sources with pagination
8173
+ * - LLM conversation history building
8174
+ * - Strategy code generation with templates
8175
+ * - File export with callbacks
8176
+ *
8177
+ * Used by OptimizerConnectionService to create optimizer instances.
8178
+ */
8179
+ declare class ClientOptimizer implements IOptimizer {
8180
+ readonly params: IOptimizerParams;
8181
+ constructor(params: IOptimizerParams);
8182
+ /**
8183
+ * Fetches data from all sources and generates strategy metadata.
8184
+ * Processes each training range and builds LLM conversation history.
8185
+ *
8186
+ * @param symbol - Trading pair symbol
8187
+ * @returns Array of generated strategies with conversation context
8188
+ */
8189
+ getData: (symbol: string) => Promise<IOptimizerStrategy[]>;
8190
+ /**
8191
+ * Generates complete executable strategy code.
8192
+ * Includes imports, helpers, strategies, walker, and launcher.
8193
+ *
8194
+ * @param symbol - Trading pair symbol
8195
+ * @returns Generated TypeScript/JavaScript code as string
8196
+ */
8197
+ getCode: (symbol: string) => Promise<string>;
8198
+ /**
8199
+ * Generates and saves strategy code to file.
8200
+ * Creates directory if needed, writes .mjs file.
8201
+ *
8202
+ * @param symbol - Trading pair symbol
8203
+ * @param path - Output directory path (default: "./")
8204
+ */
8205
+ dump: (symbol: string, path?: string) => Promise<void>;
8206
+ }
8207
+
8208
+ /**
8209
+ * Type helper for optimizer method signatures.
8210
+ * Maps IOptimizer interface methods to any return type.
8211
+ */
8212
+ type TOptimizer = {
8213
+ [key in keyof IOptimizer]: any;
8214
+ };
8215
+ /**
8216
+ * Service for creating and caching optimizer client instances.
8217
+ * Handles dependency injection and template merging.
8218
+ *
8219
+ * Features:
8220
+ * - Memoized optimizer instances (one per optimizerName)
8221
+ * - Template merging (custom + defaults)
8222
+ * - Logger injection
8223
+ * - Delegates to ClientOptimizer for actual operations
8224
+ */
8225
+ declare class OptimizerConnectionService implements TOptimizer {
8226
+ private readonly loggerService;
8227
+ private readonly optimizerSchemaService;
8228
+ private readonly optimizerTemplateService;
8229
+ /**
8230
+ * Creates or retrieves cached optimizer instance.
8231
+ * Memoized by optimizerName for performance.
8232
+ *
8233
+ * Merges custom templates from schema with defaults from OptimizerTemplateService.
8234
+ *
8235
+ * @param optimizerName - Unique optimizer identifier
8236
+ * @returns ClientOptimizer instance with resolved dependencies
8237
+ */
8238
+ getOptimizer: ((optimizerName: OptimizerName) => ClientOptimizer) & functools_kit.IClearableMemoize<string> & functools_kit.IControlMemoize<string, ClientOptimizer>;
8239
+ /**
8240
+ * Fetches data from all sources and generates strategy metadata.
8241
+ *
8242
+ * @param symbol - Trading pair symbol
8243
+ * @param optimizerName - Optimizer identifier
8244
+ * @returns Array of generated strategies with conversation context
8245
+ */
8246
+ getData: (symbol: string, optimizerName: string) => Promise<IOptimizerStrategy[]>;
8247
+ /**
8248
+ * Generates complete executable strategy code.
8249
+ *
8250
+ * @param symbol - Trading pair symbol
8251
+ * @param optimizerName - Optimizer identifier
8252
+ * @returns Generated TypeScript/JavaScript code as string
8253
+ */
8254
+ getCode: (symbol: string, optimizerName: string) => Promise<string>;
8255
+ /**
8256
+ * Generates and saves strategy code to file.
8257
+ *
8258
+ * @param symbol - Trading pair symbol
8259
+ * @param optimizerName - Optimizer identifier
8260
+ * @param path - Output directory path (optional)
8261
+ */
8262
+ dump: (symbol: string, optimizerName: string, path?: string) => Promise<void>;
8263
+ }
8264
+
8265
+ /**
8266
+ * Global service for optimizer operations with validation.
8267
+ * Entry point for public API, performs validation before delegating to ConnectionService.
8268
+ *
8269
+ * Workflow:
8270
+ * 1. Log operation
8271
+ * 2. Validate optimizer exists
8272
+ * 3. Delegate to OptimizerConnectionService
8273
+ */
8274
+ declare class OptimizerGlobalService {
8275
+ private readonly loggerService;
8276
+ private readonly optimizerConnectionService;
8277
+ private readonly optimizerValidationService;
8278
+ /**
8279
+ * Fetches data from all sources and generates strategy metadata.
8280
+ * Validates optimizer existence before execution.
8281
+ *
8282
+ * @param symbol - Trading pair symbol
8283
+ * @param optimizerName - Optimizer identifier
8284
+ * @returns Array of generated strategies with conversation context
8285
+ * @throws Error if optimizer not found
8286
+ */
8287
+ getData: (symbol: string, optimizerName: string) => Promise<IOptimizerStrategy[]>;
8288
+ /**
8289
+ * Generates complete executable strategy code.
8290
+ * Validates optimizer existence before execution.
8291
+ *
8292
+ * @param symbol - Trading pair symbol
8293
+ * @param optimizerName - Optimizer identifier
8294
+ * @returns Generated TypeScript/JavaScript code as string
8295
+ * @throws Error if optimizer not found
8296
+ */
8297
+ getCode: (symbol: string, optimizerName: string) => Promise<string>;
8298
+ /**
8299
+ * Generates and saves strategy code to file.
8300
+ * Validates optimizer existence before execution.
8301
+ *
8302
+ * @param symbol - Trading pair symbol
8303
+ * @param optimizerName - Optimizer identifier
8304
+ * @param path - Output directory path (optional)
8305
+ * @throws Error if optimizer not found
8306
+ */
8307
+ dump: (symbol: string, optimizerName: string, path?: string) => Promise<void>;
8308
+ }
8309
+
8310
+ /**
8311
+ * Connection service for partial profit/loss tracking.
8312
+ *
8313
+ * Provides memoized ClientPartial instances per signal ID.
8314
+ * Acts as factory and lifetime manager for ClientPartial objects.
8315
+ *
8316
+ * Features:
8317
+ * - Creates one ClientPartial instance per signal ID (memoized)
8318
+ * - Configures instances with logger and event emitter callbacks
8319
+ * - Delegates profit/loss/clear operations to appropriate ClientPartial
8320
+ * - Cleans up memoized instances when signals are cleared
8321
+ *
8322
+ * Architecture:
8323
+ * - Injected into ClientStrategy via PartialGlobalService
8324
+ * - Uses memoize from functools-kit for instance caching
8325
+ * - Emits events to partialProfitSubject/partialLossSubject
8326
+ *
8327
+ * @example
8328
+ * ```typescript
8329
+ * // Service injected via DI
8330
+ * const service = inject<PartialConnectionService>(TYPES.partialConnectionService);
8331
+ *
8332
+ * // Called by ClientStrategy during signal monitoring
8333
+ * await service.profit("BTCUSDT", signal, 55000, 10.0, false, new Date());
8334
+ * // Creates or reuses ClientPartial for signal.id
8335
+ * // Delegates to ClientPartial.profit()
8336
+ *
8337
+ * // When signal closes
8338
+ * await service.clear("BTCUSDT", signal, 52000);
8339
+ * // Clears signal state and removes memoized instance
8340
+ * ```
8341
+ */
8342
+ declare class PartialConnectionService implements IPartial {
8343
+ /**
8344
+ * Logger service injected from DI container.
8345
+ */
8346
+ private readonly loggerService;
8347
+ /**
8348
+ * Memoized factory function for ClientPartial instances.
8349
+ *
8350
+ * Creates one ClientPartial per signal ID with configured callbacks.
8351
+ * Instances are cached until clear() is called.
8352
+ *
8353
+ * Key format: signalId
8354
+ * Value: ClientPartial instance with logger and event emitters
8355
+ */
8356
+ private getPartial;
8357
+ /**
8358
+ * Processes profit state and emits events for newly reached profit levels.
8359
+ *
8360
+ * Retrieves or creates ClientPartial for signal ID, initializes it if needed,
8361
+ * then delegates to ClientPartial.profit() method.
8362
+ *
8363
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
8364
+ * @param data - Signal row data
8365
+ * @param currentPrice - Current market price
8366
+ * @param revenuePercent - Current profit percentage (positive value)
8367
+ * @param backtest - True if backtest mode, false if live mode
8368
+ * @param when - Event timestamp (current time for live, candle time for backtest)
8369
+ * @returns Promise that resolves when profit processing is complete
8370
+ */
8371
+ profit: (symbol: string, data: ISignalRow, currentPrice: number, revenuePercent: number, backtest: boolean, when: Date) => Promise<void>;
8372
+ /**
8373
+ * Processes loss state and emits events for newly reached loss levels.
8374
+ *
8375
+ * Retrieves or creates ClientPartial for signal ID, initializes it if needed,
8376
+ * then delegates to ClientPartial.loss() method.
8377
+ *
8378
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
8379
+ * @param data - Signal row data
8380
+ * @param currentPrice - Current market price
8381
+ * @param lossPercent - Current loss percentage (negative value)
8382
+ * @param backtest - True if backtest mode, false if live mode
8383
+ * @param when - Event timestamp (current time for live, candle time for backtest)
8384
+ * @returns Promise that resolves when loss processing is complete
8385
+ */
8386
+ loss: (symbol: string, data: ISignalRow, currentPrice: number, lossPercent: number, backtest: boolean, when: Date) => Promise<void>;
8387
+ /**
8388
+ * Clears partial profit/loss state when signal closes.
8389
+ *
8390
+ * Retrieves ClientPartial for signal ID, initializes if needed,
8391
+ * delegates clear operation, then removes memoized instance.
8392
+ *
8393
+ * Sequence:
8394
+ * 1. Get ClientPartial from memoize cache
8395
+ * 2. Ensure initialization (waitForInit)
8396
+ * 3. Call ClientPartial.clear() - removes state, persists to disk
8397
+ * 4. Clear memoized instance - prevents memory leaks
8398
+ *
8399
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
8400
+ * @param data - Signal row data
8401
+ * @param priceClose - Final closing price
8402
+ * @returns Promise that resolves when clear is complete
8403
+ */
8404
+ clear: (symbol: string, data: ISignalRow, priceClose: number) => Promise<void>;
8405
+ }
8406
+
8407
+ /**
8408
+ * Global service for partial profit/loss tracking.
8409
+ *
8410
+ * Thin delegation layer that forwards operations to PartialConnectionService.
8411
+ * Provides centralized logging for all partial operations at the global level.
8412
+ *
8413
+ * Architecture:
8414
+ * - Injected into ClientStrategy constructor via IStrategyParams
8415
+ * - Delegates all operations to PartialConnectionService
8416
+ * - Logs operations at "partialGlobalService" level before delegation
8417
+ *
8418
+ * Purpose:
8419
+ * - Single injection point for ClientStrategy (dependency injection pattern)
8420
+ * - Centralized logging for monitoring partial operations
8421
+ * - Layer of abstraction between strategy and connection layer
8422
+ *
8423
+ * @example
8424
+ * ```typescript
8425
+ * // Service injected into ClientStrategy via DI
8426
+ * const strategy = new ClientStrategy({
8427
+ * partial: partialGlobalService,
8428
+ * ...
8429
+ * });
8430
+ *
8431
+ * // Called during signal monitoring
8432
+ * await strategy.params.partial.profit("BTCUSDT", signal, 55000, 10.0, false, new Date());
8433
+ * // Logs at global level → delegates to PartialConnectionService
8434
+ * ```
8435
+ */
8436
+ declare class PartialGlobalService {
8437
+ /**
8438
+ * Logger service injected from DI container.
8439
+ * Used for logging operations at global service level.
8440
+ */
8441
+ private readonly loggerService;
8442
+ /**
8443
+ * Connection service injected from DI container.
8444
+ * Handles actual ClientPartial instance creation and management.
8445
+ */
8446
+ private readonly partialConnectionService;
8447
+ /**
8448
+ * Processes profit state and emits events for newly reached profit levels.
8449
+ *
8450
+ * Logs operation at global service level, then delegates to PartialConnectionService.
8451
+ *
8452
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
8453
+ * @param data - Signal row data
8454
+ * @param currentPrice - Current market price
8455
+ * @param revenuePercent - Current profit percentage (positive value)
8456
+ * @param backtest - True if backtest mode, false if live mode
8457
+ * @param when - Event timestamp (current time for live, candle time for backtest)
8458
+ * @returns Promise that resolves when profit processing is complete
8459
+ */
8460
+ profit: (symbol: string, data: ISignalRow, currentPrice: number, revenuePercent: number, backtest: boolean, when: Date) => Promise<void>;
8461
+ /**
8462
+ * Processes loss state and emits events for newly reached loss levels.
8463
+ *
8464
+ * Logs operation at global service level, then delegates to PartialConnectionService.
8465
+ *
8466
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
8467
+ * @param data - Signal row data
8468
+ * @param currentPrice - Current market price
8469
+ * @param lossPercent - Current loss percentage (negative value)
8470
+ * @param backtest - True if backtest mode, false if live mode
8471
+ * @param when - Event timestamp (current time for live, candle time for backtest)
8472
+ * @returns Promise that resolves when loss processing is complete
8473
+ */
8474
+ loss: (symbol: string, data: ISignalRow, currentPrice: number, lossPercent: number, backtest: boolean, when: Date) => Promise<void>;
8475
+ /**
8476
+ * Clears partial profit/loss state when signal closes.
8477
+ *
8478
+ * Logs operation at global service level, then delegates to PartialConnectionService.
8479
+ *
8480
+ * @param symbol - Trading pair symbol (e.g., "BTCUSDT")
8481
+ * @param data - Signal row data
8482
+ * @param priceClose - Final closing price
8483
+ * @returns Promise that resolves when clear is complete
8484
+ */
8485
+ clear: (symbol: string, data: ISignalRow, priceClose: number) => Promise<void>;
8486
+ }
8487
+
6358
8488
  declare const backtest: {
8489
+ optimizerTemplateService: OptimizerTemplateService;
6359
8490
  exchangeValidationService: ExchangeValidationService;
6360
8491
  strategyValidationService: StrategyValidationService;
6361
8492
  frameValidationService: FrameValidationService;
6362
8493
  walkerValidationService: WalkerValidationService;
6363
8494
  sizingValidationService: SizingValidationService;
6364
8495
  riskValidationService: RiskValidationService;
8496
+ optimizerValidationService: OptimizerValidationService;
6365
8497
  backtestMarkdownService: BacktestMarkdownService;
6366
8498
  liveMarkdownService: LiveMarkdownService;
6367
8499
  scheduleMarkdownService: ScheduleMarkdownService;
6368
8500
  performanceMarkdownService: PerformanceMarkdownService;
6369
8501
  walkerMarkdownService: WalkerMarkdownService;
6370
8502
  heatMarkdownService: HeatMarkdownService;
8503
+ partialMarkdownService: PartialMarkdownService;
6371
8504
  backtestLogicPublicService: BacktestLogicPublicService;
6372
8505
  liveLogicPublicService: LiveLogicPublicService;
6373
8506
  walkerLogicPublicService: WalkerLogicPublicService;
@@ -6382,17 +8515,22 @@ declare const backtest: {
6382
8515
  frameGlobalService: FrameGlobalService;
6383
8516
  sizingGlobalService: SizingGlobalService;
6384
8517
  riskGlobalService: RiskGlobalService;
8518
+ optimizerGlobalService: OptimizerGlobalService;
8519
+ partialGlobalService: PartialGlobalService;
6385
8520
  exchangeSchemaService: ExchangeSchemaService;
6386
8521
  strategySchemaService: StrategySchemaService;
6387
8522
  frameSchemaService: FrameSchemaService;
6388
8523
  walkerSchemaService: WalkerSchemaService;
6389
8524
  sizingSchemaService: SizingSchemaService;
6390
8525
  riskSchemaService: RiskSchemaService;
8526
+ optimizerSchemaService: OptimizerSchemaService;
6391
8527
  exchangeConnectionService: ExchangeConnectionService;
6392
8528
  strategyConnectionService: StrategyConnectionService;
6393
8529
  frameConnectionService: FrameConnectionService;
6394
8530
  sizingConnectionService: SizingConnectionService;
6395
8531
  riskConnectionService: RiskConnectionService;
8532
+ optimizerConnectionService: OptimizerConnectionService;
8533
+ partialConnectionService: PartialConnectionService;
6396
8534
  executionContextService: {
6397
8535
  readonly context: IExecutionContext;
6398
8536
  };
@@ -6402,4 +8540,4 @@ declare const backtest: {
6402
8540
  loggerService: LoggerService;
6403
8541
  };
6404
8542
 
6405
- export { Backtest, type BacktestStatistics, type CandleInterval, type DoneContract, type EntityId, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IHeatmapStatistics, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, Live, type LiveStatistics, MethodContextService, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatistics, PersistBase, PersistRiskAdapter, PersistSignalAdapter, PositionSize, type ProgressContract, type RiskData, Schedule, type ScheduleStatistics, type SignalData, type SignalInterval, type TPersistBase, type TPersistBaseCtor, Walker, type WalkerMetric, type WalkerStatistics, addExchange, addFrame, addRisk, addSizing, addStrategy, addWalker, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getDate, getMode, backtest as lib, listExchanges, listFrames, listRisks, listSizings, listStrategies, listWalkers, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenPerformance, listenProgress, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, setConfig, setLogger };
8543
+ export { Backtest, type BacktestStatistics, type CandleInterval, type DoneContract, type EntityId, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IHeatmapStatistics, type IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, Live, type LiveStatistics, type MessageModel, type MessageRole, MethodContextService, Optimizer, Partial$1 as Partial, type PartialData, type PartialLossContract, type PartialProfitContract, type PartialStatistics, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatistics, PersistBase, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, type ProgressBacktestContract, type ProgressWalkerContract, type RiskData, Schedule, type ScheduleData, type ScheduleStatistics, type SignalData, type SignalInterval, type TPersistBase, type TPersistBaseCtor, Walker, type WalkerContract, type WalkerMetric, type WalkerStatistics, addExchange, addFrame, addOptimizer, addRisk, addSizing, addStrategy, addWalker, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getDate, getMode, backtest as lib, listExchanges, listFrames, listOptimizers, listRisks, listSizings, listStrategies, listWalkers, listenBacktestProgress, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenPartialLoss, listenPartialLossOnce, listenPartialProfit, listenPartialProfitOnce, listenPerformance, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, setConfig, setLogger };