@backtest-kit/ollama 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/build/index.cjs +2300 -104
  2. package/build/index.mjs +2294 -108
  3. package/package.json +1 -1
  4. package/types.d.ts +1353 -1
package/types.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { IOutlineMessage, ISwarmCompletionArgs, ISwarmMessage, IOutlineCompletionArgs } from 'agent-swarm-kit';
2
2
  import { ZodType } from 'zod';
3
+ import { ISignalDto } from 'backtest-kit';
3
4
  import * as di_scoped from 'di-scoped';
5
+ import * as functools_kit from 'functools-kit';
4
6
 
5
7
  /**
6
8
  * Generate structured trading signal from Ollama models.
@@ -424,6 +426,895 @@ declare const setLogger: (logger: ILogger) => void;
424
426
  */
425
427
  declare function overrideSignalFormat<ZodInput extends ZodType>(format: ZodInput): void;
426
428
 
429
+ /**
430
+ * Message role type for LLM conversation context.
431
+ * Defines the sender of a message in a chat-based interaction.
432
+ */
433
+ type MessageRole = "assistant" | "system" | "user";
434
+ /**
435
+ * Message model for LLM conversation history.
436
+ * Used in Optimizer to build prompts and maintain conversation context.
437
+ */
438
+ interface MessageModel {
439
+ /**
440
+ * The sender of the message.
441
+ * - "system": System instructions and context
442
+ * - "user": User input and questions
443
+ * - "assistant": LLM responses
444
+ */
445
+ role: MessageRole;
446
+ /**
447
+ * The text content of the message.
448
+ * Contains the actual message text sent or received.
449
+ */
450
+ content: string;
451
+ }
452
+
453
+ /**
454
+ * Dumps signal data and LLM conversation history to markdown files.
455
+ * Used by AI-powered strategies to save debug logs for analysis.
456
+ *
457
+ * Creates a directory structure with:
458
+ * - 00_system_prompt.md - System messages and output summary
459
+ * - XX_user_message.md - Each user message in separate file (numbered)
460
+ * - XX_llm_output.md - Final LLM output with signal data
461
+ *
462
+ * Skips if directory already exists to avoid overwriting previous results.
463
+ *
464
+ * @param signalId - Unique identifier for the result (used as directory name, e.g., UUID)
465
+ * @param history - Array of message models from LLM conversation
466
+ * @param signal - Signal DTO returned by LLM (position, priceOpen, TP, SL, etc.)
467
+ * @param outputDir - Output directory path (default: "./dump/strategy")
468
+ * @returns Promise that resolves when all files are written
469
+ *
470
+ * @example
471
+ * ```typescript
472
+ * import { dumpSignal, getCandles } from "backtest-kit";
473
+ * import { v4 as uuid } from "uuid";
474
+ *
475
+ * addStrategy({
476
+ * strategyName: "llm-strategy",
477
+ * interval: "5m",
478
+ * getSignal: async (symbol) => {
479
+ * const messages = [];
480
+ *
481
+ * // Build multi-timeframe analysis conversation
482
+ * const candles1h = await getCandles(symbol, "1h", 24);
483
+ * messages.push(
484
+ * { role: "user", content: `Analyze 1h trend:\n${formatCandles(candles1h)}` },
485
+ * { role: "assistant", content: "Trend analyzed" }
486
+ * );
487
+ *
488
+ * const candles5m = await getCandles(symbol, "5m", 24);
489
+ * messages.push(
490
+ * { role: "user", content: `Analyze 5m structure:\n${formatCandles(candles5m)}` },
491
+ * { role: "assistant", content: "Structure analyzed" }
492
+ * );
493
+ *
494
+ * // Request signal
495
+ * messages.push({
496
+ * role: "user",
497
+ * content: "Generate trading signal. Use position: 'wait' if uncertain."
498
+ * });
499
+ *
500
+ * const resultId = uuid();
501
+ * const signal = await llmRequest(messages);
502
+ *
503
+ * // Save conversation and result for debugging
504
+ * await dumpSignal(resultId, messages, signal);
505
+ *
506
+ * return signal;
507
+ * }
508
+ * });
509
+ *
510
+ * // Creates: ./dump/strategy/{uuid}/00_system_prompt.md
511
+ * // ./dump/strategy/{uuid}/01_user_message.md (1h analysis)
512
+ * // ./dump/strategy/{uuid}/02_assistant_message.md
513
+ * // ./dump/strategy/{uuid}/03_user_message.md (5m analysis)
514
+ * // ./dump/strategy/{uuid}/04_assistant_message.md
515
+ * // ./dump/strategy/{uuid}/05_user_message.md (signal request)
516
+ * // ./dump/strategy/{uuid}/06_llm_output.md (final signal)
517
+ * ```
518
+ */
519
+ declare function dumpSignalData(signalId: string | number, history: MessageModel[], signal: ISignalDto, outputDir?: string): Promise<void>;
520
+
521
+ /**
522
+ * Type alias for enum objects with string key-value pairs
523
+ */
524
+ type Enum = Record<string, string>;
525
+ /**
526
+ * Type alias for ValidateArgs with any enum type
527
+ */
528
+ type Args = ValidateArgs<any>;
529
+ /**
530
+ * Interface defining validation arguments for all entity types.
531
+ *
532
+ * Each property accepts an enum object where values will be validated
533
+ * against registered entities in their respective validation services.
534
+ *
535
+ * @template T - Enum type extending Record<string, string>
536
+ */
537
+ interface ValidateArgs<T = Enum> {
538
+ /**
539
+ * Optimizer name enum to validate
540
+ * @example { GRID_SEARCH: "grid-search" }
541
+ */
542
+ OptimizerName?: T;
543
+ }
544
+ /**
545
+ * Validates the existence of all provided entity names across validation services.
546
+ *
547
+ * This function accepts enum objects for various entity types (exchanges, frames,
548
+ * strategies, risks, sizings, optimizers, walkers) and validates that each entity
549
+ * name exists in its respective registry. Validation results are memoized for performance.
550
+ *
551
+ * If no arguments are provided (or specific entity types are omitted), the function
552
+ * automatically fetches and validates ALL registered entities from their respective
553
+ * validation services. This is useful for comprehensive validation of the entire setup.
554
+ *
555
+ * Use this before running backtests or optimizations to ensure all referenced
556
+ * entities are properly registered and configured.
557
+ *
558
+ * @public
559
+ * @param args - Partial validation arguments containing entity name enums to validate.
560
+ * If empty or omitted, validates all registered entities.
561
+ * @throws {Error} If any entity name is not found in its validation service
562
+ *
563
+ * @example
564
+ * ```typescript
565
+ * // Validate ALL registered entities (exchanges, frames, strategies, etc.)
566
+ * await validate({});
567
+ * ```
568
+ *
569
+ * @example
570
+ * ```typescript
571
+ * // Define your entity name enums
572
+ * enum ExchangeName {
573
+ * BINANCE = "binance",
574
+ * BYBIT = "bybit"
575
+ * }
576
+ *
577
+ * enum StrategyName {
578
+ * MOMENTUM_BTC = "momentum-btc"
579
+ * }
580
+ *
581
+ * // Validate specific entities before running backtest
582
+ * await validate({
583
+ * ExchangeName,
584
+ * StrategyName,
585
+ * });
586
+ * ```
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * // Validate specific entity types
591
+ * await validate({
592
+ * RiskName: { CONSERVATIVE: "conservative" },
593
+ * SizingName: { FIXED_1000: "fixed-1000" },
594
+ * });
595
+ * ```
596
+ */
597
+ declare function validate(args?: Partial<Args>): Promise<void>;
598
+
599
+ /**
600
+ * Commits signal prompt history to the message array.
601
+ *
602
+ * Extracts trading context from ExecutionContext and MethodContext,
603
+ * then adds signal-specific system prompts at the beginning and user prompt
604
+ * at the end of the history array if they are not empty.
605
+ *
606
+ * Context extraction:
607
+ * - symbol: Provided as parameter for debugging convenience
608
+ * - backtest mode: From ExecutionContext
609
+ * - strategyName, exchangeName, frameName: From MethodContext
610
+ *
611
+ * @param symbol - Trading symbol (e.g., "BTCUSDT") for debugging convenience
612
+ * @param history - Message array to append prompts to
613
+ * @returns Promise that resolves when prompts are added
614
+ * @throws Error if ExecutionContext or MethodContext is not active
615
+ *
616
+ * @example
617
+ * ```typescript
618
+ * const messages: MessageModel[] = [];
619
+ * await commitSignalPromptHistory("BTCUSDT", messages);
620
+ * // messages now contains system prompts at start and user prompt at end
621
+ * ```
622
+ */
623
+ declare function commitSignalPromptHistory(symbol: string, history: MessageModel[]): Promise<void>;
624
+
625
+ /**
626
+ * Candle interval type for trading timeframes.
627
+ */
628
+ type CandleInterval = "1m" | "3m" | "5m" | "15m" | "30m" | "1h" | "2h" | "4h" | "6h" | "8h" | "12h" | "1d" | "3d" | "1w" | "1M";
629
+ /**
630
+ * Unique string identifier for registered exchanges.
631
+ */
632
+ type ExchangeName$1 = string;
633
+ /**
634
+ * Unique string identifier for registered frames.
635
+ */
636
+ type FrameName$1 = string;
637
+ /**
638
+ * Unique string identifier for registered walkers.
639
+ */
640
+ type WalkerName = string;
641
+ /**
642
+ * Unique string identifier for registered strategies.
643
+ */
644
+ type StrategyName$1 = string;
645
+ /**
646
+ * Unique identifier for data rows in optimizer sources.
647
+ * Can be either a string or numeric ID.
648
+ */
649
+ type RowId = string | number;
650
+ /**
651
+ * Time range configuration for optimizer training or testing periods.
652
+ * Used to define date boundaries for data collection.
653
+ */
654
+ interface IOptimizerRange {
655
+ /**
656
+ * Optional description of this time range.
657
+ * Example: "Bull market period 2024-Q1"
658
+ */
659
+ note?: string;
660
+ /**
661
+ * Start date of the range (inclusive).
662
+ */
663
+ startDate: Date;
664
+ /**
665
+ * End date of the range (inclusive).
666
+ */
667
+ endDate: Date;
668
+ }
669
+ /**
670
+ * Base interface for optimizer data sources.
671
+ * All data fetched from sources must have a unique ID for deduplication.
672
+ */
673
+ interface IOptimizerData {
674
+ /**
675
+ * Unique identifier for this data row.
676
+ * Used for deduplication when paginating data sources.
677
+ */
678
+ id: RowId;
679
+ }
680
+ /**
681
+ * Filter arguments for data source queries without pagination.
682
+ * Used internally to filter data by symbol and time range.
683
+ */
684
+ interface IOptimizerFilterArgs {
685
+ /**
686
+ * Trading pair symbol (e.g., "BTCUSDT").
687
+ */
688
+ symbol: string;
689
+ /**
690
+ * Start date of the data range (inclusive).
691
+ */
692
+ startDate: Date;
693
+ /**
694
+ * End date of the data range (inclusive).
695
+ */
696
+ endDate: Date;
697
+ }
698
+ /**
699
+ * Fetch arguments for paginated data source queries.
700
+ * Extends filter arguments with pagination parameters.
701
+ */
702
+ interface IOptimizerFetchArgs extends IOptimizerFilterArgs {
703
+ /**
704
+ * Maximum number of records to fetch per request.
705
+ * Default: 25 (ITERATION_LIMIT)
706
+ */
707
+ limit: number;
708
+ /**
709
+ * Number of records to skip from the beginning.
710
+ * Used for pagination (offset = page * limit).
711
+ */
712
+ offset: number;
713
+ }
714
+ /**
715
+ * Data source function for fetching optimizer training data.
716
+ * Must support pagination and return data with unique IDs.
717
+ *
718
+ * @param args - Fetch arguments including symbol, dates, limit, offset
719
+ * @returns Array of data rows or Promise resolving to data array
720
+ */
721
+ interface IOptimizerSourceFn<Data extends IOptimizerData = any> {
722
+ (args: IOptimizerFetchArgs): Data[] | Promise<Data[]>;
723
+ }
724
+ /**
725
+ * Generated strategy data with LLM conversation history.
726
+ * Contains the full context used to generate a trading strategy.
727
+ */
728
+ interface IOptimizerStrategy {
729
+ /**
730
+ * Trading pair symbol this strategy was generated for.
731
+ */
732
+ symbol: string;
733
+ /**
734
+ * Unique name taken from data source.
735
+ * Used in callbacks and logging.
736
+ */
737
+ name: string;
738
+ /**
739
+ * LLM conversation history used to generate the strategy.
740
+ * Contains user prompts and assistant responses for each data source.
741
+ */
742
+ messages: MessageModel[];
743
+ /**
744
+ * Generated strategy prompt/description.
745
+ * Output from getPrompt() function, used as strategy logic.
746
+ */
747
+ strategy: string;
748
+ }
749
+ /**
750
+ * Data source configuration with custom message formatters.
751
+ * Defines how to fetch data and format it for LLM conversation.
752
+ */
753
+ interface IOptimizerSource<Data extends IOptimizerData = any> {
754
+ /**
755
+ * Optional description of this data source.
756
+ * Example: "Historical backtest results for training"
757
+ */
758
+ note?: string;
759
+ /**
760
+ * Unique name identifying this data source.
761
+ * Used in callbacks and logging.
762
+ */
763
+ name: string;
764
+ /**
765
+ * Function to fetch data from this source.
766
+ * Must support pagination via limit/offset.
767
+ */
768
+ fetch: IOptimizerSourceFn<Data>;
769
+ /**
770
+ * Optional custom formatter for user messages.
771
+ * If not provided, uses default template from OptimizerTemplateService.
772
+ *
773
+ * @param symbol - Trading pair symbol
774
+ * @param data - Fetched data array
775
+ * @param name - Source name
776
+ * @returns Formatted user message content
777
+ */
778
+ user?: (symbol: string, data: Data[], name: string) => string | Promise<string>;
779
+ /**
780
+ * Optional custom formatter for assistant messages.
781
+ * If not provided, uses default template from OptimizerTemplateService.
782
+ *
783
+ * @param symbol - Trading pair symbol
784
+ * @param data - Fetched data array
785
+ * @param name - Source name
786
+ * @returns Formatted assistant message content
787
+ */
788
+ assistant?: (symbol: string, data: Data[], name: string) => string | Promise<string>;
789
+ }
790
+ /**
791
+ * Union type for data source configuration.
792
+ * Can be either a simple fetch function or a full source configuration object.
793
+ */
794
+ type Source<Data extends IOptimizerData = any> = IOptimizerSourceFn<Data> | IOptimizerSource<Data>;
795
+ /**
796
+ * Lifecycle callbacks for optimizer events.
797
+ * Provides hooks for monitoring and validating optimizer operations.
798
+ */
799
+ interface IOptimizerCallbacks {
800
+ /**
801
+ * Called after strategy data is generated for all train ranges.
802
+ * Useful for logging or validating the generated strategies.
803
+ *
804
+ * @param symbol - Trading pair symbol
805
+ * @param strategyData - Array of generated strategies with their messages
806
+ */
807
+ onData?: (symbol: string, strategyData: IOptimizerStrategy[]) => void | Promise<void>;
808
+ /**
809
+ * Called after strategy code is generated.
810
+ * Useful for logging or validating the generated code.
811
+ *
812
+ * @param symbol - Trading pair symbol
813
+ * @param code - Generated strategy code
814
+ */
815
+ onCode?: (symbol: string, code: string) => void | Promise<void>;
816
+ /**
817
+ * Called after strategy code is dumped to file.
818
+ * Useful for logging or performing additional actions after file write.
819
+ *
820
+ * @param symbol - Trading pair symbol
821
+ * @param filepath - Path where the file was saved
822
+ */
823
+ onDump?: (symbol: string, filepath: string) => void | Promise<void>;
824
+ /**
825
+ * Called after data is fetched from a source.
826
+ * Useful for logging or validating the fetched data.
827
+ *
828
+ * @param symbol - Trading pair symbol
829
+ * @param sourceName - Name of the data source
830
+ * @param data - Array of fetched data
831
+ * @param startDate - Start date of the data range
832
+ * @param endDate - End date of the data range
833
+ */
834
+ onSourceData?: <Data extends IOptimizerData = any>(symbol: string, sourceName: string, data: Data[], startDate: Date, endDate: Date) => void | Promise<void>;
835
+ }
836
+ /**
837
+ * Template interface for generating code snippets and LLM messages.
838
+ * Each method returns TypeScript/JavaScript code as a string.
839
+ */
840
+ interface IOptimizerTemplate {
841
+ /**
842
+ * Generates the top banner with imports and initialization.
843
+ *
844
+ * @param symbol - Trading pair symbol
845
+ * @returns Generated import statements and setup code
846
+ */
847
+ getTopBanner(symbol: string): string | Promise<string>;
848
+ /**
849
+ * Generates default user message content for LLM conversation.
850
+ *
851
+ * @param symbol - Trading pair symbol
852
+ * @param data - Data array from source
853
+ * @param name - Source name
854
+ * @returns Formatted user message content
855
+ */
856
+ getUserMessage<Data extends IOptimizerData = any>(symbol: string, data: Data[], name: string): string | Promise<string>;
857
+ /**
858
+ * Generates default assistant message content for LLM conversation.
859
+ *
860
+ * @param symbol - Trading pair symbol
861
+ * @param data - Data array from source
862
+ * @param name - Source name
863
+ * @returns Formatted assistant message content
864
+ */
865
+ getAssistantMessage<Data extends IOptimizerData = any>(symbol: string, data: Data[], name: string): string | Promise<string>;
866
+ /**
867
+ * Generates Walker configuration code.
868
+ *
869
+ * @param walkerName - Unique walker identifier
870
+ * @param exchangeName - Exchange name to use
871
+ * @param frameName - Frame name for testing
872
+ * @param strategies - Array of strategy names to compare
873
+ * @returns Generated addWalker() call
874
+ */
875
+ getWalkerTemplate(walkerName: WalkerName, exchangeName: ExchangeName$1, frameName: FrameName$1, strategies: string[]): string | Promise<string>;
876
+ /**
877
+ * Generates Exchange configuration code.
878
+ *
879
+ * @param symbol - Trading pair symbol
880
+ * @param exchangeName - Unique exchange identifier
881
+ * @returns Generated addExchange() call with CCXT integration
882
+ */
883
+ getExchangeTemplate(symbol: string, exchangeName: ExchangeName$1): string | Promise<string>;
884
+ /**
885
+ * Generates Frame (timeframe) configuration code.
886
+ *
887
+ * @param symbol - Trading pair symbol
888
+ * @param frameName - Unique frame identifier
889
+ * @param interval - Candle interval (e.g., "1m", "5m")
890
+ * @param startDate - Frame start date
891
+ * @param endDate - Frame end date
892
+ * @returns Generated addFrame() call
893
+ */
894
+ getFrameTemplate(symbol: string, frameName: FrameName$1, interval: CandleInterval, startDate: Date, endDate: Date): string | Promise<string>;
895
+ /**
896
+ * Generates Strategy configuration code with LLM integration.
897
+ *
898
+ * @param strategyName - Unique strategy identifier
899
+ * @param interval - Signal throttling interval (e.g., "5m")
900
+ * @param prompt - Strategy logic prompt from getPrompt()
901
+ * @returns Generated addStrategy() call with getSignal() function
902
+ */
903
+ getStrategyTemplate(strategyName: StrategyName$1, interval: CandleInterval, prompt: string): string | Promise<string>;
904
+ /**
905
+ * Generates launcher code to run Walker and listen to events.
906
+ *
907
+ * @param symbol - Trading pair symbol
908
+ * @param walkerName - Walker name to launch
909
+ * @returns Generated Walker.background() call with event listeners
910
+ */
911
+ getLauncherTemplate(symbol: string, walkerName: WalkerName): string | Promise<string>;
912
+ /**
913
+ * Generates text() helper function for LLM text generation.
914
+ *
915
+ * @param symbol - Trading pair symbol
916
+ * @returns Generated async text() function using Ollama
917
+ */
918
+ getTextTemplate(symbol: string): string | Promise<string>;
919
+ /**
920
+ * Generates json() helper function for structured LLM output.
921
+ *
922
+ * @param symbol - Trading pair symbol
923
+ * @returns Generated async json() function with signal schema
924
+ */
925
+ getJsonTemplate(symbol: string): string | Promise<string>;
926
+ /**
927
+ * Generates dumpJson() helper function for debug output.
928
+ *
929
+ * @param symbol - Trading pair symbol
930
+ * @returns Generated async dumpJson() function for file logging
931
+ */
932
+ getJsonDumpTemplate: (symbol: string) => string | Promise<string>;
933
+ }
934
+ /**
935
+ * Schema configuration for optimizer registration.
936
+ * Defines how to collect data, generate strategies, and create executable code.
937
+ */
938
+ interface IOptimizerSchema {
939
+ /**
940
+ * Optional description of this optimizer configuration.
941
+ */
942
+ note?: string;
943
+ /**
944
+ * Unique identifier for this optimizer.
945
+ * Used to retrieve optimizer instance from registry.
946
+ */
947
+ optimizerName: OptimizerName;
948
+ /**
949
+ * Array of training time ranges.
950
+ * Each range generates a separate strategy variant for comparison.
951
+ */
952
+ rangeTrain: IOptimizerRange[];
953
+ /**
954
+ * Testing time range for strategy validation.
955
+ * Used in generated Walker to evaluate strategy performance.
956
+ */
957
+ rangeTest: IOptimizerRange;
958
+ /**
959
+ * Array of data sources for strategy generation.
960
+ * Each source contributes to the LLM conversation context.
961
+ */
962
+ source: Source[];
963
+ /**
964
+ * Function to generate strategy prompt from conversation history.
965
+ * Called after all sources are processed for each training range.
966
+ *
967
+ * @param symbol - Trading pair symbol
968
+ * @param messages - Complete conversation history with all sources
969
+ * @returns Strategy prompt/logic description
970
+ */
971
+ getPrompt: (symbol: string, messages: MessageModel[]) => string | Promise<string>;
972
+ /**
973
+ * Optional custom template overrides.
974
+ * If not provided, uses defaults from OptimizerTemplateService.
975
+ */
976
+ template?: Partial<IOptimizerTemplate>;
977
+ /**
978
+ * Optional lifecycle callbacks for monitoring.
979
+ */
980
+ callbacks?: Partial<IOptimizerCallbacks>;
981
+ }
982
+ /**
983
+ * Internal parameters for ClientOptimizer instantiation.
984
+ * Extends schema with resolved dependencies (logger, complete template).
985
+ */
986
+ interface IOptimizerParams extends IOptimizerSchema {
987
+ /**
988
+ * Logger instance for debug and info messages.
989
+ * Injected by OptimizerConnectionService.
990
+ */
991
+ logger: ILogger;
992
+ /**
993
+ * Complete template implementation with all methods.
994
+ * Merged from schema.template and OptimizerTemplateService defaults.
995
+ */
996
+ template: IOptimizerTemplate;
997
+ }
998
+ /**
999
+ * Optimizer client interface for strategy generation and code export.
1000
+ * Implemented by ClientOptimizer class.
1001
+ */
1002
+ interface IOptimizer {
1003
+ /**
1004
+ * Fetches data from all sources and generates strategy metadata.
1005
+ * Processes each training range and builds LLM conversation history.
1006
+ *
1007
+ * @param symbol - Trading pair symbol
1008
+ * @returns Array of generated strategies with conversation context
1009
+ */
1010
+ getData(symbol: string): Promise<IOptimizerStrategy[]>;
1011
+ /**
1012
+ * Generates complete executable strategy code.
1013
+ * Includes imports, helpers, strategies, walker, and launcher.
1014
+ *
1015
+ * @param symbol - Trading pair symbol
1016
+ * @returns Generated TypeScript/JavaScript code as string
1017
+ */
1018
+ getCode(symbol: string): Promise<string>;
1019
+ /**
1020
+ * Generates and saves strategy code to file.
1021
+ * Creates directory if needed, writes .mjs file.
1022
+ *
1023
+ * @param symbol - Trading pair symbol
1024
+ * @param path - Output directory path (default: "./")
1025
+ */
1026
+ dump(symbol: string, path?: string): Promise<void>;
1027
+ }
1028
+ /**
1029
+ * Unique string identifier for registered optimizers.
1030
+ */
1031
+ type OptimizerName = string;
1032
+
1033
+ /**
1034
+ * Registers an optimizer configuration in the framework.
1035
+ *
1036
+ * The optimizer generates trading strategies by:
1037
+ * - Collecting data from multiple sources across training periods
1038
+ * - Building LLM conversation history with fetched data
1039
+ * - Generating strategy prompts using getPrompt()
1040
+ * - Creating executable backtest code with templates
1041
+ *
1042
+ * The optimizer produces a complete .mjs file containing:
1043
+ * - Exchange, Frame, Strategy, and Walker configurations
1044
+ * - Multi-timeframe analysis logic
1045
+ * - LLM integration for signal generation
1046
+ * - Event listeners for progress tracking
1047
+ *
1048
+ * @param optimizerSchema - Optimizer configuration object
1049
+ * @param optimizerSchema.optimizerName - Unique optimizer identifier
1050
+ * @param optimizerSchema.rangeTrain - Array of training time ranges (each generates a strategy variant)
1051
+ * @param optimizerSchema.rangeTest - Testing time range for strategy validation
1052
+ * @param optimizerSchema.source - Array of data sources (functions or source objects with custom formatters)
1053
+ * @param optimizerSchema.getPrompt - Function to generate strategy prompt from conversation history
1054
+ * @param optimizerSchema.template - Optional custom template overrides (top banner, helpers, strategy logic, etc.)
1055
+ * @param optimizerSchema.callbacks - Optional lifecycle callbacks (onData, onCode, onDump, onSourceData)
1056
+ *
1057
+ * @example
1058
+ * ```typescript
1059
+ * // Basic optimizer with single data source
1060
+ * addOptimizerSchema({
1061
+ * optimizerName: "llm-strategy-generator",
1062
+ * rangeTrain: [
1063
+ * {
1064
+ * note: "Bull market period",
1065
+ * startDate: new Date("2024-01-01"),
1066
+ * endDate: new Date("2024-01-31"),
1067
+ * },
1068
+ * {
1069
+ * note: "Bear market period",
1070
+ * startDate: new Date("2024-02-01"),
1071
+ * endDate: new Date("2024-02-28"),
1072
+ * },
1073
+ * ],
1074
+ * rangeTest: {
1075
+ * note: "Validation period",
1076
+ * startDate: new Date("2024-03-01"),
1077
+ * endDate: new Date("2024-03-31"),
1078
+ * },
1079
+ * source: [
1080
+ * {
1081
+ * name: "historical-backtests",
1082
+ * fetch: async ({ symbol, startDate, endDate, limit, offset }) => {
1083
+ * // Fetch historical backtest results from database
1084
+ * return await db.backtests.find({
1085
+ * symbol,
1086
+ * date: { $gte: startDate, $lte: endDate },
1087
+ * })
1088
+ * .skip(offset)
1089
+ * .limit(limit);
1090
+ * },
1091
+ * user: async (symbol, data, name) => {
1092
+ * return `Analyze these ${data.length} backtest results for ${symbol}:\n${JSON.stringify(data)}`;
1093
+ * },
1094
+ * assistant: async (symbol, data, name) => {
1095
+ * return "Historical data analyzed successfully";
1096
+ * },
1097
+ * },
1098
+ * ],
1099
+ * getPrompt: async (symbol, messages) => {
1100
+ * // Generate strategy prompt from conversation
1101
+ * return `"Analyze ${symbol} using RSI and MACD. Enter LONG when RSI < 30 and MACD crosses above signal."`;
1102
+ * },
1103
+ * callbacks: {
1104
+ * onData: (symbol, strategyData) => {
1105
+ * console.log(`Generated ${strategyData.length} strategies for ${symbol}`);
1106
+ * },
1107
+ * onCode: (symbol, code) => {
1108
+ * console.log(`Generated ${code.length} characters of code for ${symbol}`);
1109
+ * },
1110
+ * onDump: (symbol, filepath) => {
1111
+ * console.log(`Saved strategy to ${filepath}`);
1112
+ * },
1113
+ * onSourceData: (symbol, sourceName, data, startDate, endDate) => {
1114
+ * console.log(`Fetched ${data.length} rows from ${sourceName} for ${symbol}`);
1115
+ * },
1116
+ * },
1117
+ * });
1118
+ * ```
1119
+ */
1120
+ declare function addOptimizerSchema(optimizerSchema: IOptimizerSchema): void;
1121
+
1122
+ /**
1123
+ * Contract for optimizer progress events.
1124
+ *
1125
+ * Emitted during optimizer execution to track progress.
1126
+ * Contains information about total sources, processed sources, and completion percentage.
1127
+ *
1128
+ * @example
1129
+ * ```typescript
1130
+ * import { listenOptimizerProgress } from "@backtest-kit/ollama";
1131
+ *
1132
+ * listenOptimizerProgress((event) => {
1133
+ * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
1134
+ * console.log(`Processed: ${event.processedSources} / ${event.totalSources}`);
1135
+ * });
1136
+ * ```
1137
+ */
1138
+ interface ProgressOptimizerContract {
1139
+ /** optimizerName - Name of the optimizer being executed */
1140
+ optimizerName: string;
1141
+ /** symbol - Trading symbol (e.g., "BTCUSDT") */
1142
+ symbol: string;
1143
+ /** totalSources - Total number of sources to process */
1144
+ totalSources: number;
1145
+ /** processedSources - Number of sources processed so far */
1146
+ processedSources: number;
1147
+ /** progress - Completion percentage from 0.0 to 1.0 */
1148
+ progress: number;
1149
+ }
1150
+
1151
+ /**
1152
+ * Subscribe to optimizer progress events.
1153
+ * Receives updates during optimizer execution with progress percentage.
1154
+ *
1155
+ * @param callback - Function called on each progress update
1156
+ * @returns Unsubscribe function
1157
+ *
1158
+ * @example
1159
+ * ```typescript
1160
+ * const unsub = listenOptimizerProgress((event) => {
1161
+ * console.log(`Progress: ${(event.progress * 100).toFixed(2)}%`);
1162
+ * console.log(`Processed: ${event.processedSources} / ${event.totalSources}`);
1163
+ * });
1164
+ * // Later: unsub();
1165
+ * ```
1166
+ */
1167
+ declare function listenOptimizerProgress(callback: (event: ProgressOptimizerContract) => void): () => void;
1168
+ /**
1169
+ * Subscribe to error events.
1170
+ * Receives errors from optimizer operations.
1171
+ *
1172
+ * @param callback - Function called on each error
1173
+ * @returns Unsubscribe function
1174
+ *
1175
+ * @example
1176
+ * ```typescript
1177
+ * const unsub = listenError((error) => {
1178
+ * console.error("Error occurred:", error);
1179
+ * });
1180
+ * // Later: unsub();
1181
+ * ```
1182
+ */
1183
+ declare function listenError(callback: (error: Error) => void): () => void;
1184
+
1185
+ /**
1186
+ * Retrieves a registered optimizer schema by name.
1187
+ *
1188
+ * @param optimizerName - Unique optimizer identifier
1189
+ * @returns The optimizer schema configuration object
1190
+ * @throws Error if optimizer is not registered
1191
+ *
1192
+ * @example
1193
+ * ```typescript
1194
+ * const optimizer = getOptimizer("llm-strategy-generator");
1195
+ * console.log(optimizer.rangeTrain); // Array of training ranges
1196
+ * console.log(optimizer.rangeTest); // Testing range
1197
+ * console.log(optimizer.source); // Array of data sources
1198
+ * console.log(optimizer.getPrompt); // async function
1199
+ * ```
1200
+ */
1201
+ declare function getOptimizerSchema(optimizerName: OptimizerName): IOptimizerSchema;
1202
+
1203
+ /**
1204
+ * Returns a list of all registered optimizer schemas.
1205
+ *
1206
+ * Retrieves all optimizers that have been registered via addOptimizer().
1207
+ * Useful for debugging, documentation, or building dynamic UIs.
1208
+ *
1209
+ * @returns Array of optimizer schemas with their configurations
1210
+ *
1211
+ * @example
1212
+ * ```typescript
1213
+ * import { listOptimizers, addOptimizer } from "backtest-kit";
1214
+ *
1215
+ * addOptimizer({
1216
+ * optimizerName: "llm-strategy-generator",
1217
+ * note: "Generates trading strategies using LLM",
1218
+ * rangeTrain: [
1219
+ * {
1220
+ * note: "Training period 1",
1221
+ * startDate: new Date("2024-01-01"),
1222
+ * endDate: new Date("2024-01-31"),
1223
+ * },
1224
+ * ],
1225
+ * rangeTest: {
1226
+ * note: "Testing period",
1227
+ * startDate: new Date("2024-02-01"),
1228
+ * endDate: new Date("2024-02-28"),
1229
+ * },
1230
+ * source: [],
1231
+ * getPrompt: async (symbol, messages) => "Generate strategy",
1232
+ * });
1233
+ *
1234
+ * const optimizers = listOptimizers();
1235
+ * console.log(optimizers);
1236
+ * // [{ optimizerName: "llm-strategy-generator", note: "Generates...", ... }]
1237
+ * ```
1238
+ */
1239
+ declare function listOptimizerSchema(): Promise<IOptimizerSchema[]>;
1240
+
1241
+ /**
1242
+ * Public API utilities for optimizer operations.
1243
+ * Provides high-level methods for strategy generation and code export.
1244
+ *
1245
+ * Usage:
1246
+ * ```typescript
1247
+ * import { Optimizer } from "@backtest-kit/ollama";
1248
+ *
1249
+ * // Get strategy data
1250
+ * const strategies = await Optimizer.getData("BTCUSDT", {
1251
+ * optimizerName: "my-optimizer"
1252
+ * });
1253
+ *
1254
+ * // Generate code
1255
+ * const code = await Optimizer.getCode("BTCUSDT", {
1256
+ * optimizerName: "my-optimizer"
1257
+ * });
1258
+ *
1259
+ * // Save to file
1260
+ * await Optimizer.dump("BTCUSDT", {
1261
+ * optimizerName: "my-optimizer"
1262
+ * }, "./output");
1263
+ * ```
1264
+ */
1265
+ declare class OptimizerUtils {
1266
+ /**
1267
+ * Fetches data from all sources and generates strategy metadata.
1268
+ * Processes each training range and builds LLM conversation history.
1269
+ *
1270
+ * @param symbol - Trading pair symbol
1271
+ * @param context - Context with optimizerName
1272
+ * @returns Array of generated strategies with conversation context
1273
+ * @throws Error if optimizer not found
1274
+ */
1275
+ getData: (symbol: string, context: {
1276
+ optimizerName: OptimizerName;
1277
+ }) => Promise<IOptimizerStrategy[]>;
1278
+ /**
1279
+ * Generates complete executable strategy code.
1280
+ * Includes imports, helpers, strategies, walker, and launcher.
1281
+ *
1282
+ * @param symbol - Trading pair symbol
1283
+ * @param context - Context with optimizerName
1284
+ * @returns Generated TypeScript/JavaScript code as string
1285
+ * @throws Error if optimizer not found
1286
+ */
1287
+ getCode: (symbol: string, context: {
1288
+ optimizerName: OptimizerName;
1289
+ }) => Promise<string>;
1290
+ /**
1291
+ * Generates and saves strategy code to file.
1292
+ * Creates directory if needed, writes .mjs file.
1293
+ *
1294
+ * Format: `{optimizerName}_{symbol}.mjs`
1295
+ *
1296
+ * @param symbol - Trading pair symbol
1297
+ * @param context - Context with optimizerName
1298
+ * @param path - Output directory path (default: "./")
1299
+ * @throws Error if optimizer not found or file write fails
1300
+ */
1301
+ dump: (symbol: string, context: {
1302
+ optimizerName: string;
1303
+ }, path?: string) => Promise<void>;
1304
+ }
1305
+ /**
1306
+ * Singleton instance of OptimizerUtils.
1307
+ * Public API for optimizer operations.
1308
+ *
1309
+ * @example
1310
+ * ```typescript
1311
+ * import { Optimizer } from "@backtest-kit/ollama";
1312
+ *
1313
+ * await Optimizer.dump("BTCUSDT", { optimizerName: "my-optimizer" });
1314
+ * ```
1315
+ */
1316
+ declare const Optimizer: OptimizerUtils;
1317
+
427
1318
  /**
428
1319
  * Enumeration of supported LLM inference providers.
429
1320
  *
@@ -1026,11 +1917,472 @@ declare class OutlinePublicService {
1026
1917
  }>;
1027
1918
  }
1028
1919
 
1920
+ type StrategyName = string;
1921
+ type ExchangeName = string;
1922
+ type FrameName = string;
1923
+ /**
1924
+ * Service for managing signal prompts for AI/LLM integrations.
1925
+ *
1926
+ * Provides access to system and user prompts configured in signal.prompt.cjs.
1927
+ * Supports both static prompt arrays and dynamic prompt functions.
1928
+ *
1929
+ * Key responsibilities:
1930
+ * - Lazy-loads prompt configuration from config/prompt/signal.prompt.cjs
1931
+ * - Resolves system prompts (static arrays or async functions)
1932
+ * - Provides user prompt strings
1933
+ * - Falls back to empty prompts if configuration is missing
1934
+ *
1935
+ * Used for AI-powered signal analysis and strategy recommendations.
1936
+ */
1937
+ declare class SignalPromptService {
1938
+ private readonly loggerService;
1939
+ /**
1940
+ * Retrieves system prompts for AI context.
1941
+ *
1942
+ * System prompts can be:
1943
+ * - Static array of strings (returned directly)
1944
+ * - Async/sync function returning string array (executed and awaited)
1945
+ * - Undefined (returns empty array)
1946
+ *
1947
+ * @param symbol - Trading symbol (e.g., "BTCUSDT")
1948
+ * @param strategyName - Strategy identifier
1949
+ * @param exchangeName - Exchange identifier
1950
+ * @param frameName - Timeframe identifier
1951
+ * @param backtest - Whether running in backtest mode
1952
+ * @returns Promise resolving to array of system prompt strings
1953
+ */
1954
+ getSystemPrompt: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean) => Promise<string[]>;
1955
+ /**
1956
+ * Retrieves user prompt string for AI input.
1957
+ *
1958
+ * @param symbol - Trading symbol (e.g., "BTCUSDT")
1959
+ * @param strategyName - Strategy identifier
1960
+ * @param exchangeName - Exchange identifier
1961
+ * @param frameName - Timeframe identifier
1962
+ * @param backtest - Whether running in backtest mode
1963
+ * @returns Promise resolving to user prompt string
1964
+ */
1965
+ getUserPrompt: (symbol: string, strategyName: StrategyName, exchangeName: ExchangeName, frameName: FrameName, backtest: boolean) => Promise<string>;
1966
+ }
1967
+
1968
+ /**
1969
+ * Unique identifier for outline result.
1970
+ * Can be string or number for flexible ID formats.
1971
+ */
1972
+ type ResultId = string | number;
1973
+ /**
1974
+ * Service for generating markdown documentation from LLM outline results.
1975
+ * Used by AI Strategy Optimizer to save debug logs and conversation history.
1976
+ *
1977
+ * Creates directory structure:
1978
+ * - ./dump/strategy/{signalId}/00_system_prompt.md - System messages and output data
1979
+ * - ./dump/strategy/{signalId}/01_user_message.md - First user input
1980
+ * - ./dump/strategy/{signalId}/02_user_message.md - Second user input
1981
+ * - ./dump/strategy/{signalId}/XX_llm_output.md - Final LLM output
1982
+ */
1983
+ declare class OutlineMarkdownService {
1984
+ /** Logger service injected via DI */
1985
+ private readonly loggerService;
1986
+ /**
1987
+ * Dumps signal data and conversation history to markdown files.
1988
+ * Skips if directory already exists to avoid overwriting previous results.
1989
+ *
1990
+ * Generated files:
1991
+ * - 00_system_prompt.md - System messages and output summary
1992
+ * - XX_user_message.md - Each user message in separate file (numbered)
1993
+ * - XX_llm_output.md - Final LLM output with signal data
1994
+ *
1995
+ * @param signalId - Unique identifier for the result (used as directory name)
1996
+ * @param history - Array of message models from LLM conversation
1997
+ * @param signal - Signal DTO with trade parameters (priceOpen, TP, SL, etc.)
1998
+ * @param outputDir - Output directory path (default: "./dump/strategy")
1999
+ * @returns Promise that resolves when all files are written
2000
+ *
2001
+ * @example
2002
+ * ```typescript
2003
+ * await outlineService.dumpSignal(
2004
+ * "strategy-1",
2005
+ * conversationHistory,
2006
+ * { position: "long", priceTakeProfit: 51000, priceStopLoss: 49000, minuteEstimatedTime: 60 }
2007
+ * );
2008
+ * // Creates: ./dump/strategy/strategy-1/00_system_prompt.md
2009
+ * // ./dump/strategy/strategy-1/01_user_message.md
2010
+ * // ./dump/strategy/strategy-1/02_llm_output.md
2011
+ * ```
2012
+ */
2013
+ dumpSignal: (signalId: ResultId, history: MessageModel[], signal: ISignalDto, outputDir?: string) => Promise<void>;
2014
+ }
2015
+
2016
+ /**
2017
+ * Default template service for generating optimizer code snippets.
2018
+ * Implements all IOptimizerTemplate methods with Ollama LLM integration.
2019
+ *
2020
+ * Features:
2021
+ * - Multi-timeframe analysis (1m, 5m, 15m, 1h)
2022
+ * - JSON structured output for signals
2023
+ * - Debug logging to ./dump/strategy
2024
+ * - CCXT exchange integration
2025
+ * - Walker-based strategy comparison
2026
+ *
2027
+ * Can be partially overridden in optimizer schema configuration.
2028
+ */
2029
+ declare class OptimizerTemplateService implements IOptimizerTemplate {
2030
+ private readonly loggerService;
2031
+ /**
2032
+ * Generates the top banner with imports and constants.
2033
+ *
2034
+ * @param symbol - Trading pair symbol
2035
+ * @returns Shebang, imports, and WARN_KB constant
2036
+ */
2037
+ getTopBanner: (symbol: string) => Promise<string>;
2038
+ /**
2039
+ * Generates default user message for LLM conversation.
2040
+ * Simple prompt to read and acknowledge data.
2041
+ *
2042
+ * @param symbol - Trading pair symbol
2043
+ * @param data - Fetched data array
2044
+ * @param name - Source name
2045
+ * @returns User message with JSON data
2046
+ */
2047
+ getUserMessage: (symbol: string, data: IOptimizerData[], name: string) => Promise<string>;
2048
+ /**
2049
+ * Generates default assistant message for LLM conversation.
2050
+ * Simple acknowledgment response.
2051
+ *
2052
+ * @param symbol - Trading pair symbol
2053
+ * @param data - Fetched data array
2054
+ * @param name - Source name
2055
+ * @returns Assistant acknowledgment message
2056
+ */
2057
+ getAssistantMessage: (symbol: string, data: IOptimizerData[], name: string) => Promise<string>;
2058
+ /**
2059
+ * Generates Walker configuration code.
2060
+ * Compares multiple strategies on test frame.
2061
+ *
2062
+ * @param walkerName - Unique walker identifier
2063
+ * @param exchangeName - Exchange to use for backtesting
2064
+ * @param frameName - Test frame name
2065
+ * @param strategies - Array of strategy names to compare
2066
+ * @returns Generated addWalker() call
2067
+ */
2068
+ getWalkerTemplate: (walkerName: WalkerName, exchangeName: ExchangeName$1, frameName: FrameName$1, strategies: string[]) => Promise<string>;
2069
+ /**
2070
+ * Generates Strategy configuration with LLM integration.
2071
+ * Includes multi-timeframe analysis and signal generation.
2072
+ *
2073
+ * @param strategyName - Unique strategy identifier
2074
+ * @param interval - Signal throttling interval (e.g., "5m")
2075
+ * @param prompt - Strategy logic from getPrompt()
2076
+ * @returns Generated addStrategy() call with getSignal() function
2077
+ */
2078
+ getStrategyTemplate: (strategyName: StrategyName$1, interval: CandleInterval, prompt: string) => Promise<string>;
2079
+ /**
2080
+ * Generates Exchange configuration code.
2081
+ * Uses CCXT Binance with standard formatters.
2082
+ *
2083
+ * @param symbol - Trading pair symbol (unused, for consistency)
2084
+ * @param exchangeName - Unique exchange identifier
2085
+ * @returns Generated addExchange() call with CCXT integration
2086
+ */
2087
+ getExchangeTemplate: (symbol: string, exchangeName: ExchangeName$1) => Promise<string>;
2088
+ /**
2089
+ * Generates Frame (timeframe) configuration code.
2090
+ *
2091
+ * @param symbol - Trading pair symbol (unused, for consistency)
2092
+ * @param frameName - Unique frame identifier
2093
+ * @param interval - Candle interval (e.g., "1m")
2094
+ * @param startDate - Frame start date
2095
+ * @param endDate - Frame end date
2096
+ * @returns Generated addFrame() call
2097
+ */
2098
+ getFrameTemplate: (symbol: string, frameName: FrameName$1, interval: CandleInterval, startDate: Date, endDate: Date) => Promise<string>;
2099
+ /**
2100
+ * Generates launcher code to run Walker with event listeners.
2101
+ * Includes progress tracking and completion handlers.
2102
+ *
2103
+ * @param symbol - Trading pair symbol
2104
+ * @param walkerName - Walker name to launch
2105
+ * @returns Generated Walker.background() call with listeners
2106
+ */
2107
+ getLauncherTemplate: (symbol: string, walkerName: WalkerName) => Promise<string>;
2108
+ /**
2109
+ * Generates dumpJson() helper function for debug output.
2110
+ * Saves LLM conversations and results to ./dump/strategy/{resultId}/
2111
+ *
2112
+ * @param symbol - Trading pair symbol (unused, for consistency)
2113
+ * @returns Generated async dumpJson() function
2114
+ */
2115
+ getJsonDumpTemplate: (symbol: string) => Promise<string>;
2116
+ /**
2117
+ * Generates text() helper for LLM text generation.
2118
+ * Uses Ollama deepseek-v3.1:671b model for market analysis.
2119
+ *
2120
+ * @param symbol - Trading pair symbol (used in prompt)
2121
+ * @returns Generated async text() function
2122
+ */
2123
+ getTextTemplate: (symbol: string) => Promise<string>;
2124
+ /**
2125
+ * Generates json() helper for structured LLM output.
2126
+ * Uses Ollama with JSON schema for trading signals.
2127
+ *
2128
+ * Signal schema:
2129
+ * - position: "wait" | "long" | "short"
2130
+ * - note: strategy explanation
2131
+ * - priceOpen: entry price
2132
+ * - priceTakeProfit: target price
2133
+ * - priceStopLoss: stop price
2134
+ * - minuteEstimatedTime: expected duration (max 360 min)
2135
+ *
2136
+ * @param symbol - Trading pair symbol (unused, for consistency)
2137
+ * @returns Generated async json() function with signal schema
2138
+ */
2139
+ getJsonTemplate: (symbol: string) => Promise<string>;
2140
+ }
2141
+
2142
+ /**
2143
+ * Service for managing optimizer schema registration and retrieval.
2144
+ * Provides validation and registry management for optimizer configurations.
2145
+ *
2146
+ * Uses ToolRegistry for immutable schema storage.
2147
+ */
2148
+ declare class OptimizerSchemaService {
2149
+ readonly loggerService: LoggerService;
2150
+ private _registry;
2151
+ /**
2152
+ * Registers a new optimizer schema.
2153
+ * Validates required fields before registration.
2154
+ *
2155
+ * @param key - Unique optimizer name
2156
+ * @param value - Optimizer schema configuration
2157
+ * @throws Error if schema validation fails
2158
+ */
2159
+ register: (key: OptimizerName, value: IOptimizerSchema) => void;
2160
+ /**
2161
+ * Validates optimizer schema structure.
2162
+ * Checks required fields: optimizerName, rangeTrain, source, getPrompt.
2163
+ *
2164
+ * @param optimizerSchema - Schema to validate
2165
+ * @throws Error if validation fails
2166
+ */
2167
+ private validateShallow;
2168
+ /**
2169
+ * Partially overrides an existing optimizer schema.
2170
+ * Merges provided values with existing schema.
2171
+ *
2172
+ * @param key - Optimizer name to override
2173
+ * @param value - Partial schema values to merge
2174
+ * @returns Updated complete schema
2175
+ * @throws Error if optimizer not found
2176
+ */
2177
+ override: (key: OptimizerName, value: Partial<IOptimizerSchema>) => IOptimizerSchema;
2178
+ /**
2179
+ * Retrieves optimizer schema by name.
2180
+ *
2181
+ * @param key - Optimizer name
2182
+ * @returns Complete optimizer schema
2183
+ * @throws Error if optimizer not found
2184
+ */
2185
+ get: (key: OptimizerName) => IOptimizerSchema;
2186
+ }
2187
+
2188
+ /**
2189
+ * Service for validating optimizer existence and managing optimizer registry.
2190
+ * Maintains a Map of registered optimizers for validation purposes.
2191
+ *
2192
+ * Uses memoization for efficient repeated validation checks.
2193
+ */
2194
+ declare class OptimizerValidationService {
2195
+ private readonly loggerService;
2196
+ private _optimizerMap;
2197
+ /**
2198
+ * Adds optimizer to validation registry.
2199
+ * Prevents duplicate optimizer names.
2200
+ *
2201
+ * @param optimizerName - Unique optimizer identifier
2202
+ * @param optimizerSchema - Complete optimizer schema
2203
+ * @throws Error if optimizer with same name already exists
2204
+ */
2205
+ addOptimizer: (optimizerName: OptimizerName, optimizerSchema: IOptimizerSchema) => void;
2206
+ /**
2207
+ * Validates that optimizer exists in registry.
2208
+ * Memoized for performance on repeated checks.
2209
+ *
2210
+ * @param optimizerName - Optimizer name to validate
2211
+ * @param source - Source method name for error messages
2212
+ * @throws Error if optimizer not found
2213
+ */
2214
+ validate: (optimizerName: OptimizerName, source: string) => void;
2215
+ /**
2216
+ * Lists all registered optimizer schemas.
2217
+ *
2218
+ * @returns Array of all optimizer schemas
2219
+ */
2220
+ list: () => Promise<IOptimizerSchema[]>;
2221
+ }
2222
+
2223
+ /**
2224
+ * Client implementation for optimizer operations.
2225
+ *
2226
+ * Features:
2227
+ * - Data collection from multiple sources with pagination
2228
+ * - LLM conversation history building
2229
+ * - Strategy code generation with templates
2230
+ * - File export with callbacks
2231
+ *
2232
+ * Used by OptimizerConnectionService to create optimizer instances.
2233
+ */
2234
+ declare class ClientOptimizer implements IOptimizer {
2235
+ readonly params: IOptimizerParams;
2236
+ readonly onProgress: (progress: ProgressOptimizerContract) => void;
2237
+ constructor(params: IOptimizerParams, onProgress: (progress: ProgressOptimizerContract) => void);
2238
+ /**
2239
+ * Fetches data from all sources and generates strategy metadata.
2240
+ * Processes each training range and builds LLM conversation history.
2241
+ *
2242
+ * @param symbol - Trading pair symbol
2243
+ * @returns Array of generated strategies with conversation context
2244
+ */
2245
+ getData: (symbol: string) => Promise<IOptimizerStrategy[]>;
2246
+ /**
2247
+ * Generates complete executable strategy code.
2248
+ * Includes imports, helpers, strategies, walker, and launcher.
2249
+ *
2250
+ * @param symbol - Trading pair symbol
2251
+ * @returns Generated TypeScript/JavaScript code as string
2252
+ */
2253
+ getCode: (symbol: string) => Promise<string>;
2254
+ /**
2255
+ * Generates and saves strategy code to file.
2256
+ * Creates directory if needed, writes .mjs file.
2257
+ *
2258
+ * @param symbol - Trading pair symbol
2259
+ * @param path - Output directory path (default: "./")
2260
+ */
2261
+ dump: (symbol: string, path?: string) => Promise<void>;
2262
+ }
2263
+
2264
+ /**
2265
+ * Type helper for optimizer method signatures.
2266
+ * Maps IOptimizer interface methods to any return type.
2267
+ */
2268
+ type TOptimizer$1 = {
2269
+ [key in keyof IOptimizer]: any;
2270
+ };
2271
+ /**
2272
+ * Service for creating and caching optimizer client instances.
2273
+ * Handles dependency injection and template merging.
2274
+ *
2275
+ * Features:
2276
+ * - Memoized optimizer instances (one per optimizerName)
2277
+ * - Template merging (custom + defaults)
2278
+ * - Logger injection
2279
+ * - Delegates to ClientOptimizer for actual operations
2280
+ */
2281
+ declare class OptimizerConnectionService implements TOptimizer$1 {
2282
+ private readonly loggerService;
2283
+ private readonly optimizerSchemaService;
2284
+ private readonly optimizerTemplateService;
2285
+ /**
2286
+ * Creates or retrieves cached optimizer instance.
2287
+ * Memoized by optimizerName for performance.
2288
+ *
2289
+ * Merges custom templates from schema with defaults from OptimizerTemplateService.
2290
+ *
2291
+ * @param optimizerName - Unique optimizer identifier
2292
+ * @returns ClientOptimizer instance with resolved dependencies
2293
+ */
2294
+ getOptimizer: ((optimizerName: OptimizerName) => ClientOptimizer) & functools_kit.IClearableMemoize<string> & functools_kit.IControlMemoize<string, ClientOptimizer>;
2295
+ /**
2296
+ * Fetches data from all sources and generates strategy metadata.
2297
+ *
2298
+ * @param symbol - Trading pair symbol
2299
+ * @param optimizerName - Optimizer identifier
2300
+ * @returns Array of generated strategies with conversation context
2301
+ */
2302
+ getData: (symbol: string, optimizerName: string) => Promise<IOptimizerStrategy[]>;
2303
+ /**
2304
+ * Generates complete executable strategy code.
2305
+ *
2306
+ * @param symbol - Trading pair symbol
2307
+ * @param optimizerName - Optimizer identifier
2308
+ * @returns Generated TypeScript/JavaScript code as string
2309
+ */
2310
+ getCode: (symbol: string, optimizerName: string) => Promise<string>;
2311
+ /**
2312
+ * Generates and saves strategy code to file.
2313
+ *
2314
+ * @param symbol - Trading pair symbol
2315
+ * @param optimizerName - Optimizer identifier
2316
+ * @param path - Output directory path (optional)
2317
+ */
2318
+ dump: (symbol: string, optimizerName: string, path?: string) => Promise<void>;
2319
+ }
2320
+
2321
+ /**
2322
+ * Type definition for optimizer methods.
2323
+ * Maps all keys of IOptimizer to any type.
2324
+ * Used for dynamic method routing in OptimizerGlobalService.
2325
+ */
2326
+ type TOptimizer = {
2327
+ [key in keyof IOptimizer]: any;
2328
+ };
2329
+ /**
2330
+ * Global service for optimizer operations with validation.
2331
+ * Entry point for public API, performs validation before delegating to ConnectionService.
2332
+ *
2333
+ * Workflow:
2334
+ * 1. Log operation
2335
+ * 2. Validate optimizer exists
2336
+ * 3. Delegate to OptimizerConnectionService
2337
+ */
2338
+ declare class OptimizerGlobalService implements TOptimizer {
2339
+ private readonly loggerService;
2340
+ private readonly optimizerConnectionService;
2341
+ private readonly optimizerValidationService;
2342
+ /**
2343
+ * Fetches data from all sources and generates strategy metadata.
2344
+ * Validates optimizer existence before execution.
2345
+ *
2346
+ * @param symbol - Trading pair symbol
2347
+ * @param optimizerName - Optimizer identifier
2348
+ * @returns Array of generated strategies with conversation context
2349
+ * @throws Error if optimizer not found
2350
+ */
2351
+ getData: (symbol: string, optimizerName: string) => Promise<IOptimizerStrategy[]>;
2352
+ /**
2353
+ * Generates complete executable strategy code.
2354
+ * Validates optimizer existence before execution.
2355
+ *
2356
+ * @param symbol - Trading pair symbol
2357
+ * @param optimizerName - Optimizer identifier
2358
+ * @returns Generated TypeScript/JavaScript code as string
2359
+ * @throws Error if optimizer not found
2360
+ */
2361
+ getCode: (symbol: string, optimizerName: string) => Promise<string>;
2362
+ /**
2363
+ * Generates and saves strategy code to file.
2364
+ * Validates optimizer existence before execution.
2365
+ *
2366
+ * @param symbol - Trading pair symbol
2367
+ * @param optimizerName - Optimizer identifier
2368
+ * @param path - Output directory path (optional)
2369
+ * @throws Error if optimizer not found
2370
+ */
2371
+ dump: (symbol: string, optimizerName: string, path?: string) => Promise<void>;
2372
+ }
2373
+
1029
2374
  /**
1030
2375
  * Main engine object containing all services.
1031
2376
  * Provides unified access to the entire service layer.
1032
2377
  */
1033
2378
  declare const engine: {
2379
+ optimizerTemplateService: OptimizerTemplateService;
2380
+ optimizerSchemaService: OptimizerSchemaService;
2381
+ optimizerValidationService: OptimizerValidationService;
2382
+ optimizerConnectionService: OptimizerConnectionService;
2383
+ optimizerGlobalService: OptimizerGlobalService;
2384
+ outlineMarkdownService: OutlineMarkdownService;
2385
+ signalPromptService: SignalPromptService;
1034
2386
  runnerPublicService: RunnerPublicService;
1035
2387
  outlinePublicService: OutlinePublicService;
1036
2388
  runnerPrivateService: RunnerPrivateService;
@@ -1041,4 +2393,4 @@ declare const engine: {
1041
2393
  loggerService: LoggerService;
1042
2394
  };
1043
2395
 
1044
- export { alibaba, claude, cohere, deepseek, glm4, gpt5, grok, hf, engine as lib, mistral, ollama, overrideSignalFormat, perplexity, setLogger };
2396
+ export { type IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, type MessageModel, type MessageRole, Optimizer, type ProgressOptimizerContract, addOptimizerSchema, alibaba, claude, cohere, commitSignalPromptHistory, deepseek, dumpSignalData, getOptimizerSchema, glm4, gpt5, grok, hf, engine as lib, listOptimizerSchema, listenError, listenOptimizerProgress, mistral, ollama, overrideSignalFormat, perplexity, setLogger, validate };