Snippet
//@version=5strategy("Buy on Small Dip in Bullish Trend", overlay=true) // --- Input Parameters for MA Lengths ---// Input for the length of the short Moving Average (e.g., for quick movements/dips)shortMaLength = input.int(10, "Short MA Length", minval=1) // Input for the length of the medium Moving Average (e.g., for intermediate movements/dips)mediumMaLength = input.int(50, "Medium MA Length", minval=1) // Input for the length of the long Moving Average (e.g., for main trend identification)longMaLength = input.int(200, "Long MA Length", minval=1) // --- Risk Management Parameters ---// Stop loss set to 10% as requestedstopLossPercent = input.float(10.0, "Stop Loss %", minval=0.1, step=0.1) / 100// Take profit set to 3% as requestedtakeProfitPercent = input.float(3.0, "Take Profit %", minval=0.1, step=0.1) / 100 // --- Moving Average Calculations ---// Calculate the short-period Simple Moving Average of the closing priceshortMa = ta.sma(close, shortMaLength) // Calculate the medium-period Simple Moving Average of the closing pricemediumMa = ta.sma(close, mediumMaLength) // Calculate the long-period Simple Moving Average of the closing pricelongMa = ta.sma(close, longMaLength) // --- Trend and Dip Conditions ---// Condition for a long-term bullish trend:// Current price is above the long-term MA, and the long-term MA itself is sloping upwards.isBullishTrend = close > longMa and longMa > longMa[1] // Condition for a small dip:// The short MA crosses below the medium MA (indicating a dip starts),// AND then the short MA crosses back above the medium MA (indicating the dip ends and uptrend resumes).// We use `ta.crossunder` to detect the dip initiation and `ta.crossover` for the dip recovery.dipInitiated = ta.crossunder(shortMa, mediumMa)dipRecovered = ta.crossover(shortMa, mediumMa) // A buy signal is generated when the dip recovers AND the overall trend is bullish.buySignal = dipRecovered and isBullishTrend // --- Entry Logic ---// Enter a long position when the buy signal is trueif buySignal strategy.entry("BuyDip", strategy.long) // --- Exit Logic (Stop Loss and Take Profit) ---// Calculate stop loss and take profit prices based on entry pricelongStopPrice = strategy.position_avg_price * (1 - stopLossPercent)longTakeProfitPrice = strategy.position_avg_price * (1 + takeProfitPercent) // Apply stop loss and take profit orders for the "BuyDip" entrystrategy.exit("Exit", from_entry="BuyDip", stop=longStopPrice, limit=longTakeProfitPrice) // --- Plotting Moving Averages ---// Plot the short MA on the chart (e.g., green for faster movement)plot(shortMa, "Short MA", color=color.green, linewidth=2) // Plot the medium MA on the chart (e.g., orange for intermediate movement)plot(mediumMa, "Medium MA", color=color.orange, linewidth=2) // Plot the long MA on the chart (e.g., blue for main trend)plot(longMa, "Long MA", color=color.blue, linewidth=3)