tradai.common.entities¶
Domain entities using Pydantic for validation and immutability.
TradAI common entities.
This module provides all shared entity classes used across the TradAI platform. All entities are Pydantic models with frozen=True for immutability.
Submodules: - aws: AWS-related entities (S3Path, AWSConfig, JobStatus) - backtest: Backtesting entities (BacktestConfig, BacktestResult, BacktestJobStatus) - config_version: Config versioning entities (ConfigVersion, ConfigVersionStatus) - deployment: Deployment entities (DeploymentRecord, DeploymentStatus) - exchange: Exchange entities (ExchangeConfig, TradingMode, AuthType, OperatingMode) - hyperopt: Hyperparameter optimization entities (OptunaHyperoptConfig, TrialResult) - mlflow: MLflow entities (ModelVersion, ExperimentRun, RegisteredModel) - retraining: Retraining workflow entities (RetrainingState, RetrainingTrigger) - strategy: Strategy entity (Strategy) - trading_state: Trading state entities (TradingState, TradingStatus, StrategyPnL)
Example
from tradai.common.entities import BacktestConfig, ExchangeConfig config = BacktestConfig(strategy_name="PascalStrategy", ...)
ExchangeConfig ¶
Bases: BaseModel
Configuration for a CCXT exchange connection.
Supports both CEX (API key/secret) and DEX (private key) authentication. Uses TradingMode enum for market type. Provides ccxt_types property for CCXT market filtering.
Example
CEX (Binance)¶
config = ExchangeConfig(name="binance", trading_mode=TradingMode.FUTURES) config.key 'binance_futures'
DEX (Hyperliquid)¶
config = ExchangeConfig( ... name="hyperliquid", ... auth_type=AuthType.PRIVATE_KEY, ... private_key=SecretStr("0x..."), ... )
From Secrets Manager¶
config = ExchangeConfig.from_secret("tradai/prod/exchange/binance")
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | |
key: str property ¶
Return dict key for this exchange (e.g., 'binance_futures').
ccxt_types: frozenset[str] property ¶
Get CCXT market types for filtering.
is_authenticated: bool property ¶
Check if credentials are present for authentication.
Returns:
| Type | Description |
|---|---|
bool | True if required credentials are set. |
from_secret(secret_name: str, name: str | None = None, trading_mode: TradingMode = TradingMode.FUTURES, client: Any = None) -> ExchangeConfig classmethod ¶
Load credentials from AWS Secrets Manager.
Expected secret format for CEX:
Expected secret format for DEX:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret_name | str | Name or ARN of the secret in Secrets Manager | required |
name | str | None | Exchange name (optional, can be in secret as "exchange_name") | None |
trading_mode | TradingMode | Trading mode (default: FUTURES) | FUTURES |
client | Any | Optional Secrets Manager client for testing | None |
Returns:
| Type | Description |
|---|---|
ExchangeConfig | ExchangeConfig instance |
Raises:
| Type | Description |
|---|---|
ExternalServiceError | If secret retrieval fails |
ValidationError | If secret format is invalid |
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
to_ccxt_config() -> dict[str, str] ¶
Convert credentials to CCXT configuration format.
Returns:
| Type | Description |
|---|---|
dict[str, str] | Dictionary suitable for CCXT exchange initialization. |
Example
config = ExchangeConfig(name="binance", api_key=SecretStr("key"), ...) ccxt_config = config.to_ccxt_config() exchange = ccxt.binance(ccxt_config)
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
validate_credentials(timeout: int = 10) -> None ¶
Validate exchange credentials by making an authenticated API call.
Uses fetch_balance() as the validation method - it's lightweight and requires authentication on all exchanges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout | int | Request timeout in seconds | 10 |
Raises:
| Type | Description |
|---|---|
AuthenticationError | If credentials are invalid or missing |
ExternalServiceError | If exchange API call fails for other reasons |
Example
config = ExchangeConfig.from_secret("tradai/prod/binance") config.validate_credentials() # Raises if invalid
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
validate_name(v: str) -> str classmethod ¶
Normalize exchange name to lowercase.
parse_trading_mode(v: str | TradingMode) -> TradingMode classmethod ¶
Parse trading mode from string or TradingMode enum.
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
BacktestConfig ¶
Bases: BaseModel
Backtest configuration with validation.
Defines all parameters needed to run a backtest. Validates symbols use proper trading pair format and date range is valid.
Attributes:
| Name | Type | Description |
|---|---|---|
strategy | str | Strategy name to backtest |
timeframe | str | Trading timeframe (e.g., "1h", "4h", "1d") |
start_date | str | Start date in YYYY-MM-DD format |
end_date | str | End date in YYYY-MM-DD format |
symbols | list[str] | List of trading pairs |
stoploss | float | None | Optional stoploss percentage (-1.0 to 0.0) |
stake_amount | float | Position size in stake currency |
exchange | str | Exchange key (e.g., "binance_futures") |
strategy_version | str | MLflow version specifier ("latest", stage name, or number) |
config_version_id | str | None | Optional ConfigVersion ID for reproducibility |
Example
config = BacktestConfig( ... strategy="PascalStrategy", ... timeframe="1h", ... start_date="2024-01-01", ... end_date="2024-06-30", ... symbols=["BTC/USDT:USDT", "ETH/USDT:USDT"], ... exchange="binance_futures", ... strategy_version="Production", ... )
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
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 | |
validate_date_is_real(v: str) -> str classmethod ¶
Validate date string represents an actual calendar date (C6).
The pattern regex only checks format (YYYY-MM-DD), not validity. This validator catches impossible dates like 2024-02-30 or 2024-13-01.
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
validate_strategy_version(v: str) -> str classmethod ¶
Validate strategy_version format.
Valid formats: - "latest" - resolve to highest version number - "Production", "Staging", "Archived", "None" - resolve by MLflow stage - Numeric string like "1", "2", "3" - specific version number
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
validate_symbols_format(v: list[str]) -> list[str] classmethod ¶
Validate all symbols use proper trading pair format.
Uses validate_trading_pair to ensure format like BTC/USDT or BTC/USDT:USDT. Prevents command injection and normalizes to uppercase.
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
validate_date_range() -> BacktestConfig ¶
Ensure end_date is not before start_date.
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
BacktestResult ¶
Bases: BaseModel
Backtest execution result.
Contains complete metrics and trades from a Freqtrade backtest. Includes all key ratios: Sharpe, Sortino, Calmar, SQN, etc. Additional metrics stored in the metrics dict for MLflow logging.
Attributes:
| Name | Type | Description |
|---|---|---|
total_trades | int | Total number of trades executed |
winning_trades | int | Number of profitable trades |
losing_trades | int | Number of losing trades |
draw_trades | int | Number of break-even trades |
total_profit | float | Total profit in stake currency |
total_profit_pct | float | Total profit as percentage |
profit_factor | float | None | Ratio of gross profit to gross loss |
sharpe_ratio | float | None | Risk-adjusted return metric |
sortino_ratio | float | None | Downside risk-adjusted return |
calmar_ratio | float | None | Return over max drawdown |
sqn | float | None | System Quality Number |
cagr | float | None | Compound Annual Growth Rate |
max_drawdown | float | None | Maximum drawdown in stake currency |
max_drawdown_pct | float | None | Maximum drawdown as percentage |
win_rate | float | None | Percentage of winning trades |
metrics | dict[str, float] | Additional custom metrics |
trades | list[dict[str, Any]] | Raw trade data (limited) |
raw_stats | dict[str, Any] | Full raw stats from Freqtrade |
mlflow_run_id | str | None | MLflow run ID for traceability |
config_artifact_uri | str | None | URI of config artifact in MLflow |
results_artifact_uri | str | None | S3 URI of results file |
job_id | str | None | DynamoDB job ID for reverse lookup |
git_commit | str | None | Git commit SHA for reproducibility |
resolved_strategy_version | str | None | Resolved MLflow version number |
config_version_id | str | None | ConfigVersion ID used for this backtest |
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
validate_winning_trades(v: int, info: Any) -> int classmethod ¶
Ensure winning trades <= total trades.
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
validate_git_commit(v: str | None) -> str | None classmethod ¶
Validate git commit SHA format (P1.3).
Accepts: - None (no git info available) - "unknown" (not in a git repository) - 7-char short SHA (e.g., "abc1234") - 40-char full SHA (e.g., "abc1234567890...")
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
from_mlflow_metrics(metrics: dict[str, float], mlflow_run_id: str, config_artifact_uri: str | None = None) -> BacktestResult classmethod ¶
Create BacktestResult from MLflow run metrics dict.
Extracts standard metric keys from MLflow's flat metrics dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics | dict[str, float] | MLflow run metrics (e.g., run.data.metrics) | required |
mlflow_run_id | str | MLflow run ID for traceability | required |
config_artifact_uri | str | None | Optional URI of config artifact | None |
Returns:
| Type | Description |
|---|---|
BacktestResult | BacktestResult with metrics populated from the dict |
Example
run = mlflow_client.get_run(run_id) result = BacktestResult.from_mlflow_metrics( ... run.data.metrics, run_id ... )
Source code in libs/tradai-common/src/tradai/common/entities/backtest.py
AWSConfig ¶
Bases: BaseModel
AWS infrastructure configuration.
All values loaded from environment variables - no hardcoded infrastructure IDs.
Attributes:
| Name | Type | Description |
|---|---|---|
region | str | AWS region (e.g., "us-east-1") |
account_id | str | 12-digit AWS account ID |
execution_role_arn | str | IAM role ARN for task execution |
task_role_arn | str | IAM role ARN for task |
ecs_cluster | str | ECS cluster name |
subnets | list[str] | List of subnet IDs |
security_groups | list[str] | List of security group IDs |
Example
config = AWSConfig( ... region="us-east-1", ... account_id="123456789012", ... execution_role_arn="arn:aws:iam::123456789012:role/ecsTaskExecutionRole", ... task_role_arn="arn:aws:iam::123456789012:role/ecsTaskRole", ... ecs_cluster="tradai-cluster", ... subnets=["subnet-abc123"], ... security_groups=["sg-xyz789"], ... )
Source code in libs/tradai-common/src/tradai/common/entities/aws.py
validate_subnets(v: list[str]) -> list[str] classmethod ¶
Validate subnet IDs format.
Source code in libs/tradai-common/src/tradai/common/entities/aws.py
validate_security_groups(v: list[str]) -> list[str] classmethod ¶
Validate security group IDs format.
Source code in libs/tradai-common/src/tradai/common/entities/aws.py
S3Path ¶
Bases: BaseModel
Parsed S3 path with validation.
Immutable representation of an S3 URI.
Attributes:
| Name | Type | Description |
|---|---|---|
bucket | str | S3 bucket name (3-63 characters) |
key | str | S3 object key |
Example
path = S3Path.parse("s3://my-bucket/path/to/file.json") path.bucket 'my-bucket' path.key 'path/to/file.json' str(path) 's3://my-bucket/path/to/file.json'
Source code in libs/tradai-common/src/tradai/common/entities/aws.py
parse(uri: str) -> S3Path classmethod ¶
Parse S3 URI into bucket and key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri | str | S3 URI (e.g., "s3://bucket/key/path") | required |
Returns:
| Type | Description |
|---|---|
S3Path | S3Path instance |
Raises:
| Type | Description |
|---|---|
ValueError | If URI format is invalid |
Source code in libs/tradai-common/src/tradai/common/entities/aws.py
TradingMode ¶
Bases: str, Enum
Trading mode enum compatible with Freqtrade's TradingMode.
Defines market types for exchange connections: - SPOT: Spot trading markets - MARGIN: Margin trading markets - FUTURES: Futures markets (perpetual swaps and delivery)
Maps to CCXT market types via ccxt_types property.
Example
mode = TradingMode.FUTURES mode.value 'futures' mode.ccxt_types frozenset({'swap', 'future'})
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
ccxt_types: frozenset[str] property ¶
Get CCXT market types for filtering.
Returns:
| Type | Description |
|---|---|
frozenset[str] | Set of CCXT type strings for this trading mode |
from_string(value: str) -> TradingMode classmethod ¶
Parse trading mode from string (case-insensitive).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | str | Trading mode string ('spot', 'margin', 'futures') | required |
Returns:
| Type | Description |
|---|---|
TradingMode | TradingMode enum value |
Raises:
| Type | Description |
|---|---|
ValueError | If value is not a valid trading mode |
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
AuthType ¶
Bases: str, Enum
Authentication type for exchange connections.
CEX (Centralized Exchange): Uses API key/secret authentication. DEX (Decentralized Exchange): Uses private key signing (EVM wallet).
Example
auth_type = AuthType.API_KEY # For Binance, Kraken auth_type = AuthType.PRIVATE_KEY # For Hyperliquid
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
OperatingMode ¶
Bases: str, Enum
Operating mode for strategy deployment.
Defines whether a deployed strategy runs with real or simulated trading: - LIVE: Real trading with actual funds - DRY_RUN: Paper trading simulation (no real orders)
Distinct from TradingMode (market type) and used for deployment tracking.
Example
mode = OperatingMode.DRY_RUN mode.value 'dry-run' mode.is_paper_trading True
Source code in libs/tradai-common/src/tradai/common/entities/exchange.py
is_paper_trading: bool property ¶
Check if this mode uses paper trading (no real orders).
from_string(value: str) -> OperatingMode classmethod ¶
Parse operating mode from string (case-insensitive).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | str | Operating mode string ('live', 'dry-run', 'dry_run') | required |
Returns:
| Type | Description |
|---|---|
OperatingMode | OperatingMode enum value |
Raises:
| Type | Description |
|---|---|
ValueError | If value is not a valid operating mode |