Strategy Entities¶
Auto-generated API reference for tradai.strategy framework.
Base Class¶
tradai.strategy.base.TradAIStrategy ¶
Bases: IStrategy, StrategyDebugMixin
TradAI strategy base class.
Note: Includes pickle support for hyperopt multiprocessing. See: https://github.com/freqtrade/freqtrade/issues/10287
All TradAI strategies must extend this class and implement: 1. get_metadata() - Return StrategyMetadata (REQUIRED) 2. populate_indicators() - Calculate indicators (Freqtrade REQUIRED) 3. populate_entry_trend() - Define entry signals (Freqtrade REQUIRED) 4. populate_exit_trend() - Define exit signals (Freqtrade REQUIRED)
Optional methods with default implementations: - validate_configuration() - Custom config validation - get_test_config() - Test configuration parameters
Debug methods (from StrategyDebugMixin): - check_nan_indicators(df, pair) - Detect NaN in indicator columns - print_indicator_summary(df, pair) - Print indicator values for latest candle
All Freqtrade IStrategy methods remain available: - custom_stoploss(), custom_exit(), leverage() - confirm_trade_entry(), confirm_trade_exit() - bot_start(), bot_loop_start() - And all other IStrategy lifecycle hooks
Example
class MyStrategy(TradAIStrategy): ... timeframe = '1h' ... stoploss = -0.08 ... ... def get_metadata(self): ... return StrategyMetadata( ... name="MyStrategy", ... version="1.0.0", ... description="My trading strategy", ... timeframe=self.timeframe, ... category=StrategyCategory.MEAN_REVERSION, ... tags=["macd", "rsi"] ... ) ... ... def populate_indicators(self, dataframe, metadata): ... # Calculate indicators using TA-Lib ... import talib ... dataframe['rsi'] = talib.RSI(dataframe['close']) ... # Debug: check for NaN (output when TRADAI_DEBUG=1) ... self.check_nan_indicators(dataframe, metadata.get('pair')) ... return dataframe ... ... def populate_entry_trend(self, dataframe, metadata): ... # Define entry logic ... dataframe.loc[dataframe['rsi'] < 30, 'enter_long'] = 1 ... return dataframe ... ... def populate_exit_trend(self, dataframe, metadata): ... # Define exit logic (or leave empty for stoploss-only) ... return dataframe
Source code in libs/tradai-strategy/src/tradai/strategy/base.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
get_metadata() -> StrategyMetadata abstractmethod ¶
Return strategy metadata (REQUIRED).
This method must be implemented by all TradAI strategies. Metadata is used for: - Strategy registration in MLflow - Docker image labels - Strategy discovery/listing - Documentation generation
Returns:
| Name | Type | Description |
|---|---|---|
StrategyMetadata | StrategyMetadata | Pydantic model with strategy information |
Example
def get_metadata(self): ... return StrategyMetadata( ... name="PascalStrategyV2", ... version="2.0.0", ... description="MACD mean reversion with RSI filter", ... timeframe=self.timeframe, ... can_short=self.can_short, ... category=StrategyCategory.MEAN_REVERSION, ... tags=["macd", "rsi", "mean-reversion"], ... parameters={ ... "macd_fast": self.macd_fast, ... "macd_slow": self.macd_slow, ... } ... )
Source code in libs/tradai-strategy/src/tradai/strategy/base.py
validate_configuration(config: dict[str, Any]) -> bool ¶
Validate strategy-specific configuration (optional).
Override this method to add custom validation logic for your strategy. Called during strategy initialization to ensure config is valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | dict[str, Any] | Freqtrade configuration dictionary | required |
Returns:
| Name | Type | Description |
|---|---|---|
bool | bool | True if valid, raises exception if invalid |
Example
def validate_configuration(self, config): ... # Ensure ML model file exists ... ml_path = config.get('ml_preds_filepath') ... if ml_path and not os.path.exists(ml_path): ... raise ValueError(f"ML predictions file not found: {ml_path}") ... return True
Source code in libs/tradai-strategy/src/tradai/strategy/base.py
get_test_config() -> dict[str, Any] ¶
Return test configuration for unit/integration testing (optional).
Override this method to provide strategy-specific test parameters. Used by testing utilities to run automated tests on your strategy.
Returns:
| Name | Type | Description |
|---|---|---|
dict | dict[str, Any] | Test configuration with symbols, timerange, etc. |
Example
def get_test_config(self): ... return { ... "symbols": ["BTC/USDT:USDT", "ETH/USDT:USDT"], ... "timerange": "20230101-20230201", ... "timeframe": self.timeframe, ... "stake_amount": 1000, ... "dry_run": True, ... }
Source code in libs/tradai-strategy/src/tradai/strategy/base.py
Metadata¶
tradai.strategy.metadata.StrategyMetadata ¶
Bases: BaseModel
Standardized metadata for all TradAI strategies.
This model defines required and optional metadata fields that every TradAI strategy must provide via get_metadata() method.
Required Fields
name: Strategy class name (e.g., 'PascalStrategyV2') version: Semantic version (e.g., '2.0.0') description: Short description of strategy logic timeframe: Primary timeframe (e.g., '1h', '15m') category: Trading style category (enum)
Optional Fields
can_short: Supports short positions (default: False) tags: Searchable tags (default: []) author: Strategy author (default: 'TradAI Team') status: Lifecycle status (default: TESTING) parameters: Configurable parameters with defaults (default: {}) min_freqtrade_version: Minimum Freqtrade version required
Example
metadata = StrategyMetadata( ... name="PascalStrategyV2", ... version="2.0.0", ... description="MACD mean reversion with RSI filter", ... timeframe="1h", ... category=StrategyCategory.MEAN_REVERSION, ... can_short=True, ... tags=["macd", "rsi", "mean-reversion"] ... )
Source code in libs/tradai-strategy/src/tradai/strategy/metadata.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
validate_version(v: str) -> str classmethod ¶
Validate semantic versioning format (X.Y.Z).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v | str | Version string to validate | required |
Returns:
| Type | Description |
|---|---|
str | Validated version string |
Raises:
| Type | Description |
|---|---|
ValueError | If version doesn't match X.Y.Z format |
Source code in libs/tradai-strategy/src/tradai/strategy/metadata.py
validate_trading_modes(v: list[str]) -> list[str] classmethod ¶
Validate trading modes are valid values.
Valid modes: backtest, hyperopt, dry-run, live
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v | list[str] | List of trading mode strings | required |
Returns:
| Type | Description |
|---|---|
list[str] | Validated list of trading modes |
Raises:
| Type | Description |
|---|---|
ValueError | If any mode is not valid |
Source code in libs/tradai-strategy/src/tradai/strategy/metadata.py
validate_min_freqtrade_version(v: str | None) -> str | None classmethod ¶
Validate min_freqtrade_version is a valid version string.
Freqtrade uses versions like '2024.1', '2024.11' (YYYY.N format). The packaging.Version class can validate these formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v | str | None | Version string to validate | required |
Returns:
| Type | Description |
|---|---|
str | None | Validated version string or None |
Raises:
| Type | Description |
|---|---|
ValueError | If version string is invalid |
Source code in libs/tradai-strategy/src/tradai/strategy/metadata.py
to_mlflow_tags() -> list[dict[str, str]] ¶
Convert metadata to MLflow registry tags format.
Returns:
| Type | Description |
|---|---|
list[dict[str, str]] | List of tag dictionaries with 'key' and 'value' fields |
Example
tags = metadata.to_mlflow_tags() tags[0]
Source code in libs/tradai-strategy/src/tradai/strategy/metadata.py
to_docker_labels() -> dict[str, str] ¶
Convert metadata to Docker image labels format.
Uses 'tradai.' prefix for all labels.
Returns:
| Type | Description |
|---|---|
dict[str, str] | Dictionary of label key-value pairs |
Example
labels = metadata.to_docker_labels() labels['tradai.strategy.name'] 'PascalStrategyV2'
Source code in libs/tradai-strategy/src/tradai/strategy/metadata.py
Enums¶
tradai.strategy.enums.StrategyCategory ¶
Bases: str, Enum
Trading strategy category/style.
Source code in libs/tradai-strategy/src/tradai/strategy/enums.py
Validation¶
tradai.strategy.validation_entities.CheckSeverity ¶
Bases: str, Enum
Severity levels for validation checks.
Used across all validation systems (preflight, sanity, CI gate) to indicate the severity of issues found.
Attributes:
| Name | Type | Description |
|---|---|---|
ERROR | Critical issue that blocks execution/merge | |
WARNING | Issue that should be reviewed but doesn't block | |
INFO | Informational message, no action required |
Source code in libs/tradai-strategy/src/tradai/strategy/validation_entities.py
tradai.strategy.validation_entities.ValidationIssue ¶
Bases: BaseModel
Base class for all validation issues.
Provides common fields shared across preflight, sanity, and CI validation results. Specific validation systems extend this with additional fields.
Attributes:
| Name | Type | Description |
|---|---|---|
rule_id | str | Identifier for the validation rule that triggered |
severity | CheckSeverity | Severity level of the issue |
message | str | Human-readable description of the issue |
details | dict[str, Any] | Additional structured data about the issue |
Source code in libs/tradai-strategy/src/tradai/strategy/validation_entities.py
tradai.strategy.validation_entities.MetricValidationIssue ¶
Bases: ValidationIssue
Validation issue for metric threshold violations.
Extends ValidationIssue with fields specific to numeric metric checks, used by SanityWarning and CIViolation.
Attributes:
| Name | Type | Description |
|---|---|---|
actual_value | float | int | None | The actual metric value from backtest/validation |
threshold | float | int | The threshold that was exceeded/not met |
suggestion | str | Recommended action to investigate (optional) |
Source code in libs/tradai-strategy/src/tradai/strategy/validation_entities.py
format_comparison(comparison: str = 'vs') -> str ¶
Format the metric comparison for display.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comparison | str | Comparison word/symbol (e.g., 'vs', '>', '<') | 'vs' |
Returns:
| Type | Description |
|---|---|
str | Formatted string like "actual: 0.5 vs threshold: 1.0" |
Source code in libs/tradai-strategy/src/tradai/strategy/validation_entities.py
tradai.strategy.validation_entities.ValidationResultMixin ¶
Mixin providing common aggregation properties for validation results.
Add this mixin to validation result classes (PreflightResult, SanityCheckResult, CIValidationResult) to get consistent filtering and counting of issues.
The inheriting class must have an attribute issues: list[ValidationIssue] or override the _get_issues method.
Source code in libs/tradai-strategy/src/tradai/strategy/validation_entities.py
errors: list[ValidationIssue] property ¶
Get all ERROR-level issues.
warnings_only: list[ValidationIssue] property ¶
Get all WARNING-level issues (excluding errors).
error_count: int property ¶
Count of ERROR-level issues.
warning_count: int property ¶
Count of WARNING-level issues.
has_errors: bool property ¶
Check if there are any error-level issues.
has_warnings: bool property ¶
Check if there are any warning-level issues.