Advertisement IC Markets

The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Discuss 1-minute to 15-minute price action setups, fading intraday momentum, key support/resistance zones, and proven short-term trading methodologies.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

Hey traders, hi scalpers,

I’ve been trading Gold (XAUUSD) for a few years now, and we all know how unforgiving the 1-minute and 5-minute charts can be. Whipsaws and liquidity sweeps will easily eat your account if you aren't trading with the macro trend.

To help filter out the noise, I built the Ultimate XAUUSD Scalper in TradingView. It’s 100% free, fully non-repainting, and explicitly designed to catch momentum bursts during the London and New York sessions.

How the Indicator Works

Instead of relying on a single metric, this script requires three points of confluence before printing a signal:

The Macro Filter (200 EMA): The script won't allow buy signals if the price is below the 200 EMA, and won't allow sell signals if the price is above it.

The Trigger (9 & 21 EMA): A fast crossover acts as the primary entry mechanism for catching immediate momentum.

The Confirmation (RSI 14): To avoid buying at the top or selling at the bottom of a micro-range, RSI must be > 50 for longs and < 50 for shorts.

Live Dashboard: I built in a real-time table in the top right corner so you can see the immediate trend, RSI reading, and ATR (volatility) at a glance without cluttering your sub-windows.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Recommended broker for automated trading & scalping IC Markets
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

The Pine Script v5 Code

Copy and paste this into your TradingView Pine Editor:

Code: Select all

//@version=5
indicator("Ultimate XAUUSD Scalper [Forex-Scalping.com]", overlay=true, max_lines_count=500, max_labels_count=500)

// ==========================================
// 1. USER INPUTS
// ==========================================
grp1 = "Trend & Trigger Settings"
fastEmaLen  = input.int(9, title="Fast EMA Length", group=grp1)
slowEmaLen  = input.int(21, title="Slow EMA Length", group=grp1)
trendEmaLen = input.int(200, title="Baseline Trend EMA", group=grp1)

grp2 = "Momentum & Volatility"
rsiLen      = input.int(14, title="RSI Length", group=grp2)
atrLen      = input.int(14, title="ATR Length", group=grp2)

// ==========================================
// 2. CALCULATIONS
// ==========================================
fastEma  = ta.ema(close, fastEmaLen)
slowEma  = ta.ema(close, slowEmaLen)
trendEma = ta.ema(close, trendEmaLen)
rsiVal   = ta.rsi(close, rsiLen)
atrVal   = ta.atr(atrLen)

// ==========================================
// 3. LOGIC & CONDITIONS
// ==========================================
// Macro Trend Check
bullishTrend = close > trendEma
bearishTrend = close < trendEma

// Entry Signals
buySignal  = ta.crossover(fastEma, slowEma) and bullishTrend and rsiVal > 50
sellSignal = ta.crossunder(fastEma, slowEma) and bearishTrend and rsiVal < 50

// ==========================================
// 4. PLOTTING
// ==========================================
plot(fastEma, color=color.new(color.blue, 0), title="Fast EMA", linewidth=1)
plot(slowEma, color=color.new(color.orange, 0), title="Slow EMA", linewidth=1)
plot(trendEma, color=color.new(color.white, 0), title="200 EMA Baseline", linewidth=2)

// Signal Shapes
plotshape(buySignal, title="Buy Signal", text="BUY", location=location.belowbar, style=shape.labelup, size=size.small, color=color.new(color.green, 0), textcolor=color.white)
plotshape(sellSignal, title="Sell Signal", text="SELL", location=location.abovebar, style=shape.labeldown, size=size.small, color=color.new(color.red, 0), textcolor=color.white)

// ==========================================
// 5. DASHBOARD TABLE
// ==========================================
var table dash = table.new(position.top_right, 2, 4, border_color=color.new(color.gray, 50), border_width=1, frame_color=color.new(color.gray, 50), frame_width=1)

if barstate.islast
    // Header
    table.cell(dash, 0, 0, "XAUUSD Scalper", text_color=color.white, bgcolor=color.new(color.blue, 20), text_size=size.small)
    table.cell(dash, 1, 0, "Status", text_color=color.white, bgcolor=color.new(color.blue, 20), text_size=size.small)
    
    // Trend
    table.cell(dash, 0, 1, "Macro Trend", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 1, bullishTrend ? "BULLISH" : "BEARISH", text_color=color.white, bgcolor=bullishTrend ? color.new(color.green, 30) : color.new(color.red, 30), text_size=size.small)
    
    // RSI
    table.cell(dash, 0, 2, "RSI (14)", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 2, str.tostring(math.round(rsiVal, 1)), text_color=color.white, bgcolor=rsiVal > 50 ? color.new(color.green, 30) : color.new(color.red, 30), text_size=size.small)
    
    // ATR
    table.cell(dash, 0, 3, "ATR (14)", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 3, str.tostring(math.round(atrVal, 2)), text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)

// ==========================================
// 6. ALERTS
// ==========================================
alertcondition(buySignal, title="XAUUSD Buy Alert", message="Ultimate Scalper: BUY Signal on XAUUSD")
alertcondition(sellSignal, title="XAUUSD Sell Alert", message="Ultimate Scalper: SELL Signal on XAUUSD")
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

How to Install it on TradingView

1.Open TradingView: Log into your TradingView account and open the XAUUSD chart on your preferred scalping timeframe (the 1m or 5m charts work best for this setup).

2.Open the Pine Editor: Look at the bottom of your screen and click on the Pine Editor tab. Delete any existing template code in the window.

3.Paste the Code: Copy the entire Pine Script block from above and paste it directly into the editor.

4.Add to Chart: Save and apply.Click the Add to Chart button in the top right corner of the editor. I also recommend clicking Save so you can easily access it from your script library later.

Recommended Scalping Rules:

Stop Loss: Place your SL directly below the recent swing low for longs (or just above the swing high for shorts), or strictly use a 1.5x ATR distance.

Take Profit: Aim for a 1:1.5 or 1:2 Risk-to-Reward ratio. Since gold moves fast, take partials at 1:1 and move your stop to breakeven.

Time of Day: Only trade this during the London/NY crossover (12:00 PM - 4:00 PM GMT) when volume is actually present.

Let me know if you guys want me to add any specific features to this (like an automatic session time filter or dynamic take-profit plotting lines). Happy scalping!
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

Here is the updated script. I’ve added a complete Risk Management section that automatically calculates and plots your Stop Loss and Take Profit levels the moment a signal fires.

To keep the chart clean, the script tracks the "active" trade and will automatically hide the SL and TP lines once the price hits either level.

What’s New in This Version:

ATR Multiplier Input: You can now choose exactly how wide you want your Stop Loss based on current volatility (default is 1.5x ATR).

Risk/Reward Ratio Input: Set your target (default is 1:2 R:R), and the script automatically calculates the Take Profit level based on your Stop Loss distance.

Dynamic Line Plotting: Green lines for Take Profit and red lines for Stop Loss appear on the signal bar and disappear when the target or stop is hit.

The Updated Pine Script v5 Code

Copy and paste this over the previous code in your Pine Editor:

Code: Select all

//@version=5
indicator("Ultimate XAUUSD Scalper v2 [Forex-Scalping.com]", overlay=true, max_lines_count=500, max_labels_count=500)

// ==========================================
// 1. USER INPUTS
// ==========================================
grp1 = "Trend & Trigger Settings"
fastEmaLen  = input.int(9, title="Fast EMA Length", group=grp1)
slowEmaLen  = input.int(21, title="Slow EMA Length", group=grp1)
trendEmaLen = input.int(200, title="Baseline Trend EMA", group=grp1)

grp2 = "Momentum & Volatility"
rsiLen      = input.int(14, title="RSI Length", group=grp2)
atrLen      = input.int(14, title="ATR Length", group=grp2)

grp3 = "Risk Management (SL & TP)"
slMultiplier = input.float(1.5, title="Stop Loss ATR Multiplier", step=0.1, group=grp3)
rrRatio      = input.float(2.0, title="Risk/Reward Ratio", step=0.1, group=grp3)

// ==========================================
// 2. CALCULATIONS
// ==========================================
fastEma  = ta.ema(close, fastEmaLen)
slowEma  = ta.ema(close, slowEmaLen)
trendEma = ta.ema(close, trendEmaLen)
rsiVal   = ta.rsi(close, rsiLen)
atrVal   = ta.atr(atrLen)

// ==========================================
// 3. LOGIC & CONDITIONS
// ==========================================
// Macro Trend Check
bullishTrend = close > trendEma
bearishTrend = close < trendEma

// Entry Signals
buySignal  = ta.crossover(fastEma, slowEma) and bullishTrend and rsiVal > 50
sellSignal = ta.crossunder(fastEma, slowEma) and bearishTrend and rsiVal < 50

// ==========================================
// 4. SL & TP TRACKING
// ==========================================
var float slLevel = na
var float tpLevel = na
var int tradeDir = 0 // 1 for Long, -1 for Short

// Update levels on new signal
if buySignal
    slLevel := close - (atrVal * slMultiplier)
    tpLevel := close + ((close - slLevel) * rrRatio)
    tradeDir := 1
else if sellSignal
    slLevel := close + (atrVal * slMultiplier)
    tpLevel := close - ((slLevel - close) * rrRatio)
    tradeDir := -1

// Clear levels when hit
if tradeDir == 1
    if high >= tpLevel or low <= slLevel
        slLevel := na
        tpLevel := na
        tradeDir := 0
else if tradeDir == -1
    if low <= tpLevel or high >= slLevel
        slLevel := na
        tpLevel := na
        tradeDir := 0

// ==========================================
// 5. PLOTTING
// ==========================================
// EMAs
plot(fastEma, color=color.new(color.blue, 0), title="Fast EMA", linewidth=1)
plot(slowEma, color=color.new(color.orange, 0), title="Slow EMA", linewidth=1)
plot(trendEma, color=color.new(color.white, 0), title="200 EMA Baseline", linewidth=2)

// Signal Shapes
plotshape(buySignal, title="Buy Signal", text="BUY", location=location.belowbar, style=shape.labelup, size=size.small, color=color.new(color.green, 0), textcolor=color.white)
plotshape(sellSignal, title="Sell Signal", text="SELL", location=location.abovebar, style=shape.labeldown, size=size.small, color=color.new(color.red, 0), textcolor=color.white)

// Target Lines
plot(slLevel, title="Stop Loss", color=color.new(color.red, 20), style=plot.style_linebr, linewidth=2)
plot(tpLevel, title="Take Profit", color=color.new(color.green, 20), style=plot.style_linebr, linewidth=2)

// ==========================================
// 6. DASHBOARD TABLE
// ==========================================
var table dash = table.new(position.top_right, 2, 4, border_color=color.new(color.gray, 50), border_width=1, frame_color=color.new(color.gray, 50), frame_width=1)

if barstate.islast
    // Header
    table.cell(dash, 0, 0, "XAUUSD Scalper", text_color=color.white, bgcolor=color.new(color.blue, 20), text_size=size.small)
    table.cell(dash, 1, 0, "Status", text_color=color.white, bgcolor=color.new(color.blue, 20), text_size=size.small)
    
    // Trend
    table.cell(dash, 0, 1, "Macro Trend", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 1, bullishTrend ? "BULLISH" : "BEARISH", text_color=color.white, bgcolor=bullishTrend ? color.new(color.green, 30) : color.new(color.red, 30), text_size=size.small)
    
    // RSI
    table.cell(dash, 0, 2, "RSI (14)", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 2, str.tostring(math.round(rsiVal, 1)), text_color=color.white, bgcolor=rsiVal > 50 ? color.new(color.green, 30) : color.new(color.red, 30), text_size=size.small)
    
    // ATR
    table.cell(dash, 0, 3, "ATR (14)", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 3, str.tostring(math.round(atrVal, 2)), text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)

// ==========================================
// 7. ALERTS
// ==========================================
alertcondition(buySignal, title="XAUUSD Buy Alert", message="Ultimate Scalper: BUY Signal on XAUUSD")
alertcondition(sellSignal, title="XAUUSD Sell Alert", message="Ultimate Scalper: SELL Signal on XAUUSD")
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

When you add this to the chart, you'll see horizontal plot.style_linebr segments that start exactly when a trade triggers.
This makes visually backtesting the strategy on historical bars incredibly fast, as you can instantly see which signals reached their 2R target and which ones stopped out!
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

And here is the complete code converted into a Pine Script Strategy.

By changing it from an indicator to a strategy, TradingView can now simulate actual trades. I've added a Backtest Range filter so you can isolate specific months or years, and I’ve included realistic default capital and position sizing constraints so your profit graph isn't artificially inflated.

What Changed:

strategy() instead of indicator(): This unlocks the "Strategy Tester" tab in TradingView, giving you a full breakdown of Net Profit, Profit Factor, Win Rate, and Drawdown.

Strategy Execution: Replaced the visual alerts with strategy.entry() and strategy.exit() commands. The script now officially places simulated trades at your exact ATR-based Stop Loss and Take Profit levels.

No Pyramiding: The script is coded to only take one trade at a time (strategy.position_size == 0). It won't open a new long if it's already in an active long.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

The Strategy Code:

Copy and paste this into your Pine Editor, replacing the previous code:

Code: Select all

//@version=5
strategy("Ultimate XAUUSD Scalper Strategy [Forex-Scalping.com]", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.cash_per_order, commission_value=1)

// ==========================================
// 1. USER INPUTS
// ==========================================
grp1 = "Trend & Trigger Settings"
fastEmaLen  = input.int(9, title="Fast EMA Length", group=grp1)
slowEmaLen  = input.int(21, title="Slow EMA Length", group=grp1)
trendEmaLen = input.int(200, title="Baseline Trend EMA", group=grp1)

grp2 = "Momentum & Volatility"
rsiLen      = input.int(14, title="RSI Length", group=grp2)
atrLen      = input.int(14, title="ATR Length", group=grp2)

grp3 = "Risk Management (SL & TP)"
slMultiplier = input.float(1.5, title="Stop Loss ATR Multiplier", step=0.1, group=grp3)
rrRatio      = input.float(2.0, title="Risk/Reward Ratio", step=0.1, group=grp3)

grp4 = "Backtest Date Range"
startDate = input.time(timestamp("2023-01-01T00:00:00"), title="Start Date", group=grp4)
endDate   = input.time(timestamp("2099-12-31T23:59:59"), title="End Date", group=grp4)
inDateRange = true

// ==========================================
// 2. CALCULATIONS
// ==========================================
fastEma  = ta.ema(close, fastEmaLen)
slowEma  = ta.ema(close, slowEmaLen)
trendEma = ta.ema(close, trendEmaLen)
rsiVal   = ta.rsi(close, rsiLen)
atrVal   = ta.atr(atrLen)

// ==========================================
// 3. LOGIC & CONDITIONS
// ==========================================
bullishTrend = close > trendEma
bearishTrend = close < trendEma

buySignal  = ta.crossover(fastEma, slowEma) and bullishTrend and rsiVal > 50
sellSignal = ta.crossunder(fastEma, slowEma) and bearishTrend and rsiVal < 50

// ==========================================
// 4. STRATEGY EXECUTION & TP/SL TRACKING
// ==========================================
var float slLevel = na
var float tpLevel = na

// Only take new trades if we are flat (no active positions)
if buySignal and strategy.position_size == 0 and inDateRange
    slLevel := close - (atrVal * slMultiplier)
    tpLevel := close + (atrVal * slMultiplier * rrRatio)
    strategy.entry("Long", strategy.long)
    strategy.exit("Exit Long", from_entry="Long", stop=slLevel, limit=tpLevel)

if sellSignal and strategy.position_size == 0 and inDateRange
    slLevel := close + (atrVal * slMultiplier)
    tpLevel := close - (atrVal * slMultiplier * rrRatio)
    strategy.entry("Short", strategy.short)
    strategy.exit("Exit Short", from_entry="Short", stop=slLevel, limit=tpLevel)

// Clear the plotting lines when the trade is closed
if strategy.position_size == 0
    slLevel := na
    tpLevel := na

// ==========================================
// 5. PLOTTING
// ==========================================
// EMAs
plot(fastEma, color=color.new(color.blue, 0), title="Fast EMA", linewidth=1)
plot(slowEma, color=color.new(color.orange, 0), title="Slow EMA", linewidth=1)
plot(trendEma, color=color.new(color.white, 0), title="200 EMA Baseline", linewidth=2)

// Target Lines (Only show when in an active trade)
plot(strategy.position_size != 0 ? slLevel : na, title="Stop Loss", color=color.new(color.red, 20), style=plot.style_linebr, linewidth=2)
plot(strategy.position_size != 0 ? tpLevel : na, title="Take Profit", color=color.new(color.green, 20), style=plot.style_linebr, linewidth=2)

// ==========================================
// 6. DASHBOARD TABLE
// ==========================================
var table dash = table.new(position.top_right, 2, 4, border_color=color.new(color.gray, 50), border_width=1, frame_color=color.new(color.gray, 50), frame_width=1)

if barstate.islast
    table.cell(dash, 0, 0, "XAUUSD Scalper", text_color=color.white, bgcolor=color.new(color.blue, 20), text_size=size.small)
    table.cell(dash, 1, 0, "Status", text_color=color.white, bgcolor=color.new(color.blue, 20), text_size=size.small)
    
    table.cell(dash, 0, 1, "Macro Trend", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 1, bullishTrend ? "BULLISH" : "BEARISH", text_color=color.white, bgcolor=bullishTrend ? color.new(color.green, 30) : color.new(color.red, 30), text_size=size.small)
    
    table.cell(dash, 0, 2, "RSI (14)", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 2, str.tostring(math.round(rsiVal, 1)), text_color=color.white, bgcolor=rsiVal > 50 ? color.new(color.green, 30) : color.new(color.red, 30), text_size=size.small)
    
    table.cell(dash, 0, 3, "ATR (14)", text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 3, str.tostring(math.round(atrVal, 2)), text_color=color.white, bgcolor=color.new(color.black, 0), text_size=size.small)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

How to View Your Backtest Results

1.) Click Add to Chart.

2.) Because it is a strategy script, TradingView will automatically open the Strategy Tester panel at the bottom of your screen.

3.) Click on the Overview tab to see your total net profit, maximum drawdown, and win rate.

4.) Click on the List of Trades tab to see a row-by-row accounting of every simulated Long and Short position, exactly where it entered, and whether it hit your SL or TP.

You can now click the gear icon (⚙️) on the indicator to tweak the EMAs, RSI, or Risk/Reward ratio, and the Strategy Tester will instantly recalculate your profit graph so you can find the most optimal settings for your timeframe!
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

To take this from a basic retail script to a Pro-Level / Institutional-grade algorithm, we need to address the three things professional quants care about most: Market Context, Capital Preservation, and Realistic Backtesting.

Amateur scripts trade 24/7 and get chopped up in ranging markets. Pro scripts only trade when volume is present, filter out the chop, and protect profits the moment a trade goes in their favor.

What Makes This Version "Pro-Level":

The "Killzone" Time Filter: Gold is heavily manipulated during low-volume Asian sessions. This script now includes a time filter so it only trades during the London and New York overlaps (when institutional volume drives real trends).

ADX Chop Filter: EMAs are notorious for generating false signals in sideways markets. I've integrated the Average Directional Index (ADX). If the ADX is below 20, the market is flat, and the script will refuse to trade, saving you from whipsaws.

Auto Break-Even (Capital Preservation): You can now toggle a feature that automatically moves your Stop Loss to Break-Even the moment price reaches a 1:1 Risk/Reward.

Realistic Backtest Modeling: The strategy() header now includes realistic commission ($3 per lot) and slippage (2 ticks), so your profit curve reflects what will actually happen in a live brokerage account, rather than a fantasy simulation.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: The Ultimate XAUUSD Scalping Indicator (Pine Script v5) - Trend + Momentum Confluence

Post by PTScalper »

The Pro-Level XAUUSD Strategy Code (Pine Script v5)

Copy and replace your current script in the Pine Editor with this:

Code: Select all

//@version=5
strategy("Institutional XAUUSD Scalper Pro [Forex-Scalping.com]", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=5, commission_type=strategy.commission.cash_per_order, commission_value=3, slippage=2)

// ==========================================
// 1. USER INPUTS
// ==========================================
grp1 = "Trend & Trigger Settings"
fastEmaLen  = input.int(9, title="Fast EMA Length", group=grp1)
slowEmaLen  = input.int(21, title="Slow EMA Length", group=grp1)
trendEmaLen = input.int(200, title="Baseline Trend EMA", group=grp1)

grp2 = "Momentum, Volatility & Chop Filter"
rsiLen       = input.int(14, title="RSI Length", group=grp2)
atrLen       = input.int(14, title="ATR Length", group=grp2)
useAdxFilter = input.bool(true, title="Use ADX Chop Filter?", group=grp2)
adxLen       = input.int(14, title="ADX Length", group=grp2)
adxThreshold = input.int(20, title="ADX Minimum Strength", group=grp2)

grp3 = "Risk Management (SL, TP & Trailing)"
slMultiplier = input.float(1.5, title="Stop Loss ATR Multiplier", step=0.1, group=grp3)
rrRatio      = input.float(2.0, title="Risk/Reward Ratio", step=0.1, group=grp3)
useBreakEven = input.bool(true, title="Move SL to Break-Even at 1R?", group=grp3)

grp4 = "Session & Time Filters"
useSession   = input.bool(true, title="Only Trade During Specific Sessions?", group=grp4)
sessionTime  = input.session("0800-1600", title="Trading Hours (EST)", group=grp4)

// ==========================================
// 2. CALCULATIONS
// ==========================================
fastEma  = ta.ema(close, fastEmaLen)
slowEma  = ta.ema(close, slowEmaLen)
trendEma = ta.ema(close, trendEmaLen)
rsiVal   = ta.rsi(close, rsiLen)
atrVal   = ta.atr(atrLen)

// ADX Calculation
[diPlus, diMinus, adx] = ta.dmi(14, adxLen)

// Time Session Logic
inSession = not useSession or not na(time(timeframe.period, sessionTime, "America/New_York"))

// ==========================================
// 3. LOGIC & CONDITIONS
// ==========================================
bullishTrend = close > trendEma
bearishTrend = close < trendEma
trendStrong  = not useAdxFilter or adx > adxThreshold

buySignal  = ta.crossover(fastEma, slowEma) and bullishTrend and rsiVal > 50 and trendStrong and inSession
sellSignal = ta.crossunder(fastEma, slowEma) and bearishTrend and rsiVal < 50 and trendStrong and inSession

// ==========================================
// 4. STRATEGY EXECUTION & TRADE MANAGEMENT
// ==========================================
var float entryPrice = na
var float slLevel = na
var float tpLevel = na
var bool  beTriggered = false
var float riskAmount = na

// Entry Logic
if buySignal and strategy.position_size == 0
    entryPrice := close
    riskAmount := atrVal * slMultiplier
    slLevel := entryPrice - riskAmount
    tpLevel := entryPrice + (riskAmount * rrRatio)
    beTriggered := false
    strategy.entry("Long", strategy.long)
    strategy.exit("Exit Long", from_entry="Long", stop=slLevel, limit=tpLevel)

if sellSignal and strategy.position_size == 0
    entryPrice := close
    riskAmount := atrVal * slMultiplier
    slLevel := entryPrice + riskAmount
    tpLevel := entryPrice - (riskAmount * rrRatio)
    beTriggered := false
    strategy.entry("Short", strategy.short)
    strategy.exit("Exit Short", from_entry="Short", stop=slLevel, limit=tpLevel)

// Trade Management (Break-Even Logic)
if strategy.position_size > 0 and useBreakEven and not beTriggered
    if high >= entryPrice + riskAmount // Price reached 1R
        slLevel := entryPrice // Move SL to entry
        beTriggered := true
        strategy.exit("Exit Long", from_entry="Long", stop=slLevel, limit=tpLevel)

if strategy.position_size < 0 and useBreakEven and not beTriggered
    if low <= entryPrice - riskAmount // Price reached 1R
        slLevel := entryPrice // Move SL to entry
        beTriggered := true
        strategy.exit("Exit Short", from_entry="Short", stop=slLevel, limit=tpLevel)

// Reset levels when flat
if strategy.position_size == 0
    slLevel := na
    tpLevel := na
    entryPrice := na

// ==========================================
// 5. PLOTTING
// ==========================================
plot(fastEma, color=color.new(color.blue, 0), title="Fast EMA", linewidth=1)
plot(slowEma, color=color.new(color.orange, 0), title="Slow EMA", linewidth=1)
plot(trendEma, color=color.new(color.white, 0), title="200 EMA Baseline", linewidth=2)

// Dynamic Stop Loss and Take Profit Lines
plot(strategy.position_size != 0 ? slLevel : na, title="Stop Loss", color=color.new(color.red, 20), style=plot.style_linebr, linewidth=2)
plot(strategy.position_size != 0 ? tpLevel : na, title="Take Profit", color=color.new(color.green, 20), style=plot.style_linebr, linewidth=2)

// Background Session Highlight
bgcolor(inSession and useSession ? color.new(color.blue, 95) : na, title="Trading Session Highlights")

// ==========================================
// 6. PRO DASHBOARD
// ==========================================
var table dash = table.new(position.top_right, 2, 5, border_color=color.new(color.gray, 80), border_width=1, frame_color=color.new(color.gray, 80), frame_width=1)

if barstate.islast
    table.cell(dash, 0, 0, "PRO SCALPER", text_color=color.white, bgcolor=color.new(#0800ff, 20), text_size=size.small)
    table.cell(dash, 1, 0, "STATUS", text_color=color.white, bgcolor=color.new(#0800ff, 20), text_size=size.small)
    
    table.cell(dash, 0, 1, "Macro Trend", text_color=color.gray, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 1, bullishTrend ? "BULL" : "BEAR", text_color=bullishTrend ? color.green : color.red, bgcolor=color.new(color.black, 0), text_size=size.small)
    
    table.cell(dash, 0, 2, "Volatility (ADX)", text_color=color.gray, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 2, str.tostring(math.round(adx, 1)), text_color=trendStrong ? color.green : color.orange, bgcolor=color.new(color.black, 0), text_size=size.small)
    
    table.cell(dash, 0, 3, "Session Active", text_color=color.gray, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 3, inSession ? "YES" : "NO", text_color=inSession ? color.green : color.red, bgcolor=color.new(color.black, 0), text_size=size.small)

    table.cell(dash, 0, 4, "Trade Status", text_color=color.gray, bgcolor=color.new(color.black, 0), text_size=size.small)
    table.cell(dash, 1, 4, strategy.position_size > 0 ? "LONG" : strategy.position_size < 0 ? "SHORT" : "FLAT", text_color=strategy.position_size != 0 ? color.white : color.gray, bgcolor=strategy.position_size > 0 ? color.new(color.green, 30) : strategy.position_size < 0 ? color.new(color.red, 30) : color.new(color.black, 0), text_size=size.small)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply