//@version=5
strategy("Advanced Multi-Timeframe Strategy with Rapid Averages", overlay=true, margin_long=100, margin_short=100, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// =====================
// User-defined Inputs
// =====================
// Allow the user to customize risk tolerance, investment horizon, and moving average periods
// Risk management parameters
risk_tolerance = input.float(title="Risk Tolerance (%)", defval=1.0, minval=0.1, step=0.1)
// Investment horizon selection (affects indicator periods)
investment_horizon = input.string(title="Investment Horizon", defval="Medium Term", options=["Short Term", "Medium Term", "Long Term"])
// Rapid average periods for quick trend identification
ema_fast_period = input.int(title="Fast EMA Period", defval=9, minval=1)
sma_fast_period = input.int(title="Fast SMA Period", defval=20, minval=1)
// Longer-term average periods for trend confirmation
ema_slow_period = input.int(title="Slow EMA Period", defval=50, minval=1)
sma_slow_period = input.int(title="Slow SMA Period", defval=200, minval=1)
// =====================
// Multiple Timeframe Analysis with Rapid Averages
// =====================
// Define lower timeframes for rapid averages
fast_timeframes = ["1", "5", "15"] // Timeframes in minutes
// Initialize arrays to store rapid averages from lower timeframes
ema_fast_array = array.new_float()
sma_fast_array = array.new_float()
// Loop through each lower timeframe to calculate rapid averages
for tf in fast_timeframes
// Retrieve close prices from lower timeframe
close_tf = request.security(syminfo.tickerid, tf + "", close)
// Calculate fast EMA and SMA on lower timeframe
ema_tf = ta.ema(close_tf, ema_fast_period)
sma_tf = ta.sma(close_tf, sma_fast_period)
// Store the averages in arrays
array.push(ema_fast_array, ema_tf)
array.push(sma_fast_array, sma_tf)
// Calculate the average of the rapid averages from all lower timeframes
ema_fast_avg = array.avg(ema_fast_array)
sma_fast_avg = array.avg(sma_fast_array)
// =====================
// Longer-term Moving Averages for Trend Confirmation
// =====================
// Calculate slow EMA and SMA on the current timeframe
ema_slow = ta.ema(close, ema_slow_period)
sma_slow = ta.sma(close, sma_slow_period)
// =====================
// Additional Technical Indicators
// =====================
// Relative Strength Index (RSI)
rsi = ta.rsi(close, 14)
// Moving Average Convergence Divergence (MACD)
[macd_line, signal_line, hist_line] = ta.macd(close, 12, 26, 9)
// Bollinger Bands
bb_upper, bb_middle, bb_lower = ta.bb(close, 20, 2)
// =====================
// Fundamental Analysis Factors
// =====================
// Retrieve fundamental data (earnings growth, P/E ratio, dividend yield)
earnings_growth = request.financial(syminfo.tickerid, "earnings_per_share_basic", "FQ")
pe_ratio = request.financial(syminfo.tickerid, "price_earnings_ttm", "FY")
dividend_yield = request.financial(syminfo.tickerid, "dividends_per_share", "FY")
// Evaluate fundamental conditions
fundamental_score = 0
if earnings_growth > earnings_growth[1]
fundamental_score += 1 // Earnings are growing
if pe_ratio < 20
fundamental_score += 1 // P/E ratio is favorable
if dividend_yield > dividend_yield[1]
fundamental_score += 1 // Dividend yield is increasing
// Check if fundamental criteria are met
fundamental_ok = fundamental_score >= 2
// =====================
// Volume-Based Confirmation Indicators
// =====================
// Volume Weighted Average Price (VWAP)
vwap = ta.vwap(close)
// On-Balance Volume (OBV)
obv = ta.obv(close, volume)
// =====================
// Adaptive Risk Management Techniques
// =====================
// Average True Range (ATR) for volatility calculation
atr = ta.atr(14)
// Account size for position sizing
account_size = strategy.equity
// Dynamic position sizing based on volatility and risk tolerance
position_size = (account_size * (risk_tolerance / 100)) / atr
// Ensure position size is not exceeding account size
position_size := math.min(position_size, account_size)
// =====================
// Statistical Model for Price Prediction
// =====================
// Linear Regression (as a placeholder for machine learning)
prediction_length = 10 // Number of periods to predict
predicted_price = ta.linreg(close, prediction_length, 0)
// =====================
// Multi-Timeframe Volatility Filter
// =====================
// Retrieve ATR values from lower timeframes for volatility assessment
volatility_tf1 = request.security(syminfo.tickerid, "1", ta.atr(14))
volatility_tf5 = request.security(syminfo.tickerid, "5", ta.atr(14))
volatility_tf15 = request.security(syminfo.tickerid, "15", ta.atr(14))
// Calculate average volatility
avg_volatility = (volatility_tf1 + volatility_tf5 + volatility_tf15) / 3
// Adjust trading conditions based on volatility
high_volatility = avg_volatility > ta.atr(14)
// =====================
// Visual Signals on the Chart
// =====================
// Plot longer-term moving averages
plot(ema_slow, color=color.blue, title="EMA Slow")
plot(sma_slow, color=color.orange, title="SMA Slow")
// Plot rapid averages with color coding for trend direction
trend_color = ema_fast_avg > sma_fast_avg ? color.green : color.red
plot(ema_fast_avg, color=trend_color, title="EMA Fast Average")
plot(sma_fast_avg, color=trend_color, title="SMA Fast Average")
// Mark overbought/oversold conditions with shaded areas
rsi_ob_level = 70
rsi_os_level = 30
hline(rsi_ob_level, 'Overbought Level', color=color.gray, linestyle=hline.style_dashed)
hline(rsi_os_level, 'Oversold Level', color=color.gray, linestyle=hline.style_dashed)
bgcolor(rsi > rsi_ob_level ? color.new(color.red, 90) : na)
bgcolor(rsi < rsi_os_level ? color.new(color.green, 90) : na)
// =====================
// Entry and Exit Signals with Markers
// =====================
// Initialize signals
buy_signal = false
sell_signal = false
// Define entry conditions for a long position
if fundamental_ok and ema_fast_avg > sma_fast_avg and ema_slow > sma_slow and rsi < rsi_ob_level and macd_line > signal_line and obv > obv[1]
buy_signal := true
// Define exit conditions for the long position
if ema_fast_avg < sma_fast_avg or ema_slow < sma_slow or rsi > rsi_ob_level or macd_line < signal_line or obv < obv[1]
sell_signal := true
// Execute long entry
if buy_signal and strategy.position_size == 0
strategy.entry("Long Entry", strategy.long, qty=position_size)
// Initialize trailing stop price
trail_stop_price = close - atr * 1.5
// Execute long exit
if sell_signal and strategy.position_size > 0
strategy.close("Long Entry")
trail_stop_price := na
// =====================
// Smart Trailing Stop-Loss Mechanism
// =====================
// Update trailing stop based on rapid average crossovers
if strategy.position_size > 0
// Adjust trailing stop if rapid averages indicate a potential reversal
if ema_fast_avg < sma_fast_avg
trail_stop_price := max(trail_stop_price, close - atr * 1.5)
// Exit position if price falls below trailing stop
if close < trail_stop_price
strategy.close("Long Entry")
trail_stop_price := na
// =====================
// Comprehensive Performance Metrics
// =====================
// Calculate daily returns
daily_return = (strategy.equity / strategy.equity[1]) - 1
// Calculate standard deviation of daily returns over the last 14 days
std_dev_returns = ta.stdev(daily_return, 14)
// Risk-free rate (e.g., 1% annualized converted to daily)
risk_free_rate = 0.01 / 252
// Calculate Sharpe Ratio
sharpe_ratio = (strategy.netprofit / strategy.initial_capital - risk_free_rate) / (std_dev_returns * sqrt(252))
// Calculate Sortino Ratio
negative_returns = daily_return < 0 ? daily_return : 0
downside_deviation = ta.stdev(negative_returns, 14)
sortino_ratio = (strategy.netprofit / strategy.initial_capital - risk_free_rate) / (downside_deviation * sqrt(252))
// Display performance metrics
plot(title="Sharpe Ratio", series=sharpe_ratio, color=color.purple, linewidth=2, display=display.none)
plot(title="Sortino Ratio", series=sortino_ratio, color=color.fuchsia, linewidth=2, display=display.none)
// Maximum Drawdown and Recovery Time are available in the Strategy Tester report
// =====================
// Multi-level Alerts
// =====================
// Alert for Rapid Average Crossovers (Bullish)
alertcondition(crossover(ema_fast_avg, sma_fast_avg), title="Bullish Crossover", message="EMA Fast Average crossed above SMA Fast Average")
// Alert for Rapid Average Crossovers (Bearish)
alertcondition(crossunder(ema_fast_avg, sma_fast_avg), title="Bearish Crossover", message="EMA Fast Average crossed below SMA Fast Average")
// Alert for Breakouts from Key Levels
resistance = ta.highest(high, 50)
support = ta.lowest(low, 50)
breakout_up = close > resistance
breakout_down = close < support
alertcondition(breakout_up, title="Breakout Up", message="Price broke above resistance level")
alertcondition(breakout_down, title="Breakout Down", message="Price broke below support level")
// Alert for Divergences between Price and RSI
price_higher_high = high > high[1]
rsi_lower_high = rsi < rsi[1]
bearish_divergence = price_higher_high and rsi_lower_high
price_lower_low = low < low[1]
rsi_higher_low = rsi > rsi[1]
bullish_divergence = price_lower_low and rsi_higher_low
alertcondition(bearish_divergence, title="Bearish Divergence", message="Bearish divergence detected between price and RSI")
alertcondition(bullish_divergence, title="Bullish Divergence", message="Bullish divergence detected between price and RSI")
// Note: Alerts for fundamental data updates are not directly supported in Pine Script
// =====================
// Optimization and Backtesting Instructions
// =====================
/*
To optimize and backtest this strategy across multiple timeframes:
1. Adjust the 'investment_horizon' input to match your desired trading timeframe (Short Term, Medium Term, Long Term). This will influence the sensitivity of the indicators and signals.
2. Utilize TradingView's built-in Strategy Tester:
- Navigate to the Strategy Tester tab at the bottom of the chart.
- Review the performance summary, list of trades, and performance metrics.
- Adjust the input parameters such as 'risk_tolerance', 'ema_fast_period', 'sma_fast_period', 'ema_slow_period', and 'sma_slow_period' to optimize performance.
3. Backtest on different timeframes:
- Change the chart timeframe (e.g., 15-minute, 1-hour, daily) to see how the strategy performs across different periods.
- Observe changes in signals, profitability, and performance metrics.
4. Analyze the equity curve and drawdown to ensure the strategy aligns with your risk tolerance and investment goals.
5. Save different versions with varying parameters to compare results.
*/
// =====================
// End of Strategy Code
// =====================
Explanation of the Strategy Components:
-
User-defined Inputs: Allow customization of risk tolerance, investment horizon, and moving average periods to tailor the strategy to individual preferences.
-
Multiple Timeframe Analysis: Incorporate rapid averages from lower timeframes (1-minute, 5-minute, and 15-minute) using the request.security() function. These rapid averages help in quick trend identification and improve precision in entry and exit signals.
-
Technical Indicators:
- Rapid Moving Averages: Fast EMA and SMA computed from lower timeframes aid in detecting short-term trends.
- Longer-term Moving Averages: Slow EMA and SMA on the current timeframe confirm overall trend direction.
- RSI, MACD, Bollinger Bands: Provide additional layers of analysis for momentum, trend strength, and volatility.
-
Fundamental Analysis Factors: Evaluate key financial metrics like earnings growth, P/E ratio, and dividend yield to ensure trades are made on fundamentally sound stocks.
-
Volume-Based Confirmation: Use VWAP and OBV to confirm price movements with volume, enhancing the reliability of signals.
-
Adaptive Risk Management:
- Dynamic Position Sizing: Adjust position sizes based on account size and market volatility (ATR), aligning with the defined risk tolerance.
- Smart Trailing Stop-Loss: Implement a trailing stop that adapts to rapid average crossovers, helping protect profits and limit losses.
- Portfolio Diversification: While actual portfolio management is beyond Pine Script's scope, the strategy only proceeds with trades when fundamental criteria are met, indirectly promoting diversification.
-
Statistical Model for Price Prediction: A linear regression model serves as a simple predictive tool, representing the integration of statistical models.
-
Multi-Timeframe Volatility Filter: Assess volatility across multiple timeframes to adjust trading conditions, helping the strategy adapt to different market environments.
-
Clear Visual Signals:
- Color-coded Averages: Rapid averages are color-coded (green for bullish, red for bearish) to indicate trend direction at a glance.
- Entry and Exit Markers: Clearly marked on the chart for easy visualization of trade actions.
Note: This strategy is designed to prioritize profitability and risk management. It combines technical and fundamental analysis to make informed trading decisions. The integration of multiple confirmations aims to reduce false signals, and the adaptive elements help in navigating varying market dynamics.
Disclaimer: Trading strategies involve risks, and past performance is not indicative of future results. It's important to thoroughly test and adjust the strategy to align with your individual risk tolerance and investment objectives before applying it to live trading.