Vasily.onl d71cb763bc 3.4 - 3.0 Strategy Configuration System
Implement comprehensive chart configuration and validation system

- Introduced a modular chart configuration system in `components/charts/config/` to manage indicator definitions, default configurations, and strategy-specific setups.
- Added new modules for error handling and validation, enhancing user guidance and error reporting capabilities.
- Implemented detailed schema validation for indicators and strategies, ensuring robust configuration management.
- Created example strategies and default configurations to facilitate user onboarding and usage.
- Enhanced documentation to provide clear guidelines on the configuration system, validation rules, and usage examples.
- Added unit tests for all new components to ensure functionality and reliability across the configuration system.
2025-06-03 14:33:25 +08:00

460 lines
15 KiB
Python

"""
Default Indicator Configurations and Parameters
This module provides comprehensive default indicator configurations
organized by categories, trading strategies, and common use cases.
"""
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
from enum import Enum
from .indicator_defs import ChartIndicatorConfig, create_indicator_config, IndicatorType
class IndicatorCategory(str, Enum):
"""Categories for organizing indicators."""
TREND = "trend"
MOMENTUM = "momentum"
VOLATILITY = "volatility"
VOLUME = "volume"
SUPPORT_RESISTANCE = "support_resistance"
class TradingStrategy(str, Enum):
"""Common trading strategy types."""
SCALPING = "scalping"
DAY_TRADING = "day_trading"
SWING_TRADING = "swing_trading"
POSITION_TRADING = "position_trading"
MOMENTUM = "momentum"
MEAN_REVERSION = "mean_reversion"
@dataclass
class IndicatorPreset:
"""
Predefined indicator configuration preset.
"""
name: str
description: str
category: IndicatorCategory
recommended_timeframes: List[str]
config: ChartIndicatorConfig
# Color schemes for different indicator categories
CATEGORY_COLORS = {
IndicatorCategory.TREND: {
'primary': '#007bff', # Blue
'secondary': '#28a745', # Green
'tertiary': '#17a2b8', # Cyan
'quaternary': '#6c757d' # Gray
},
IndicatorCategory.MOMENTUM: {
'primary': '#dc3545', # Red
'secondary': '#fd7e14', # Orange
'tertiary': '#e83e8c', # Pink
'quaternary': '#6f42c1' # Purple
},
IndicatorCategory.VOLATILITY: {
'primary': '#6f42c1', # Purple
'secondary': '#e83e8c', # Pink
'tertiary': '#20c997', # Teal
'quaternary': '#ffc107' # Yellow
}
}
def create_trend_indicators() -> Dict[str, IndicatorPreset]:
"""Create default trend indicator configurations."""
trend_indicators = {}
# Simple Moving Averages
sma_configs = [
(5, "Very Short Term", ['1m', '5m']),
(10, "Short Term", ['5m', '15m']),
(20, "Short-Medium Term", ['15m', '1h']),
(50, "Medium Term", ['1h', '4h']),
(100, "Long Term", ['4h', '1d']),
(200, "Very Long Term", ['1d', '1w'])
]
for period, desc, timeframes in sma_configs:
config, _ = create_indicator_config(
name=f"SMA ({period})",
indicator_type="sma",
parameters={"period": period},
color=CATEGORY_COLORS[IndicatorCategory.TREND]['primary'] if period <= 20 else
CATEGORY_COLORS[IndicatorCategory.TREND]['secondary'] if period <= 50 else
CATEGORY_COLORS[IndicatorCategory.TREND]['tertiary'],
line_width=2 if period <= 50 else 3
)
trend_indicators[f"sma_{period}"] = IndicatorPreset(
name=f"SMA {period}",
description=f"{desc} Simple Moving Average - {period} periods",
category=IndicatorCategory.TREND,
recommended_timeframes=timeframes,
config=config
)
# Exponential Moving Averages
ema_configs = [
(5, "Very Short Term", ['1m', '5m']),
(12, "Short Term (MACD Fast)", ['5m', '15m', '1h']),
(21, "Fibonacci Short Term", ['15m', '1h']),
(26, "Medium Term (MACD Slow)", ['1h', '4h']),
(50, "Medium-Long Term", ['4h', '1d']),
(100, "Long Term", ['1d', '1w']),
(200, "Very Long Term", ['1d', '1w'])
]
for period, desc, timeframes in ema_configs:
config, _ = create_indicator_config(
name=f"EMA ({period})",
indicator_type="ema",
parameters={"period": period},
color=CATEGORY_COLORS[IndicatorCategory.TREND]['secondary'] if period <= 21 else
CATEGORY_COLORS[IndicatorCategory.TREND]['tertiary'] if period <= 50 else
CATEGORY_COLORS[IndicatorCategory.TREND]['quaternary'],
line_width=2,
line_style='dash' if period in [12, 26] else 'solid'
)
trend_indicators[f"ema_{period}"] = IndicatorPreset(
name=f"EMA {period}",
description=f"{desc} Exponential Moving Average - {period} periods",
category=IndicatorCategory.TREND,
recommended_timeframes=timeframes,
config=config
)
return trend_indicators
def create_momentum_indicators() -> Dict[str, IndicatorPreset]:
"""Create default momentum indicator configurations."""
momentum_indicators = {}
# RSI configurations
rsi_configs = [
(7, "Fast RSI", ['1m', '5m', '15m']),
(14, "Standard RSI", ['15m', '1h', '4h']),
(21, "Slow RSI", ['1h', '4h', '1d']),
(30, "Very Slow RSI", ['4h', '1d', '1w'])
]
for period, desc, timeframes in rsi_configs:
config, _ = create_indicator_config(
name=f"RSI ({period})",
indicator_type="rsi",
parameters={"period": period},
color=CATEGORY_COLORS[IndicatorCategory.MOMENTUM]['primary'] if period == 14 else
CATEGORY_COLORS[IndicatorCategory.MOMENTUM]['secondary'],
line_width=2,
subplot_height_ratio=0.25
)
momentum_indicators[f"rsi_{period}"] = IndicatorPreset(
name=f"RSI {period}",
description=f"{desc} - Relative Strength Index with {period} periods",
category=IndicatorCategory.MOMENTUM,
recommended_timeframes=timeframes,
config=config
)
# MACD configurations
macd_configs = [
((5, 13, 4), "Fast MACD", ['1m', '5m']),
((8, 17, 6), "Scalping MACD", ['5m', '15m']),
((12, 26, 9), "Standard MACD", ['15m', '1h', '4h']),
((19, 39, 13), "Slow MACD", ['1h', '4h', '1d']),
((26, 52, 18), "Very Slow MACD", ['4h', '1d', '1w'])
]
for (fast, slow, signal), desc, timeframes in macd_configs:
config, _ = create_indicator_config(
name=f"MACD ({fast},{slow},{signal})",
indicator_type="macd",
parameters={
"fast_period": fast,
"slow_period": slow,
"signal_period": signal
},
color=CATEGORY_COLORS[IndicatorCategory.MOMENTUM]['secondary'] if (fast, slow, signal) == (12, 26, 9) else
CATEGORY_COLORS[IndicatorCategory.MOMENTUM]['tertiary'],
line_width=2,
subplot_height_ratio=0.3
)
momentum_indicators[f"macd_{fast}_{slow}_{signal}"] = IndicatorPreset(
name=f"MACD {fast}/{slow}/{signal}",
description=f"{desc} - MACD with {fast}/{slow}/{signal} periods",
category=IndicatorCategory.MOMENTUM,
recommended_timeframes=timeframes,
config=config
)
return momentum_indicators
def create_volatility_indicators() -> Dict[str, IndicatorPreset]:
"""Create default volatility indicator configurations."""
volatility_indicators = {}
# Bollinger Bands configurations
bb_configs = [
((10, 1.5), "Tight Bollinger Bands", ['1m', '5m']),
((20, 2.0), "Standard Bollinger Bands", ['15m', '1h', '4h']),
((20, 2.5), "Wide Bollinger Bands", ['1h', '4h']),
((50, 2.0), "Long-term Bollinger Bands", ['4h', '1d', '1w'])
]
for (period, std_dev), desc, timeframes in bb_configs:
config, _ = create_indicator_config(
name=f"BB ({period}, {std_dev})",
indicator_type="bollinger_bands",
parameters={"period": period, "std_dev": std_dev},
color=CATEGORY_COLORS[IndicatorCategory.VOLATILITY]['primary'] if (period, std_dev) == (20, 2.0) else
CATEGORY_COLORS[IndicatorCategory.VOLATILITY]['secondary'],
line_width=1,
opacity=0.7
)
volatility_indicators[f"bb_{period}_{int(std_dev*10)}"] = IndicatorPreset(
name=f"Bollinger Bands {period}/{std_dev}",
description=f"{desc} - {period} period with {std_dev} standard deviations",
category=IndicatorCategory.VOLATILITY,
recommended_timeframes=timeframes,
config=config
)
return volatility_indicators
def create_strategy_presets() -> Dict[str, Dict[str, List[str]]]:
"""Create predefined indicator combinations for common trading strategies."""
strategy_presets = {
TradingStrategy.SCALPING.value: {
"name": "Scalping Strategy",
"description": "Fast indicators for 1-5 minute scalping",
"timeframes": ["1m", "5m"],
"indicators": [
"ema_5", "ema_12", "ema_21",
"rsi_7", "macd_5_13_4",
"bb_10_15"
]
},
TradingStrategy.DAY_TRADING.value: {
"name": "Day Trading Strategy",
"description": "Balanced indicators for intraday trading",
"timeframes": ["5m", "15m", "1h"],
"indicators": [
"sma_20", "ema_12", "ema_26",
"rsi_14", "macd_12_26_9",
"bb_20_20"
]
},
TradingStrategy.SWING_TRADING.value: {
"name": "Swing Trading Strategy",
"description": "Medium-term indicators for swing trading",
"timeframes": ["1h", "4h", "1d"],
"indicators": [
"sma_50", "ema_21", "ema_50",
"rsi_14", "rsi_21", "macd_12_26_9",
"bb_20_20"
]
},
TradingStrategy.POSITION_TRADING.value: {
"name": "Position Trading Strategy",
"description": "Long-term indicators for position trading",
"timeframes": ["4h", "1d", "1w"],
"indicators": [
"sma_100", "sma_200", "ema_50", "ema_100",
"rsi_21", "macd_19_39_13",
"bb_50_20"
]
},
TradingStrategy.MOMENTUM.value: {
"name": "Momentum Strategy",
"description": "Momentum-focused indicators",
"timeframes": ["15m", "1h", "4h"],
"indicators": [
"ema_12", "ema_26",
"rsi_7", "rsi_14", "macd_8_17_6", "macd_12_26_9"
]
},
TradingStrategy.MEAN_REVERSION.value: {
"name": "Mean Reversion Strategy",
"description": "Indicators for mean reversion trading",
"timeframes": ["15m", "1h", "4h"],
"indicators": [
"sma_20", "sma_50", "bb_20_20", "bb_20_25",
"rsi_14", "rsi_21"
]
}
}
return strategy_presets
def get_all_default_indicators() -> Dict[str, IndicatorPreset]:
"""
Get all default indicator configurations.
Returns:
Dictionary mapping indicator names to their preset configurations
"""
all_indicators = {}
# Combine all indicator categories
all_indicators.update(create_trend_indicators())
all_indicators.update(create_momentum_indicators())
all_indicators.update(create_volatility_indicators())
return all_indicators
def get_indicators_by_category(category: IndicatorCategory) -> Dict[str, IndicatorPreset]:
"""
Get default indicators filtered by category.
Args:
category: Indicator category to filter by
Returns:
Dictionary of indicators in the specified category
"""
all_indicators = get_all_default_indicators()
return {name: preset for name, preset in all_indicators.items()
if preset.category == category}
def get_indicators_for_timeframe(timeframe: str) -> Dict[str, IndicatorPreset]:
"""
Get indicators recommended for a specific timeframe.
Args:
timeframe: Timeframe string (e.g., '1m', '5m', '1h', '4h', '1d')
Returns:
Dictionary of indicators suitable for the timeframe
"""
all_indicators = get_all_default_indicators()
return {name: preset for name, preset in all_indicators.items()
if timeframe in preset.recommended_timeframes}
def get_strategy_indicators(strategy: TradingStrategy) -> List[str]:
"""
Get indicator names for a specific trading strategy.
Args:
strategy: Trading strategy type
Returns:
List of indicator names for the strategy
"""
presets = create_strategy_presets()
strategy_config = presets.get(strategy.value, {})
return strategy_config.get("indicators", [])
def get_strategy_info(strategy: TradingStrategy) -> Dict[str, Any]:
"""
Get complete information about a trading strategy.
Args:
strategy: Trading strategy type
Returns:
Dictionary with strategy details including indicators and timeframes
"""
presets = create_strategy_presets()
return presets.get(strategy.value, {})
def create_custom_preset(
name: str,
description: str,
category: IndicatorCategory,
indicator_configs: List[Dict[str, Any]],
recommended_timeframes: Optional[List[str]] = None
) -> Dict[str, IndicatorPreset]:
"""
Create custom indicator presets.
Args:
name: Preset name
description: Preset description
category: Indicator category
indicator_configs: List of indicator configuration dictionaries
recommended_timeframes: Optional list of recommended timeframes
Returns:
Dictionary of created indicator presets
"""
custom_presets = {}
for i, config_data in enumerate(indicator_configs):
try:
config, errors = create_indicator_config(**config_data)
if errors:
continue
preset_name = f"{name.lower().replace(' ', '_')}_{i}"
custom_presets[preset_name] = IndicatorPreset(
name=f"{name} {i+1}",
description=description,
category=category,
recommended_timeframes=recommended_timeframes or ["15m", "1h", "4h"],
config=config
)
except Exception:
continue
return custom_presets
def get_available_strategies() -> List[Dict[str, str]]:
"""
Get list of available trading strategies.
Returns:
List of dictionaries with strategy information
"""
presets = create_strategy_presets()
return [
{
"value": strategy,
"name": info["name"],
"description": info["description"],
"timeframes": ", ".join(info["timeframes"])
}
for strategy, info in presets.items()
]
def get_available_categories() -> List[Dict[str, str]]:
"""
Get list of available indicator categories.
Returns:
List of dictionaries with category information
"""
return [
{
"value": category.value,
"name": category.value.replace("_", " ").title(),
"description": f"Indicators for {category.value.replace('_', ' ')} analysis"
}
for category in IndicatorCategory
]