TCPDashboard/components/charts/config/example_strategies.py
2025-06-12 13:27:30 +08:00

651 lines
23 KiB
Python

"""
Example Strategy Configurations
This module provides real-world trading strategy configurations that demonstrate
how to combine indicators for specific trading approaches like EMA crossover,
momentum trading, and other popular strategies.
"""
from typing import Dict, List, Optional
from dataclasses import dataclass
from datetime import datetime
from .strategy_charts import (
StrategyChartConfig,
SubplotConfig,
ChartStyle,
ChartLayout,
SubplotType
)
from .defaults import TradingStrategy
from utils.logger import get_logger
# Initialize logger
logger = get_logger()
@dataclass
class StrategyExample:
"""Represents an example trading strategy with metadata."""
config: StrategyChartConfig
description: str
author: str = "TCPDashboard"
difficulty: str = "Beginner" # Beginner, Intermediate, Advanced
expected_return: Optional[str] = None
risk_level: str = "Medium" # Low, Medium, High
market_conditions: List[str] = None # Trending, Sideways, Volatile
notes: List[str] = None
references: List[str] = None
def __post_init__(self):
if self.market_conditions is None:
self.market_conditions = ["Trending"]
if self.notes is None:
self.notes = []
if self.references is None:
self.references = []
def create_ema_crossover_strategy() -> StrategyExample:
"""
Create EMA crossover strategy configuration.
Classic trend-following strategy using fast and slow EMA crossovers
for entry and exit signals.
"""
config = StrategyChartConfig(
strategy_name="EMA Crossover Strategy",
strategy_type=TradingStrategy.DAY_TRADING,
description="Trend-following strategy using EMA crossovers for entry/exit signals",
timeframes=["15m", "1h", "4h"],
layout=ChartLayout.MAIN_WITH_SUBPLOTS,
main_chart_height=0.65,
overlay_indicators=[
"ema_12", # Fast EMA
"ema_26", # Slow EMA
"ema_50", # Trend filter
"bb_20_20" # Bollinger Bands for volatility context
],
subplot_configs=[
SubplotConfig(
subplot_type=SubplotType.RSI,
height_ratio=0.15,
indicators=["rsi_14"],
title="RSI Momentum",
y_axis_label="RSI",
show_grid=True
),
SubplotConfig(
subplot_type=SubplotType.MACD,
height_ratio=0.2,
indicators=["macd_12_26_9"],
title="MACD Confirmation",
y_axis_label="MACD",
show_grid=True
)
],
chart_style=ChartStyle(
theme="plotly_white",
font_size=12,
candlestick_up_color="#26a69a",
candlestick_down_color="#ef5350",
show_volume=True,
show_grid=True
),
tags=["trend-following", "ema-crossover", "day-trading", "intermediate"]
)
return StrategyExample(
config=config,
description="""
EMA Crossover Strategy uses the crossing of fast (12-period) and slow (26-period)
exponential moving averages to generate buy and sell signals. The 50-period EMA
acts as a trend filter to avoid false signals in sideways markets.
Entry Rules:
- Buy when fast EMA crosses above slow EMA and price is above 50 EMA
- RSI should be above 30 (not oversold)
- MACD line should be above signal line
Exit Rules:
- Sell when fast EMA crosses below slow EMA
- Or when RSI reaches overbought levels (>70)
- Stop loss: 2% below entry or below recent swing low
""",
author="TCPDashboard Team",
difficulty="Intermediate",
expected_return="8-15% monthly (in trending markets)",
risk_level="Medium",
market_conditions=["Trending", "Breakout"],
notes=[
"Works best in trending markets",
"Can produce whipsaws in sideways markets",
"Use 50 EMA as trend filter to reduce false signals",
"Consider volume confirmation for stronger signals",
"Best timeframes: 15m, 1h, 4h for day trading"
],
references=[
"Moving Average Convergence Divergence - Gerald Appel",
"Technical Analysis of Financial Markets - John Murphy"
]
)
def create_momentum_breakout_strategy() -> StrategyExample:
"""
Create momentum breakout strategy configuration.
Strategy focused on capturing momentum moves using RSI,
MACD, and volume confirmation.
"""
config = StrategyChartConfig(
strategy_name="Momentum Breakout Strategy",
strategy_type=TradingStrategy.MOMENTUM,
description="Momentum strategy capturing strong directional moves with volume confirmation",
timeframes=["5m", "15m", "1h"],
layout=ChartLayout.MAIN_WITH_SUBPLOTS,
main_chart_height=0.6,
overlay_indicators=[
"ema_8", # Fast trend
"ema_21", # Medium trend
"bb_20_25" # Volatility bands (wider for breakouts)
],
subplot_configs=[
SubplotConfig(
subplot_type=SubplotType.RSI,
height_ratio=0.15,
indicators=["rsi_7", "rsi_14"], # Fast and standard RSI
title="RSI Momentum (7 & 14)",
y_axis_label="RSI",
show_grid=True
),
SubplotConfig(
subplot_type=SubplotType.MACD,
height_ratio=0.15,
indicators=["macd_8_17_6"], # Faster MACD for momentum
title="MACD Fast",
y_axis_label="MACD",
show_grid=True
),
SubplotConfig(
subplot_type=SubplotType.VOLUME,
height_ratio=0.1,
indicators=[],
title="Volume Confirmation",
y_axis_label="Volume",
show_grid=True
)
],
chart_style=ChartStyle(
theme="plotly_white",
font_size=11,
candlestick_up_color="#00d4aa",
candlestick_down_color="#fe6a85",
show_volume=True,
show_grid=True
),
tags=["momentum", "breakout", "volume", "short-term"]
)
return StrategyExample(
config=config,
description="""
Momentum Breakout Strategy captures strong directional moves by identifying
momentum acceleration with volume confirmation. Uses faster indicators
to catch moves early while avoiding false breakouts.
Entry Rules:
- Price breaks above/below Bollinger Bands with strong volume
- RSI-7 > 70 for bullish momentum (< 30 for bearish)
- MACD line crosses above signal line with rising histogram
- Volume should be 1.5x average volume
- EMA-8 above EMA-21 for trend confirmation
Exit Rules:
- RSI-7 reaches extreme levels (>80 or <20)
- MACD histogram starts declining
- Volume drops significantly
- Price returns inside Bollinger Bands
- Stop loss: 1.5% or below previous swing point
""",
author="TCPDashboard Team",
difficulty="Advanced",
expected_return="15-25% monthly (high volatility)",
risk_level="High",
market_conditions=["Volatile", "Breakout", "High Volume"],
notes=[
"Requires quick execution and tight risk management",
"Best during high volatility periods",
"Monitor volume closely for confirmation",
"Use smaller position sizes due to higher risk",
"Consider market hours for better volume",
"Avoid during low liquidity periods"
],
references=[
"Momentum Stock Selection - Richard Driehaus",
"High Probability Trading - Marcel Link"
]
)
def create_mean_reversion_strategy() -> StrategyExample:
"""
Create mean reversion strategy configuration.
Counter-trend strategy using oversold/overbought conditions
and support/resistance levels.
"""
config = StrategyChartConfig(
strategy_name="Mean Reversion Strategy",
strategy_type=TradingStrategy.MEAN_REVERSION,
description="Counter-trend strategy exploiting oversold/overbought conditions",
timeframes=["15m", "1h", "4h"],
layout=ChartLayout.MAIN_WITH_SUBPLOTS,
main_chart_height=0.7,
overlay_indicators=[
"sma_20", # Mean reversion line
"sma_50", # Trend context
"bb_20_20", # Standard Bollinger Bands
"bb_20_15" # Tighter bands for entry signals
],
subplot_configs=[
SubplotConfig(
subplot_type=SubplotType.RSI,
height_ratio=0.2,
indicators=["rsi_14", "rsi_21"], # Standard and slower RSI
title="RSI Mean Reversion",
y_axis_label="RSI",
show_grid=True
),
SubplotConfig(
subplot_type=SubplotType.VOLUME,
height_ratio=0.1,
indicators=[],
title="Volume Analysis",
y_axis_label="Volume",
show_grid=True
)
],
chart_style=ChartStyle(
theme="plotly_white",
font_size=12,
candlestick_up_color="#4caf50",
candlestick_down_color="#f44336",
show_volume=True,
show_grid=True
),
tags=["mean-reversion", "counter-trend", "oversold-overbought"]
)
return StrategyExample(
config=config,
description="""
Mean Reversion Strategy exploits the tendency of prices to return to their
average after extreme moves. Uses multiple RSI periods and Bollinger Bands
to identify oversold/overbought conditions with high probability reversals.
Entry Rules (Long):
- Price touches or breaks lower Bollinger Band (20,2.0)
- RSI-14 < 30 and RSI-21 < 35 (oversold conditions)
- Price shows bullish divergence with RSI
- Volume spike on the reversal candle
- Entry on first green candle after oversold signal
Entry Rules (Short):
- Price touches or breaks upper Bollinger Band
- RSI-14 > 70 and RSI-21 > 65 (overbought conditions)
- Bearish divergence with RSI
- High volume on reversal
Exit Rules:
- Price returns to SMA-20 (mean)
- RSI reaches neutral zone (45-55)
- Stop loss: Beyond recent swing high/low
- Take profit: Opposite Bollinger Band
""",
author="TCPDashboard Team",
difficulty="Intermediate",
expected_return="10-18% monthly (ranging markets)",
risk_level="Medium",
market_conditions=["Sideways", "Ranging", "Oversold/Overbought"],
notes=[
"Works best in ranging/sideways markets",
"Avoid during strong trending periods",
"Look for divergences for higher probability setups",
"Use proper position sizing due to counter-trend nature",
"Consider market structure and support/resistance levels",
"Best during regular market hours for better volume"
],
references=[
"Mean Reversion Trading Systems - Howard Bandy",
"Contrarian Investment Strategies - David Dreman"
]
)
def create_scalping_strategy() -> StrategyExample:
"""
Create scalping strategy configuration.
High-frequency strategy for quick profits using
very fast indicators and tight risk management.
"""
config = StrategyChartConfig(
strategy_name="Scalping Strategy",
strategy_type=TradingStrategy.SCALPING,
description="High-frequency scalping strategy for quick profits",
timeframes=["1m", "5m"],
layout=ChartLayout.MAIN_WITH_SUBPLOTS,
main_chart_height=0.55,
overlay_indicators=[
"ema_5", # Very fast EMA
"ema_12", # Fast EMA
"ema_21", # Reference EMA
"bb_10_15" # Tight Bollinger Bands
],
subplot_configs=[
SubplotConfig(
subplot_type=SubplotType.RSI,
height_ratio=0.2,
indicators=["rsi_7"], # Very fast RSI
title="RSI Fast (7)",
y_axis_label="RSI",
show_grid=True
),
SubplotConfig(
subplot_type=SubplotType.MACD,
height_ratio=0.15,
indicators=["macd_5_13_4"], # Very fast MACD
title="MACD Ultra Fast",
y_axis_label="MACD",
show_grid=True
),
SubplotConfig(
subplot_type=SubplotType.VOLUME,
height_ratio=0.1,
indicators=[],
title="Volume",
y_axis_label="Volume",
show_grid=True
)
],
chart_style=ChartStyle(
theme="plotly_white",
font_size=10,
candlestick_up_color="#00e676",
candlestick_down_color="#ff1744",
show_volume=True,
show_grid=True
),
tags=["scalping", "high-frequency", "fast", "1-minute"]
)
return StrategyExample(
config=config,
description="""
Scalping Strategy designed for rapid-fire trading with small profits
and very tight risk management. Uses ultra-fast indicators to capture
small price movements multiple times per session.
Entry Rules:
- EMA-5 crosses above EMA-12 (bullish scalp)
- Price is above EMA-21 for trend alignment
- RSI-7 between 40-60 (avoid extremes)
- MACD line above signal line
- Strong volume confirmation
- Enter on pullback to EMA-5 after crossover
Exit Rules:
- Target: 5-10 pips profit (0.1-0.2% for stocks)
- Stop loss: 3-5 pips (0.05-0.1%)
- Exit if RSI reaches extreme (>75 or <25)
- Exit if EMA-5 crosses back below EMA-12
- Maximum hold time: 5-15 minutes
""",
author="TCPDashboard Team",
difficulty="Advanced",
expected_return="Small profits, high frequency (2-5% daily)",
risk_level="High",
market_conditions=["High Liquidity", "Volatile", "Active Sessions"],
notes=[
"Requires very fast execution and low latency",
"Best during active market hours (overlapping sessions)",
"Use tight spreads and low commission brokers",
"Requires constant monitoring and quick decisions",
"Risk management is critical - small stops",
"Not suitable for beginners",
"Consider transaction costs carefully",
"Practice on demo account extensively first"
],
references=[
"A Complete Guide to Volume Price Analysis - Anna Coulling",
"The Complete Guide to Day Trading - Markus Heitkoetter"
]
)
def create_swing_trading_strategy() -> StrategyExample:
"""
Create swing trading strategy configuration.
Medium-term strategy capturing price swings over
several days to weeks using trend and momentum indicators.
"""
config = StrategyChartConfig(
strategy_name="Swing Trading Strategy",
strategy_type=TradingStrategy.SWING_TRADING,
description="Medium-term strategy capturing multi-day price swings",
timeframes=["4h", "1d"],
layout=ChartLayout.MAIN_WITH_SUBPLOTS,
main_chart_height=0.7,
overlay_indicators=[
"sma_20", # Short-term trend
"sma_50", # Medium-term trend
"ema_21", # Dynamic support/resistance
"bb_20_20" # Volatility bands
],
subplot_configs=[
SubplotConfig(
subplot_type=SubplotType.RSI,
height_ratio=0.15,
indicators=["rsi_14"],
title="RSI (14)",
y_axis_label="RSI",
show_grid=True
),
SubplotConfig(
subplot_type=SubplotType.MACD,
height_ratio=0.15,
indicators=["macd_12_26_9"],
title="MACD Standard",
y_axis_label="MACD",
show_grid=True
)
],
chart_style=ChartStyle(
theme="plotly_white",
font_size=13,
candlestick_up_color="#388e3c",
candlestick_down_color="#d32f2f",
show_volume=True,
show_grid=True
),
tags=["swing-trading", "medium-term", "trend-following"]
)
return StrategyExample(
config=config,
description="""
Swing Trading Strategy captures price swings over several days to weeks
by identifying trend changes and momentum shifts. Suitable for traders
who cannot monitor markets constantly but want to catch significant moves.
Entry Rules (Long):
- Price above SMA-50 (uptrend confirmation)
- SMA-20 crosses above SMA-50 or price bounces off SMA-20
- RSI pullback to 35-45 then rises above 50
- MACD line crosses above signal line
- Price finds support at EMA-21 or lower Bollinger Band
Entry Rules (Short):
- Price below SMA-50 (downtrend confirmation)
- SMA-20 crosses below SMA-50 or price rejected at SMA-20
- RSI pullback to 55-65 then falls below 50
- MACD line crosses below signal line
Exit Rules:
- Price reaches opposite Bollinger Band
- RSI reaches overbought/oversold extremes (>70/<30)
- MACD shows divergence or histogram weakens
- Stop loss: Below/above recent swing point (2-4%)
- Take profit: 1:2 or 1:3 risk-reward ratio
""",
author="TCPDashboard Team",
difficulty="Beginner",
expected_return="15-25% annually",
risk_level="Medium",
market_conditions=["Trending", "Swing Markets"],
notes=[
"Suitable for part-time traders",
"Requires patience for proper setups",
"Good for building trading discipline",
"Consider fundamental analysis for direction",
"Use proper position sizing (1-2% risk per trade)",
"Best on daily timeframes for trend following",
"Monitor weekly charts for overall direction"
],
references=[
"Swing Trading For Beginners - Matthew Maybury",
"The Master Swing Trader - Alan Farley"
]
)
def get_all_example_strategies() -> Dict[str, StrategyExample]:
"""
Get all available example strategies.
Returns:
Dictionary mapping strategy names to StrategyExample objects
"""
return {
"ema_crossover": create_ema_crossover_strategy(),
"momentum_breakout": create_momentum_breakout_strategy(),
"mean_reversion": create_mean_reversion_strategy(),
"scalping": create_scalping_strategy(),
"swing_trading": create_swing_trading_strategy()
}
def get_example_strategy(strategy_name: str) -> Optional[StrategyExample]:
"""
Get a specific example strategy by name.
Args:
strategy_name: Name of the strategy to retrieve
Returns:
StrategyExample object or None if not found
"""
strategies = get_all_example_strategies()
return strategies.get(strategy_name)
def get_strategies_by_difficulty(difficulty: str) -> List[StrategyExample]:
"""
Get example strategies filtered by difficulty level.
Args:
difficulty: Difficulty level ("Beginner", "Intermediate", "Advanced")
Returns:
List of StrategyExample objects matching the difficulty
"""
strategies = get_all_example_strategies()
return [strategy for strategy in strategies.values()
if strategy.difficulty == difficulty]
def get_strategies_by_risk_level(risk_level: str) -> List[StrategyExample]:
"""
Get example strategies filtered by risk level.
Args:
risk_level: Risk level ("Low", "Medium", "High")
Returns:
List of StrategyExample objects matching the risk level
"""
strategies = get_all_example_strategies()
return [strategy for strategy in strategies.values()
if strategy.risk_level == risk_level]
def get_strategies_by_market_condition(condition: str) -> List[StrategyExample]:
"""
Get example strategies suitable for specific market conditions.
Args:
condition: Market condition ("Trending", "Sideways", "Volatile", etc.)
Returns:
List of StrategyExample objects suitable for the condition
"""
strategies = get_all_example_strategies()
return [strategy for strategy in strategies.values()
if condition in strategy.market_conditions]
def get_strategy_summary() -> Dict[str, Dict[str, str]]:
"""
Get a summary of all example strategies with key information.
Returns:
Dictionary with strategy summaries
"""
strategies = get_all_example_strategies()
summary = {}
for name, strategy in strategies.items():
summary[name] = {
"name": strategy.config.strategy_name,
"type": strategy.config.strategy_type.value,
"difficulty": strategy.difficulty,
"risk_level": strategy.risk_level,
"timeframes": ", ".join(strategy.config.timeframes),
"market_conditions": ", ".join(strategy.market_conditions),
"expected_return": strategy.expected_return or "N/A"
}
return summary
def export_example_strategies_to_json() -> str:
"""
Export all example strategies to JSON format.
Returns:
JSON string containing all example strategies
"""
import json
from .strategy_charts import export_strategy_config_to_json
strategies = get_all_example_strategies()
export_data = {}
for name, strategy in strategies.items():
export_data[name] = {
"config": json.loads(export_strategy_config_to_json(strategy.config)),
"metadata": {
"description": strategy.description,
"author": strategy.author,
"difficulty": strategy.difficulty,
"expected_return": strategy.expected_return,
"risk_level": strategy.risk_level,
"market_conditions": strategy.market_conditions,
"notes": strategy.notes,
"references": strategy.references
}
}
return json.dumps(export_data, indent=2)