Advertisement IC Markets

Free SMC Trading Setups

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: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

Updated Script: Silver Bullet with Liquidity Sweeps

Code: Select all

//@version=5
indicator("ICT Silver Bullet - Sweeps & FVGs", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)

// --- 1. User Inputs ---
sb_time = input.session("1000-1100", title="Silver Bullet Time Window")
tz = input.string("America/New_York", title="Timezone")
box_length = input.int(5, title="Extend FVG Boxes (Bars)")

// Pivot inputs dictate how "major" the swing high/low needs to be.
// 5 left / 2 right is a fast, responsive setting for 1m/5m scalping.
pivot_left = input.int(5, title="Swing High/Low Lookback (Left)")
pivot_right = input.int(2, title="Swing High/Low Lookahead (Right)")

// --- 2. Time Window Logic ---
in_window = not na(time(timeframe.period, sb_time, tz))
bgcolor(in_window ? color.new(color.blue, 90) : na, title="Silver Bullet Background")

// --- 3. Liquidity Pools (Swing Highs / Lows) ---
// Identify pivot points
ph = ta.pivothigh(high, pivot_left, pivot_right)
pl = ta.pivotlow(low, pivot_left, pivot_right)

// Track the most recent pivot levels and their lines
var float last_ph = na
var float last_pl = na
var line active_ph_line = na
var line active_pl_line = na
var bool ph_swept = false
var bool pl_swept = false

// When a new Swing High forms, draw a dashed line forward
if not na(ph)
    last_ph := ph
    ph_swept := false
    active_ph_line := line.new(x1=bar_index[pivot_right], y1=last_ph, x2=bar_index, y2=last_ph, color=color.new(color.red, 40), style=line.style_dashed, width=1)

// When a new Swing Low forms, draw a dashed line forward
if not na(pl)
    last_pl := pl
    pl_swept := false
    active_pl_line := line.new(x1=bar_index[pivot_right], y1=last_pl, x2=bar_index, y2=last_pl, color=color.new(color.green, 40), style=line.style_dashed, width=1)

// --- 4. Detect Liquidity Sweeps ---
// Extend the lines forward until price sweeps them
if not na(active_ph_line) and not ph_swept
    line.set_x2(active_ph_line, bar_index)
    // Buy-side liquidity sweep (Price goes above swing high)
    if high > last_ph
        ph_swept := true
        line.set_color(active_ph_line, color.new(color.red, 0))
        line.set_style(active_ph_line, line.style_solid)
        line.set_width(active_ph_line, 2)

if not na(active_pl_line) and not pl_swept
    line.set_x2(active_pl_line, bar_index)
    // Sell-side liquidity sweep (Price goes below swing low)
    if low < last_pl
        pl_swept := true
        line.set_color(active_pl_line, color.new(color.green, 0))
        line.set_style(active_pl_line, line.style_solid)
        line.set_width(active_pl_line, 2)

// --- 5. Fair Value Gap (FVG) Logic ---
bull_fvg = low > high[2] and close[1] > open[1]
bear_fvg = high < low[2] and close[1] < open[1]

// --- 6. Execution: Draw Setups inside the Window ---
if in_window
    if bull_fvg
        // Draw the FVG box
        box.new(left=bar_index[2], top=low, right=bar_index + box_length, bottom=high[2], border_color=color.new(color.green, 50), bgcolor=color.new(color.green, 85))
        
        // If the Sell-Side Liquidity was swept recently (within last 10 bars), flag it as a prime setup
        if pl_swept and bar_index - line.get_x2(active_pl_line) <= 10
            label.new(bar_index[1], low[2], text="Sweep + FVG\n(Buy)", style=label.style_label_up, color=color.green, textcolor=color.white, size=size.tiny)

    if bear_fvg
        // Draw the FVG box
        box.new(left=bar_index[2], top=low[2], right=bar_index + box_length, bottom=high, border_color=color.new(color.red, 50), bgcolor=color.new(color.red, 85))
        
        // If the Buy-Side Liquidity was swept recently (within last 10 bars), flag it as a prime setup
        if ph_swept and bar_index - line.get_x2(active_ph_line) <= 10
            label.new(bar_index[1], high[2], text="Sweep + FVG\n(Sell)", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny)
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: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

How the Mechanics Work Together:

Dynamic Liquidity Lines: The script calculates swing highs/lows using a 5-bar left / 2-bar right fractal setup. It draws a faint dashed line forward in time, representing resting liquidity pools.

The Sweep Visualization: The moment a candle wick pierces that dashed line, it turns into a thick, solid line. This visually flags that the liquidity has been taken.

The Trigger Validation: If an FVG forms inside the 10:00–11:00 AM window, the script checks if a sweep occurred within the last 10 bars. If the sequence is intact (Sweep → FVG), it prints a "Sweep + FVG" label directly on the chart.

This gives you a highly mechanical way to scrub back through months of 1-minute and 5-minute data to see exactly how often this sequence actually delivers the anticipated reversal, keeping you completely objective during the testing phase.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

Adding the Market Structure Shift (MSS) requirement transforms this from a basic liquidity-hunting script into a complete mechanical trading model.

A sweep without an MSS is just a stop-hunt in a continuing trend. By requiring price to physically close past the opposing fractal (locking in the structural shift) before evaluating the FVG, you confirm the delivery algorithm has actually reversed its objective.

To code this reliably on 1-minute and 5-minute timeframes, we must use a State Machine. This guarantees the exact sequence:

1.) Sweep (wick or close).

2.) MSS (must be a close past the locked-in fractal).

3.) FVG (must form inside the time window).

Here is the updated script. It explicitly draws the MSS lines when they occur, so you can visually verify the sequence step-by-step.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

Updated Script: Silver Bullet (Sweep → MSS → FVG)

Code: Select all

//@version=5
indicator("ICT Silver Bullet - Sweep + MSS + FVG", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)

// --- 1. User Inputs ---
sb_time = input.session("1000-1100", title="Silver Bullet Time Window")
tz = input.string("America/New_York", title="Timezone")
box_length = input.int(5, title="Extend FVG Boxes (Bars)")

pivot_left = input.int(5, title="Swing High/Low Lookback (Left)")
pivot_right = input.int(2, title="Swing High/Low Lookahead (Right)")
max_bars_to_mss = input.int(20, title="Max Bars from Sweep to MSS")
max_bars_to_fvg = input.int(15, title="Max Bars from MSS to FVG")

// --- 2. Time Window Logic ---
in_window = not na(time(timeframe.period, sb_time, tz))
bgcolor(in_window ? color.new(color.blue, 90) : na, title="Silver Bullet Background")

// --- 3. Liquidity Pools & Fractals ---
ph = ta.pivothigh(high, pivot_left, pivot_right)
pl = ta.pivotlow(low, pivot_left, pivot_right)

var float last_ph = na
var int last_ph_bar = na
var float last_pl = na
var int last_pl_bar = na

if not na(ph)
    last_ph := ph
    last_ph_bar := bar_index[pivot_right]
            
if not na(pl)
    last_pl := pl
    last_pl_bar := bar_index[pivot_right]

// --- 4. Sequence State Machine Variables ---
// 0 = Idle
// 1 = BSL Swept (Looking for Bear MSS)
// 2 = Bear MSS Confirmed (Looking for Bear FVG)
// -1 = SSL Swept (Looking for Bull MSS)
// -2 = Bull MSS Confirmed (Looking for Bull FVG)
var int seq_state = 0
var int state_bar = 0

// Lock in the structural level that must be broken for the MSS
var float mss_trigger_level = na
var int mss_trigger_bar = na

// --- 5. Detect Step 1: Liquidity Sweep ---
// Buy-Side Sweep
if high > last_ph and seq_state != 1 and seq_state != 2
    seq_state := 1
    state_bar := bar_index
    mss_trigger_level := last_pl // The low responsible for the sweep
    mss_trigger_bar := last_pl_bar
    
// Sell-Side Sweep
else if low < last_pl and seq_state != -1 and seq_state != -2
    seq_state := -1
    state_bar := bar_index
    mss_trigger_level := last_ph // The high responsible for the sweep
    mss_trigger_bar := last_ph_bar

// --- 6. Detect Step 2: Market Structure Shift (MSS) ---
// Bearish MSS (Requires CLOSE below locked Swing Low)
if seq_state == 1 and close < mss_trigger_level
    if (bar_index - state_bar) <= max_bars_to_mss
        seq_state := 2
        state_bar := bar_index
        // Draw the MSS visual
        line.new(x1=mss_trigger_bar, y1=mss_trigger_level, x2=bar_index, y2=mss_trigger_level, color=color.new(color.red, 20), style=line.style_dashed, width=2)
        label.new(int((mss_trigger_bar + bar_index)/2), mss_trigger_level, "MSS", textcolor=color.red, style=label.style_none, size=size.tiny)
    else
        seq_state := 0 // Timeout

// Bullish MSS (Requires CLOSE above locked Swing High)
else if seq_state == -1 and close > mss_trigger_level
    if (bar_index - state_bar) <= max_bars_to_mss
        seq_state := -2
        state_bar := bar_index
        // Draw the MSS visual
        line.new(x1=mss_trigger_bar, y1=mss_trigger_level, x2=bar_index, y2=mss_trigger_level, color=color.new(color.green, 20), style=line.style_dashed, width=2)
        label.new(int((mss_trigger_bar + bar_index)/2), mss_trigger_level, "MSS", textcolor=color.green, style=label.style_none, size=size.tiny)
    else
        seq_state := 0 // Timeout

// --- 7. Detect Step 3: FVG Execution Inside Window ---
bull_fvg = low > high[2] and close[1] > open[1]
bear_fvg = high < low[2] and close[1] < open[1]

if in_window
    // Bullish Execution
    if bull_fvg and seq_state == -2 and (bar_index - state_bar) <= max_bars_to_fvg
        box.new(left=bar_index[2], top=low, right=bar_index + box_length, bottom=high[2], border_color=color.new(color.green, 50), bgcolor=color.new(color.green, 85))
        label.new(bar_index[1], low[2], text="Valid Setup\n(Buy)", style=label.style_label_up, color=color.green, textcolor=color.white, size=size.tiny)
        seq_state := 0 // Reset after trigger to avoid double printing
        
    // Bearish Execution
    if bear_fvg and seq_state == 2 and (bar_index - state_bar) <= max_bars_to_fvg
        box.new(left=bar_index[2], top=low[2], right=bar_index + box_length, bottom=high, border_color=color.new(color.red, 50), bgcolor=color.new(color.red, 85))
        label.new(bar_index[1], high[2], text="Valid Setup\n(Sell)", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny)
        seq_state := 0 // Reset after trigger
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

Key Mechanical Safeguards Added:

Locked Structural Levels: When a sweep occurs, the script instantly logs the specific fractal high or low that existed before the sweep. This prevents the script from continuously adjusting its MSS threshold if price chops around after the sweep.

Closing Price Confirmation: Wicks through the locked fractal level are ignored. It strictly requires a candle close beyond the fractal to trigger state 2 (MSS Confirmed).

Pacing Timeouts: I added user inputs for max_bars_to_mss (default 20) and max_bars_to_fvg (default 15). If price sweeps liquidity but takes an hour to break structure, or breaks structure but grinds sideways instead of rapidly forming an FVG, the state machine resets. You only want to trade the high-probability explosive sequences.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

This is the final, logical evolution of the framework. Transitioning from a visual indicator to a backtestable Strategy removes the last element of human subjectivity. It forces the computer to objectively answer the only question that matters: Does this specific sequence, at this exact time, actually generate a positive expectancy over a large sample size?

To make this a true backtesting tool, we have added Trade Management (Execution, Stop Loss, and Take Profit).

How the Strategy Execution Works:

Entry: When the FVG is confirmed, it places a Limit order exactly at the proximal edge of the FVG (the top of the gap for longs, the bottom of the gap for shorts). It waits for price to retrace into it.

Stop Loss (SL): Placed at the absolute extreme (the exact highest or lowest point) of the liquidity sweep. This ensures structural protection.

Take Profit (TP): Uses a mechanical Risk:Reward ratio (default 1:2).

Order Cancellation: If the price never retraces to fill the FVG limit order within a set number of bars, the pending order is cancelled to avoid late, low-probability fills.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

Here is the complete Strategy script.

Code: Select all

//@version=5
strategy("ICT Silver Bullet Strategy", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=2, max_boxes_count=500, max_lines_count=500)

// --- 1. User Inputs ---
sb_time = input.session("1000-1100", title="Silver Bullet Time Window")
tz = input.string("America/New_York", title="Timezone")

// Trade Management Inputs
rr_ratio = input.float(2.0, title="Risk:Reward Ratio", step=0.1)
limit_timeout = input.int(10, title="Max Bars to Fill FVG Limit Order")

// Structural Inputs
pivot_left = input.int(5, title="Swing High/Low Lookback (Left)")
pivot_right = input.int(2, title="Swing High/Low Lookahead (Right)")
max_bars_to_mss = input.int(20, title="Max Bars from Sweep to MSS")
max_bars_to_fvg = input.int(15, title="Max Bars from MSS to FVG")

// --- 2. Time Window Logic ---
in_window = not na(time(timeframe.period, sb_time, tz))
bgcolor(in_window ? color.new(color.blue, 95) : na, title="Silver Bullet Background")

// --- 3. Liquidity Pools & Fractals ---
ph = ta.pivothigh(high, pivot_left, pivot_right)
pl = ta.pivotlow(low, pivot_left, pivot_right)

var float last_ph = na
var int last_ph_bar = na
var float last_pl = na
var int last_pl_bar = na

if not na(ph)
    last_ph := ph
    last_ph_bar := bar_index[pivot_right]
if not na(pl)
    last_pl := pl
    last_pl_bar := bar_index[pivot_right]

// --- 4. Sequence State Machine Variables ---
var int seq_state = 0
var int state_bar = 0
var float mss_trigger_level = na
var float sweep_extreme = na // Tracks the absolute high/low of the sweep for the SL
var int fvg_bar = na // Tracks when the FVG formed to timeout the limit order

// --- 5. Detect Step 1: Liquidity Sweep ---
// Buy-Side Sweep (Looking for Short Setup)
if high > last_ph and seq_state != 1 and seq_state != 2
    seq_state := 1
    state_bar := bar_index
    mss_trigger_level := last_pl 
    sweep_extreme := high // Initialize extreme
    
// Sell-Side Sweep (Looking for Long Setup)
else if low < last_pl and seq_state != -1 and seq_state != -2
    seq_state := -1
    state_bar := bar_index
    mss_trigger_level := last_ph 
    sweep_extreme := low // Initialize extreme

// Track the absolute extreme during the sweep phase for precise Stop Loss placement
if seq_state == 1
    sweep_extreme := math.max(sweep_extreme, high)
if seq_state == -1
    sweep_extreme := math.min(sweep_extreme, low)

// --- 6. Detect Step 2: Market Structure Shift (MSS) ---
// Bearish MSS
if seq_state == 1 and close < mss_trigger_level
    if (bar_index - state_bar) <= max_bars_to_mss
        seq_state := 2
        state_bar := bar_index
        line.new(x1=last_pl_bar, y1=mss_trigger_level, x2=bar_index, y2=mss_trigger_level, color=color.red, style=line.style_dashed)
    else
        seq_state := 0 

// Bullish MSS
else if seq_state == -1 and close > mss_trigger_level
    if (bar_index - state_bar) <= max_bars_to_mss
        seq_state := -2
        state_bar := bar_index
        line.new(x1=last_ph_bar, y1=mss_trigger_level, x2=bar_index, y2=mss_trigger_level, color=color.green, style=line.style_dashed)
    else
        seq_state := 0 

// --- 7. Detect Step 3: FVG Formation & Order Execution ---
bull_fvg = low > high[2] and close[1] > open[1]
bear_fvg = high < low[2] and close[1] < open[1]

// Only look for setups if we don't already have an open trade
if strategy.position_size == 0
    if in_window
        // Bullish Execution
        if bull_fvg and seq_state == -2 and (bar_index - state_bar) <= max_bars_to_fvg
            box.new(left=bar_index[2], top=low, right=bar_index, bottom=high[2], border_color=color.new(color.green, 50), bgcolor=color.new(color.green, 85))
            
            // Order Math
            entry_price = high[2] // Top of the Bull FVG
            sl_price = sweep_extreme // The absolute low of the sweep
            risk = entry_price - sl_price
            tp_price = entry_price + (risk * rr_ratio)
            
            if risk > 0
                strategy.entry("Long", strategy.long, limit=entry_price)
                strategy.exit("Exit Long", "Long", stop=sl_price, limit=tp_price)
                fvg_bar := bar_index // Start the timeout clock
                seq_state := 0 // Reset state machine
            
        // Bearish Execution
        if bear_fvg and seq_state == 2 and (bar_index - state_bar) <= max_bars_to_fvg
            box.new(left=bar_index[2], top=low[2], right=bar_index, bottom=high, border_color=color.new(color.red, 50), bgcolor=color.new(color.red, 85))
            
            // Order Math
            entry_price = low[2] // Bottom of the Bear FVG
            sl_price = sweep_extreme // The absolute high of the sweep
            risk = sl_price - entry_price
            tp_price = entry_price - (risk * rr_ratio)
            
            if risk > 0
                strategy.entry("Short", strategy.short, limit=entry_price)
                strategy.exit("Exit Short", "Short", stop=sl_price, limit=tp_price)
                fvg_bar := bar_index // Start the timeout clock
                seq_state := 0 // Reset state machine

// --- 8. Pending Order Timeout ---
// Cancel pending limit orders if price doesn't retrace to the FVG within the timeout limit
if strategy.position_size == 0 and not na(fvg_bar) and (bar_index - fvg_bar) >= limit_timeout
    strategy.cancel_all()
    fvg_bar := na
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

How to use this for professional Backtesting:

Load it properly: Paste this into the Pine Editor, save it, and click "Add to Chart". Ensure you are on a 1-minute or 3-minute chart for an asset like NQ (Nasdaq), ES (S&P 500), or EUR/USD.

Review the "Strategy Tester" Tab: At the bottom of TradingView, the Strategy Tester tab will now populate. It will show you the exact Net Profit, Win Rate, Max Drawdown, and Profit Factor for every Silver Bullet setup over your chart's historical data.

Optimize Responsibly (No Curve-Fitting):

The right way to optimize: Adjust the "Risk:Reward Ratio" (try 1.5 vs 2.0 vs 3.0) to see if you are leaving money on the table or setting unrealistic targets.

The wrong way to optimize: Shifting the time window by 15-minute increments until you find a "magic" window that happens to have a 70% win rate over the last 30 days. That is curve-fitting, and it will break the moment you trade it with real money.

If this Strategy yields a flat or negative profit curve out-of-the-box on your chosen asset, listen to the data. It means the exact time-window parameter does not natively generate the claimed edge without requiring further (highly discretionary) human filters.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

Moving this framework into MQL4 and MQL5 shifts it from a visual overlay into a pure execution engine. Since MetaTrader handles pending orders and bar data differently than Pine Script, the logic needs to be bound to the OnTick() event, specifically filtering for new bar generation to evaluate the state machine without repainting.

Unlike TradingView, MT4/MT5 execute on broker server time, not local or NY time. You will need to manually offset the StartTime and EndTime inputs to match 10:00-11:00 AM NY time based on your specific broker's UTC offset.

Here is the mechanical translation of the Sweep → MSS → FVG strategy for both platforms. To optimize backtesting speed, visual object drawing (boxes and lines) has been omitted in favor of pure order execution.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 3027
Joined: Mon Jul 20, 2026 1:28 pm

Re: Free SMC Trading Setups

Post by PTScalper »

MetaTrader 4 (MQL4) Expert Advisor

Code: Select all

//+------------------------------------------------------------------+
//|                                              SilverBullet_EA.mq4 |
//+------------------------------------------------------------------+
#property copyright "Execution Engine"
#property link      ""
#property version   "1.00"
#property strict

//--- Inputs
input string   StartTime         = "17:00"; // Broker Time for NY 10:00
input string   EndTime           = "18:00"; // Broker Time for NY 11:00
input double   RiskReward        = 2.0;
input double   RiskPercent       = 2.0;
input int      ExpirationBars    = 10;
input int      PivotLeft         = 5;
input int      PivotRight        = 2;
input int      MaxBarsToMSS      = 20;
input int      MaxBarsToFVG      = 15;
input int      MagicNumber       = 101101;

//--- State Variables
int            seq_state         = 0;
datetime       state_time        = 0;
double         mss_trigger_level = 0.0;
double         sweep_extreme     = 0.0;
double         last_ph           = 0.0;
double         last_pl           = 0.0;
datetime       last_bar_time     = 0;

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // Execute only on bar close/new bar open
    if(Time[0] == last_bar_time) return;
    last_bar_time = Time[0];

    // 1. Update Fractals (Shifted by PivotRight to ensure confirmation)
    int p_shift = PivotRight + 1;
    
    bool is_ph = true;
    for(int i = 1; i <= PivotLeft; i++)  { if(High[p_shift+i] > High[p_shift]) is_ph = false; }
    for(int i = 1; i <= PivotRight; i++) { if(High[p_shift-i] >= High[p_shift]) is_ph = false; }
    if(is_ph) last_ph = High[p_shift];

    bool is_pl = true;
    for(int i = 1; i <= PivotLeft; i++)  { if(Low[p_shift+i] < Low[p_shift]) is_pl = false; }
    for(int i = 1; i <= PivotRight; i++) { if(Low[p_shift-i] <= Low[p_shift]) is_pl = false; }
    if(is_pl) last_pl = Low[p_shift];

    // Calculate bars passed since state change
    int bars_passed = iBarShift(Symbol(), Period(), state_time);

    // 2. Step 1: Detect Liquidity Sweep
    if(High[1] > last_ph && last_ph > 0 && seq_state != 1 && seq_state != 2)
    {
        seq_state = 1;
        state_time = Time[1];
        mss_trigger_level = last_pl;
        sweep_extreme = High[1];
    }
    else if(Low[1] < last_pl && last_pl > 0 && seq_state != -1 && seq_state != -2)
    {
        seq_state = -1;
        state_time = Time[1];
        mss_trigger_level = last_ph;
        sweep_extreme = Low[1];
    }

    // Track extremes during sweep phase
    if(seq_state == 1 && High[1] > sweep_extreme) sweep_extreme = High[1];
    if(seq_state == -1 && Low[1] < sweep_extreme) sweep_extreme = Low[1];

    // 3. Step 2: Detect MSS
    if(seq_state == 1 && Close[1] < mss_trigger_level)
    {
        if(bars_passed <= MaxBarsToMSS) { seq_state = 2; state_time = Time[1]; }
        else seq_state = 0;
    }
    else if(seq_state == -1 && Close[1] > mss_trigger_level)
    {
        if(bars_passed <= MaxBarsToMSS) { seq_state = -2; state_time = Time[1]; }
        else seq_state = 0;
    }

    // 4. Step 3: FVG and Execution
    if(!IsWithinWindow()) return;
    if(TotalOpenOrders() > 0) return;

    bool bull_fvg = (Low[1] > High[3] && Close[2] > Open[2]);
    bool bear_fvg = (High[1] < Low[3] && Close[2] < Open[2]);

    double lot_size = CalculateLotSize(MathAbs(Close[1] - sweep_extreme));

    if(bull_fvg && seq_state == -2 && bars_passed <= MaxBarsToFVG)
    {
        double entry = High[3];
        double sl = sweep_extreme;
        double tp = entry + ((entry - sl) * RiskReward);
        datetime exp = TimeCurrent() + (ExpirationBars * PeriodSeconds());
        
        int ticket = OrderSend(Symbol(), OP_BUYLIMIT, lot_size, entry, 3, sl, tp, "SilverBullet Long", MagicNumber, exp, clrGreen);
        if(ticket > 0) seq_state = 0;
    }
    
    if(bear_fvg && seq_state == 2 && bars_passed <= MaxBarsToFVG)
    {
        double entry = Low[3];
        double sl = sweep_extreme;
        double tp = entry - ((sl - entry) * RiskReward);
        datetime exp = TimeCurrent() + (ExpirationBars * PeriodSeconds());
        
        int ticket = OrderSend(Symbol(), OP_SELLLIMIT, lot_size, entry, 3, sl, tp, "SilverBullet Short", MagicNumber, exp, clrRed);
        if(ticket > 0) seq_state = 0;
    }
}

//+------------------------------------------------------------------+
//| Helper Functions                                                 |
//+------------------------------------------------------------------+
bool IsWithinWindow()
{
    string current_time = TimeToStr(TimeCurrent(), TIME_MINUTES);
    return (current_time >= StartTime && current_time <= EndTime);
}

int TotalOpenOrders()
{
    int count = 0;
    for(int i = OrdersTotal() - 1; i >= 0; i--)
    {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) count++;
    }
    return count;
}

double CalculateLotSize(double risk_points)
{
    if(risk_points == 0) return 0.01;
    double risk_amount = AccountBalance() * (RiskPercent / 100.0);
    double tick_value = MarketInfo(Symbol(), MODE_TICKVALUE);
    double tick_size = MarketInfo(Symbol(), MODE_TICKSIZE);
    double step = MarketInfo(Symbol(), MODE_LOTSTEP);
    
    double lots = risk_amount / ((risk_points / tick_size) * tick_value);
    return MathMax(MarketInfo(Symbol(), MODE_MINLOT), NormalizeDouble(MathFloor(lots/step)*step, 2));
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply