Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Introduce NamedStrategy support for strategy serialization#1349

Merged
TheCookieLab merged 1 commit intofeature/rule-name-propertyfrom
codex/create-namedstrategy-extending-basestrategy
Oct 19, 2025
Merged

Introduce NamedStrategy support for strategy serialization#1349
TheCookieLab merged 1 commit intofeature/rule-name-propertyfrom
codex/create-namedstrategy-extending-basestrategy

Conversation

@TheCookieLab
Copy link
Member

Summary

  • add a NamedStrategy base class that builds compact descriptors and exposes string-based reconstruction hooks
  • teach StrategySerialization to detect named strategies and create them via the new BarSeries/String constructor while preserving legacy behaviour
  • exercise the new flow with round-trip tests covering named strategy descriptors and stability semantics

Testing

  • mvn -pl ta4j-core test -Dtest=StrategySerializationTest
  • mvn -B clean license:format formatter:format test install

https://chatgpt.com/codex/tasks/task_e_68f4ce8db1ec832697712037f3131513

@TheCookieLab TheCookieLab merged commit eaeecdb into feature/rule-name-property Oct 19, 2025
@TheCookieLab TheCookieLab deleted the codex/create-namedstrategy-extending-basestrategy branch October 19, 2025 12:31
Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +112 to +118
@SuppressWarnings("unchecked")
private static Class<? extends NamedStrategy> resolveConcreteType() {
return StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE)
.walk(stream -> stream.map(StackWalker.StackFrame::getDeclaringClass)
.filter(clazz -> NamedStrategy.class.isAssignableFrom(clazz) && clazz != NamedStrategy.class)
.findFirst())
.map(clazz -> (Class<? extends NamedStrategy>) clazz)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve NamedStrategy parser using deepest subclass

The constructor determines the parser to use by walking the stack and returning the first subclass of NamedStrategy. This only works when the concrete strategy directly extends NamedStrategy; if a strategy subclasses an intermediate NamedStrategy base (e.g., BaseRsiStrategyMyRsiStrategy), the first match will be the intermediate class, so PARSERS.get(type) looks up the wrong key and throws No parser registered… even when the concrete subclass registered its parser. The stack walk should pick the most-derived NamedStrategy in the call stack (or accept the class from the caller) so multi-level named strategy hierarchies can be deserialized.

Useful? React with 👍 / 👎.

TheCookieLab added a commit that referenced this pull request Nov 18, 2025
* implemented rule names

* removed agent/todo files

* Use Gson-backed descriptors for rule names (#1336)

* removed .orig files

* Add JSON serialization for indicators (#1341)

* Fix indicator instantiation parameter mapping (#1342)

* Add strategy serialization utilities (#1343)

* Add rule serialization support and expand strategy tests (#1344)

* Handle array arguments in rule serialization (#1346)

* Add NamedStrategy support and update serialization (#1349)

* Add named strategy fixture serialization tests (#1351)

* Fix NamedStrategy stack resolution for multi-level subclasses (#1352)

* Fix NamedStrategy stack walker selection (#1354)

* docs: note NamedStrategy serialization support (#1356)

* Add strategy named AGENTS guidelines (#1357)

* Harden named strategy serialization validation (#1372)

* ran formatter

* looking for ways to slim up the serialized forms

* Refactor logging in examples to use Log4j2 for improved debugging and consistency across the codebase. Updated print statements to debug logs in Quickstart, StrategyAnalysis, TradeCost, TradingBotOnMovingBarSeries, CsvBarsLoader, CsvTradesLoader, and various strategies.

* Refactor CsvBarsLoader and CsvTradesLoader to support loading from specified CSV files. Updated load methods to accept file names as parameters and improved documentation for clarity. Enhanced ADXStrategy to include charting functionality using ChartMaker for better visual analysis of trading records.

* Enhance documentation in CsvBarsLoader and CsvTradesLoader for clarity on loading methods. Implement charting functionality in multiple strategies (ADX, CCI, GlobalExtrema, MovingMomentum, RSI2, UnstableIndicator) using ChartMaker to improve visual analysis of trading records.

* added headless check for tests that produce charts

* renamed BinaryOperation and UnaryOperation to BinaryOperationIndicator and UnaryOperationIndicator to conform to indicator naming (needed for serialization feature). Left deprecation shim in place to minimize downstream disruptions

* Implement saveChartImage method overloads in ChartMaker for custom directory support. Add validation for null and empty directory inputs. Enhance unit tests to cover various scenarios for saving charts, including custom file names and nested directories.

* Add RuleSerializationCustomNameTest to validate preservation of custom rule names during serialization

* Enhance RuleSerialization to preserve custom rule names during serialization and deserialization. Implement logic to differentiate between custom names and default JSON representations. Add utility methods for comparing component descriptors and handling mouseover functionality in SwingChartDisplayer, including hover delay configuration and display of OHLC data. Update tests to validate new features and ensure proper functionality.

* Update SwingChartDisplayer to reduce default hover delay and disable tooltips. Simplify mouseover data formatting by removing series name from the display string for improved clarity.

* Refactor KalmanFilterIndicator to mark fields as transient, ensuring they are not serialized. Update IndicatorSerialization to skip transient fields during serialization. Add tests to verify that transient fields are excluded from the serialized output and ensure correct deserialization behavior.

* Enhance BacktestExecutionResult to store and attach criterion scores to trading statements. Update BaseTradingStatement to include optional criterion scores and modify TradingStatement interface to provide access to these scores. Add tests to verify the correct storage and retrieval of criterion scores in backtest results.

* Add ProgressCompletion utility for backtest progress reporting

Introduce a new ProgressCompletion class to provide default progress reporting callbacks for backtest execution. This includes no-op and logging callbacks that can be used to track progress during strategy execution. Update BacktestExecutor to utilize these callbacks, ensuring that progress can be reported effectively. Additionally, add tests to validate the functionality of the new progress reporting features.

* Add logging convenience methods to ProgressCompletion for automatic caller detection

* Add loggingWithMemory methods to ProgressCompletion for enhanced memory tracking during backtests

* Enhance AGENTS.md with detailed testing and debugging guidelines. Introduce a new method for obtaining trace display names in BaseStrategy and AbstractRule for improved logging clarity. Update RuleSerialization to support parent context resolution during rule deserialization, ensuring proper handling of Strategy-level components. Refactor TrailingStopLossRule to utilize the new trace display name method. Update example backtest code for improved logging clarity.

* Refactor AGENTS.md to clarify serialization guidelines and testing practices.

* added dayofweekstrategy in prep for namedstrategy refinement

* Refine NamedStrategy serialization and enhance AGENTS documentation

* Enhance NamedStrategy with lazy package scanning and update AGENTS documentation. Introduce `initializeRegistry` method for automatic registration of named strategies, improving usability and flexibility. Add tests to validate new functionality.

* re-organized and tweaked unreleased changelog items for clarity and impact

* Update CHANGELOG.md to clarify Java 25 compatibility note and ensure accurate representation of recent fixes and enhancements.

* Add chain rule serialization support (#1375)

* Refactor InSlopeRule for improved clarity and functionality; add support for serialization

* Update AGENTS.md and add run-full-build-quiet.sh script for improved build process; enhance serialization testing guidelines and add serialization tests for various rules.

* Update logging levels in configuration and examples; change root logger level from debug to info and adjust log statements from info to debug for better log management.

* Enhance serialization testing for rules by adding JSON round-trip assertions across multiple rule test classes; update AGENTS.md to clarify Maven testing command usage for improved feedback loop.

* Remove deprecated BinaryOperation and UnaryOperation classes, replacing them with BinaryOperationIndicator and UnaryOperationIndicator respectively, to streamline the codebase and improve clarity.

* Enhance NamedStrategy documentation with detailed guidelines on compact name format, constructor requirements, registration methods, and serialization process. Update test assertions in LinearTransactionCostModelTest and suppress deprecation warnings in CombineIndicatorTest for improved clarity and functionality.

* Refactor logging setup in StrategyTraceLoggingTest to improve clarity and prevent console output during tests. Introduce a method to safely convert maps to avoid unchecked cast warnings in RuleSerializationRoundTripTestSupport, enhancing type safety and maintainability.

* Refactor logging setup in RuleTraceLoggingTest to enhance clarity and prevent console output during tests. Update log4j2 configuration files to include a ThresholdFilter for INFO level, ensuring cleaner log management across examples and test resources.

* Update AGENTS.md to clarify that all code changes affecting build/test behavior must ensure a green build at the end of the development cycle.

* Add TopStrategiesExampleBacktest class to demonstrate strategy ranking via backtesting

This new example illustrates the use of the getTopStrategies API to identify and rank the best trading strategies based on multiple criteria, including Net Profit and Expectancy. It includes the creation of various strategies, execution of backtests, and logging of results for the top strategies.

* Refactor TopStrategiesExampleBacktest class and update logging configuration

Renamed the package and class references in TopStrategiesExampleBacktest to ensure consistency. Updated log4j2 configuration to reflect the new class name for logging purposes, enhancing clarity in the logging setup.

* Update CHANGELOG.md to reflect build output cleanup

* Add HourOfDayRule and HourOfDayStrategy classes with corresponding tests

* Add MinuteOfHourRule and MinuteOfHourStrategy classes with corresponding tests

* cleaned up unused code

* Refactor RuleSerialization methods to remove unused parameters and improve clarity.

* Enhance error handling in StrategySerialization by adding a try-catch block for Integer parsing, returning 0 on failure. Clean up unused imports in StrategySerializationTest for improved code clarity.

* Enhance StrategySerialization to use fully qualified names for strategies outside the core package.

* Improve error handling in RuleSerialization by adding try-catch blocks for numeric parsing, throwing IllegalArgumentException on failure for better debugging and clarity.

* Update AGENTS.md to clarify unit test requirements and add CHANGELOG.md documentation guidelines

* Refactor RuleSerialization to simplify match finding logic by removing unnecessary type param and improving lambda expressions for clarity.

* Refactor ComponentDescriptor by consolidating static methods for creating descriptors and improving code clarity. Remove redundant method definitions and enhance the toString implementation for better JSON serialization.

* ComponentDescriptor toString method

* Update LICENSE header path in pom.xml to use multi-module project directory variable for improved portability.

* Enhance AGENTS.md and run-full-build-quiet.sh script for improved Windows compatibility and logging. Added instructions for running scripts in Git Bash/MSYS and updated log file handling to support native paths on Windows.

* Consolidate code formatter configuration to single file at Ta4j parent root

* Update AGENTS.md to enforce mandatory build and test workflow, ensuring all code changes are validated before completion. Remove outdated rule files from .aiassistant and .cursor directories to streamline the documentation.

* Refine AGENTS.md instructions project-wide

* Enhance logging in CsvBarsLoader to handle empty series gracefully, adding a warning message when no bars are loaded from the CSV file.

* Enhance BinaryOperationIndicator to validate inputs, ensuring non-null operators and indicators share the same BarSeries. Update UnaryOperationIndicator to improve log method implementation and adjust getCountOfUnstableBars. Refactor IndicatorSerialization to handle circular references gracefully during serialization. Add tests for BinaryOperationIndicator to verify input validation and exception handling. Update CsvBarsLoader and related examples to use a more generic method for loading bar series.

* Refactor ChartMouseoverListener constructor in SwingChartDisplayer to remove unnecessary chart parameter. Update related tests to reflect the changes in listener instantiation.

* Refactor findDataFromCoordinates method in SwingChartDisplayer to remove unnecessary x-coordinate parameter, simplifying the method signature and improving code clarity.

* Refactor SwingChartDisplayer to remove ChartPanel dependency from ChartMouseoverListener, simplifying its constructor. Update related tests to reflect the changes in listener instantiation.

* Remove headless environment system property from pom.xml. Update AGENTS.md with instructions for handling headless environments in unit tests. Modify tests in SwingChartDisplayerTest and various strategy tests to use JUnit's Assume for headless environment checks.

* Enhance Strategy and AndRule classes with improved null checks and error handling. Update documentation for fromJson method in Strategy to clarify parameter requirements and exceptions. Add tests for BinaryOperationIndicator to handle division by zero scenarios and validate unstable bars in sum operations. Refactor NamedStrategyFixture to include a flag for counting typed constructions.

* Improve error handling in IndicatorSerialization by throwing an IllegalStateException when no ClassLoader is available, enhancing robustness during indicator type cache initialization.

* Refactor NamedStrategy class to improve parameter validation in buildLabel method, ensuring parameters do not contain underscores. Introduce unit tests for NamedStrategy to validate behavior with invalid parameters and ensure proper handling of null values. Additionally, clean up imports and enhance documentation for clarity.

* Update UnaryOperationIndicator to return 0 for unstable bars count and modify tests to use MockIndicator. Enhance MockIndicator with convenience constructor allowing Num varrary

* Refactor IndicatorSerialization to improve constructor selection logic, ensuring preference for constructors that consume all components. Introduce new test indicator for validation and add unit tests to verify serialization behavior. Update AGENTS.md for Windows build instructions clarity.

* Enhance AGENTS.md with unit testing best practices, including guidelines on reflection, exception testing, and dependency injection. Update IndicatorSerialization to handle null components gracefully and add a test for deserializing indicators with no components, ensuring robust behavior. Improve existing tests for clarity and coverage.

* Enhance serialization and deserialization processes for indicators and rules. Introduce IndicatorSerializationException for better error handling during serialization failures. Improve documentation for JSON methods in Indicator and Strategy classes, detailing exceptions and expected behaviors. Update tests to validate nested component extraction in rules and ensure robust handling of null values in serialization. Refactor existing tests for clarity and coverage.

* Consolidate rule serialization tests

* Enhance ChartMaker functionality by introducing a builder pattern for fluent chart construction. Update strategies to utilize the new builder for creating and saving charts. Add tests for the builder to ensure proper functionality and handle trading records effectively. Update .gitignore to include .jpg files.

* Refactor ProgressCompletion to improve null callback handling in withTotalStrategies method. Update documentation to clarify behavior for logging callbacks and enforce non-null callback requirement. Modify tests to reflect changes in exception handling.

* Add AnalysisCriterionIndicator for visualizing analysis criteria over time. Remove deprecated AnalysisDataSet and AnalysisType classes, and update ChartBuilder to support analysis criteria. Refactor tests to align with new charting capabilities and remove obsolete tests related to removed classes.

* Remove unused imports from MACDVIndicator and StopLossRule classes. Add unit tests for AnalysisCriterionIndicator to validate its functionality and ensure proper handling of null values and trading records.

* Refactor charting components to enhance usability and maintainability. Introduce explicit imports for charting dependencies in AGENTS.md. Update AnalysisCriterionIndicator to derive a label from the criterion and improve its toString method. Remove the deprecated ChartHandle class and streamline ChartBuilder functionality. Enhance TradingChartFactory with improved axis configuration and support for multiple analysis criteria overlays. Update tests to validate new charting capabilities and ensure proper handling of indicators and trading records.

* consolidated and refactored charting classes and api

* Refactor charting components by replacing ChartMaker with ChartWorkflow for improved usability.

* Refactor TradingChartFactory by removing unused methods and imports to streamline chart creation. Enhance code clarity and maintainability while ensuring support for multiple analysis criteria overlays.

* Refactor TradingChartFactory to simplify createCombinedPlot method by removing the subplotCount parameter, enhancing code clarity and maintainability.

* Add commons-math3 dependency and implement serialization support for various rules

- Added commons-math3 version 3.6.1 to pom.xml and ta4j-core/pom.xml.
- Introduced RuleSerializationException for handling serialization failures.
- Updated RuleSerialization to check for serialization support and provide detailed error messages.
- Added TODO comments in several rule classes to indicate the need for serialization support.
- Implemented placeholder tests for serialization/deserialization in multiple rule test classes, ensuring they can be skipped if serialization is not yet supported.

* - Updated remaining rules with serialization support.
- Refactored constructors to initialize stop gain/loss thresholds using dedicated methods for clarity.
- Enhanced HourOfDayRule and MinuteOfHourRule to include validation for hour and minute arrays, respectively.

* Remove TODO comments related to serialization support in BooleanIndicatorRule and its test class, as the implementation is pending. This cleanup prepares the code for future serialization enhancements.

---------

Co-authored-by: David Pang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant