Page 1 of 2

Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Thu Sep 17, 2026 2:22 am
by LondonScalper
My default gold scalp template is deliberately plain.

M5 decides bias — structure and impulse direction. M1 handles entry — retest, reclaim, or pullback hold. Hard time stop: if the idea has not worked within a defined window, I exit even if the protective stop has not been hit. Gold can drift you into a larger loss while you wait for "your level" to be respected out of stubbornness.

No stacking five indicators to bless the click. If M5 bias is unclear, there is no M1 entry. If M1 is chaotic, I do not invent precision — I either wait for M5 clarity or pass.

I review time-stop exits separately from stop-outs. They teach different lessons about patience versus stubbornness.

The time stop is written in minutes on the card so I cannot renegotiate it while gold is chopping me.
  • Do you use a time stop on gold scalps?
  • What M5 cue is mandatory before you open M1?
Template critique welcome.

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:52 pm
by PTScalper
LondonScalper wrote: Thu Sep 17, 2026 2:22 am My default gold scalp template is deliberately plain.

M5 decides bias — structure and impulse direction. M1 handles entry — retest, reclaim, or pullback hold. Hard time stop: if the idea has not worked within a defined window, I exit even if the protective stop has not been hit. Gold can drift you into a larger loss while you wait for "your level" to be respected out of stubbornness.

No stacking five indicators to bless the click. If M5 bias is unclear, there is no M1 entry. If M1 is chaotic, I do not invent precision — I either wait for M5 clarity or pass.

I review time-stop exits separately from stop-outs. They teach different lessons about patience versus stubbornness.

The time stop is written in minutes on the card so I cannot renegotiate it while gold is chopping me.
  • Do you use a time stop on gold scalps?
  • What M5 cue is mandatory before you open M1?
Template critique welcome.
Hi LondonScalper,

By stripping away lagging indicators and relying strictly on the interplay between M5 structure and M1 execution, you have built a system that defends against Gold’s (XAUUSD) worst behavior: the slow, account-draining bleed of consolidation chop.

Here is a detailed breakdown of your template, followed by answers to your specific questions.

Critique of the Template

1. The Brilliance of the Time Stop

Gold is notoriously algorithmic and momentum-driven. When it breaks, it moves violently; when it consolidates, it hunts liquidity in both directions. Your hard time stop recognizes a fundamental truth of scalping: if the trade relies on momentum, the absence of immediate momentum means the premise is already wrong. Writing the minutes down on a physical card is a superb psychological hack to bypass the bargaining phase of a stagnant trade.

2. Asymmetric Journaling

Separating time-stop exits from hard stop-outs is the most advanced component of your template. They represent entirely different failure modes.

A stop-out means your spatial invalidation level was incorrect or hunted.

A time-stop means your momentum expectation was incorrect.
Tracking these separately allows you to fine-tune your entry timing without questioning your structural analysis.

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:53 pm
by PTScalper
3. The M5/M1 Hierarchy

Refusing to invent precision on a chaotic M1 chart when the M5 is unclear prevents overtrading. The M1 timeframe is highly susceptible to spread fluctuations and localized noise. Tethering it strictly to M5 clarity ensures you are only executing when a higher-timeframe narrative is actively unfolding.

Do I use a time stop on gold scalps?

From a computational and algorithmic system-design perspective—whether programming execution logic in MQL5, cAlgo, or Pine Script—a time-based exit is one of the most mathematically robust filters you can apply to a momentum strategy.

In algorithmic models, alpha decays rapidly the longer a position sits in a range. If a setup is based on an anticipated impulse (like a retest or reclaim), the probability of success drops exponentially for every minute the market fails to expand. A time stop mathematically enforces the rule that "neutral" is actually a losing condition when you are paying spread and assuming exposure risk.

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:53 pm
by PTScalper
What M5 cue is mandatory before opening M1?

To justify dropping to the M1 timeframe for a surgical entry, the M5 must demonstrate unequivocal displacement or a confirmed trap. Without one of these cues, the M1 chart is merely a random walk.

The mandatory M5 cues should be:

A clear Liquidity Sweep (The Trap): The M5 candle wicks aggressively through a key swing high or low, but the body closes firmly back inside the previous range. This confirms the larger timeframe has absorbed breakout liquidity and is ready to reverse. You drop to M1 to catch the structural shift back in the opposite direction.

Decisive Displacement (The Impulse): The M5 breaks structure (BoS) with strong, full-bodied momentum (no heavy wicks against the move), leaving behind a clear inefficiency or unmitigated block. You drop to M1 to execute on the first clean pullback into that M5 inefficiency.

Reclaim of a Key Level: If the M5 loses a significant structural level but immediately reclaims it with strong volume in the next candle, the false breakdown becomes the catalyst. The M1 is then used to buy the immediate retest of the reclaimed level.

If the M5 is printing alternating dojis or small bodies inside the previous candle's range, there is no displacement and no trap. In that scenario, opening the M1 chart only invites the temptation to gamble on noise.

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:54 pm
by PTScalper
This MQL5 template translates your discretionary logic into an automated algorithmic framework. Because MQL5 syntax is highly comparable to C#, the architecture is modular and decoupled.

The core mechanical rules—specifically the strict Time Stop and the M5/M1 timeframe hierarchy—are fully implemented. The subjective price action components (identifying the exact structural sweep or displacement) are compartmentalized into distinct methods, allowing you to inject your specific mathematical definitions of a sweep or BoS (Break of Structure).

The MQL5 Scalp Template

Code: Select all

//+------------------------------------------------------------------+
//|                                              GoldScalp_Template.mq5|
//|                                      Strict Time-Stop Architecture |
//+------------------------------------------------------------------+
#property copyright "Asymmetric Journaling Template"
#property version   "1.00"

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>

//--- Inputs
input group "Risk Management"
input double   InpLotSize        = 0.1;       // Lot Size
input int      InpStopLossPts    = 200;       // Hard Stop Loss (in points)
input int      InpTakeProfitPts  = 400;       // Take Profit (in points)

input group "Time Stop Mechanics"
input int      InpTimeStopMins   = 15;        // Time Stop Window (minutes)

input group "System Parameters"
input ulong    InpMagicNumber    = 100100;    // EA Magic Number
input string   InpTradeComment   = "M5_M1_Scalp"; // Trade Comment

//--- Globals
CTrade         m_trade;
CPositionInfo  m_position;
CSymbolInfo    m_symbol;

enum ENUM_MARKET_BIAS {
    BIAS_NONE = 0,
    BIAS_LONG = 1,
    BIAS_SHORT = -1
};

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    if(!m_symbol.Name(_Symbol)) return(INIT_FAILED);
    
    m_trade.SetExpertMagicNumber(InpMagicNumber);
    m_trade.SetMarginMode();
    m_trade.SetTypeFillingBySymbol(_Symbol);

    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // 1. Manage existing positions (Time Stop Enforcement)
    if(PositionsTotal() > 0)
    {
        ManageOpenPositions();
    }
    // 2. Scan for new entries if flat
    else
    {
        EvaluateEntry();
    }
}

//+------------------------------------------------------------------+
//| Enforces the strict time-stop exit rule                          |
//+------------------------------------------------------------------+
void ManageOpenPositions()
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(m_position.SelectByIndex(i))
        {
            if(m_position.Symbol() == _Symbol && m_position.Magic() == InpMagicNumber)
            {
                datetime openTime = m_position.Time();
                datetime currentTime = TimeCurrent();
                
                // Calculate elapsed time in seconds
                int elapsedSeconds = (int)(currentTime - openTime);
                int timeLimitSeconds = InpTimeStopMins * 60;
                
                if(elapsedSeconds >= timeLimitSeconds)
                {
                    double pnl = m_position.Profit();
                    ulong ticket = m_position.Ticket();
                    
                    // Asymmetric Journaling: Log the specific time-stop exit BEFORE closing
                    PrintFormat("TIME STOP TRIGGERED: Ticket #%I64u | Elapsed: %d mins | PnL: %.2f. Reason: Lack of momentum.", 
                                ticket, elapsedSeconds/60, pnl);
                                
                    m_trade.PositionClose(ticket);
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Coordinates the M5/M1 hierarchy for execution                    |
//+------------------------------------------------------------------+
void EvaluateEntry()
{
    // Step 1: Establish M5 Bias (Structure & Impulse)
    ENUM_MARKET_BIAS m5Bias = GetM5Bias();
    
    if(m5Bias == BIAS_NONE) 
        return; // M5 is chaotic or unclear. Pass.
        
    // Step 2: Validate M1 Entry (Retest/Reclaim)
    if(m5Bias == BIAS_LONG && ValidateM1Entry(BIAS_LONG))
    {
        ExecuteTrade(ORDER_TYPE_BUY);
    }
    else if(m5Bias == BIAS_SHORT && ValidateM1Entry(BIAS_SHORT))
    {
        ExecuteTrade(ORDER_TYPE_SELL);
    }
}

//+------------------------------------------------------------------+
//| PLACEHOLDER: Define your M5 structural sweep or displacement     |
//+------------------------------------------------------------------+
ENUM_MARKET_BIAS GetM5Bias()
{
    // Arrays to hold M5 price data
    double close[], open[], high[], low[];
    ArraySetAsSeries(close, true); ArraySetAsSeries(open, true);
    ArraySetAsSeries(high, true); ArraySetAsSeries(low, true);
    
    CopyClose(_Symbol, PERIOD_M5, 1, 3, close);
    CopyOpen(_Symbol, PERIOD_M5, 1, 3, open);
    CopyHigh(_Symbol, PERIOD_M5, 1, 3, high);
    CopyLow(_Symbol, PERIOD_M5, 1, 3, low);

    /* 
       INJECT PRICE ACTION LOGIC HERE
       Example: Detect a strong bullish displacement (BoS) or a sweep of a key low.
       If the candle body is large and closes near the high -> BIAS_LONG
    */
    
    // Naive example condition (Replace with your structural logic)
    double bodySize = MathAbs(open[0] - close[0]);
    double totalSize = high[0] - low[0];
    
    if(totalSize > 0 && bodySize/totalSize > 0.8) // Strong full-bodied candle
    {
        if(close[0] > open[0]) return BIAS_LONG;
        if(close[0] < open[0]) return BIAS_SHORT;
    }

    return BIAS_NONE;
}

//+------------------------------------------------------------------+
//| PLACEHOLDER: Define your M1 execution trigger                    |
//+------------------------------------------------------------------+
bool ValidateM1Entry(ENUM_MARKET_BIAS bias)
{
    double close[], open[];
    ArraySetAsSeries(close, true); ArraySetAsSeries(open, true);
    
    CopyClose(_Symbol, PERIOD_M1, 1, 2, close);
    CopyOpen(_Symbol, PERIOD_M1, 1, 2, open);
    
    /* 
       INJECT ENTRY LOGIC HERE
       Example: Wait for a specific M1 pullback candle to close, 
       or an engulfing candle confirming the retest holds.
    */
    
    // Naive example: Require a small pullback/pause candle on M1 to hold
    if(bias == BIAS_LONG && close[0] > open[0]) return true;
    if(bias == BIAS_SHORT && close[0] < open[0]) return true;

    return false;
}

//+------------------------------------------------------------------+
//| Executes the trade with physical Hard Stop and TP                |
//+------------------------------------------------------------------+
void ExecuteTrade(ENUM_ORDER_TYPE orderType)
{
    m_symbol.RefreshRates();
    
    double price = (orderType == ORDER_TYPE_BUY) ? m_symbol.Ask() : m_symbol.Bid();
    double sl = 0.0, tp = 0.0;
    
    if(orderType == ORDER_TYPE_BUY)
    {
        sl = price - (InpStopLossPts * m_symbol.Point());
        tp = price + (InpTakeProfitPts * m_symbol.Point());
    }
    else
    {
        sl = price + (InpStopLossPts * m_symbol.Point());
        tp = price - (InpTakeProfitPts * m_symbol.Point());
    }
    
    if(m_trade.PositionOpen(_Symbol, orderType, InpLotSize, price, sl, tp, InpTradeComment))
    {
        PrintFormat("ENTRY EXECUTED: %s at %.3f. Time Stop initialized for %d mins.", 
                    EnumToString(orderType), price, InpTimeStopMins);
    }
}

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:55 pm
by PTScalper
Architectural Breakdown

The ManageOpenPositions() Method
This routine runs on every tick while a position is open. It calculates the delta between the position's POSITION_TIME and TimeCurrent(). If the delta exceeds your InpTimeStopMins converted to seconds, the EA forcibly closes the position.

Explicit Journaling Separations
Notice the PrintFormat log directly above the PositionClose command. It explicitly prints TIME STOP TRIGGERED. If the trade hits your hard SL or TP, the broker handles it natively, and it is logged standardly as deal sl or deal tp in your terminal. This provides the distinct data streams you need to audit patience vs. stubbornness.

Decoupled Evaluation Pipeline
EvaluateEntry() strictly enforces your hierarchy. GetM5Bias() is evaluated first. If it returns BIAS_NONE, the execution terminates immediately—the M1 arrays are not even loaded into memory. M1 is entirely subordinate to M5 clarity.

Data Injection Zones
The GetM5Bias() and ValidateM1Entry() methods are currently populated with naive, placeholder candle-math. You will replace this logic with your specific parameters for liquidity sweeps (e.g., comparing wick lengths to previous session highs/lows) or structure breaks.

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:56 pm
by PTScalper
Here is the translated MQL4 implementation.

Unlike MQL5’s object-oriented trade classes (CTrade, CPositionInfo), MQL4 relies on a procedural pool of open orders using OrderSelect() and OrdersTotal(). The logic for the strict Time Stop and the rigid M5/M1 hierarchy has been fully adapted to native MQL4 syntax.

Code: Select all

//+------------------------------------------------------------------+
//|                                              GoldScalp_Template.mq4|
//|                                      Strict Time-Stop Architecture |
//+------------------------------------------------------------------+
#property copyright "Asymmetric Journaling Template"
#property version   "1.00"
#property strict // Enforces strict compilation mode

//--- Inputs
input double   InpLotSize        = 0.1;       // Lot Size
input int      InpStopLossPts    = 200;       // Hard Stop Loss (in points)
input int      InpTakeProfitPts  = 400;       // Take Profit (in points)
input int      InpTimeStopMins   = 15;        // Time Stop Window (minutes)
input int      InpSlippage       = 30;        // Permitted slippage (points)
input int      InpMagicNumber    = 100100;    // EA Magic Number
input string   InpTradeComment   = "M5_M1_Scalp"; // Trade Comment

//--- Globals
enum ENUM_MARKET_BIAS {
    BIAS_NONE = 0,
    BIAS_LONG = 1,
    BIAS_SHORT = -1
};

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // 1. Manage existing positions (Time Stop Enforcement)
    if(CountOpenPositions() > 0)
    {
        ManageOpenPositions();
    }
    // 2. Scan for new entries if flat
    else
    {
        EvaluateEntry();
    }
}

//+------------------------------------------------------------------+
//| Helper: Counts open trades matching this EA                      |
//+------------------------------------------------------------------+
int CountOpenPositions()
{
    int count = 0;
    for(int i = OrdersTotal() - 1; i >= 0; i--)
    {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == InpMagicNumber)
            {
                count++;
            }
        }
    }
    return count;
}

//+------------------------------------------------------------------+
//| Enforces the strict time-stop exit rule                          |
//+------------------------------------------------------------------+
void ManageOpenPositions()
{
    for(int i = OrdersTotal() - 1; i >= 0; i--)
    {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == InpMagicNumber)
            {
                datetime openTime = OrderOpenTime();
                datetime currentTime = TimeCurrent();
                
                // Calculate elapsed time in seconds
                int elapsedSeconds = (int)(currentTime - openTime);
                int timeLimitSeconds = InpTimeStopMins * 60;
                
                if(elapsedSeconds >= timeLimitSeconds)
                {
                    double pnl = OrderProfit();
                    int ticket = OrderTicket();
                    
                    // Determine correct closing price based on order type
                    double closePrice = (OrderType() == OP_BUY) ? Bid : Ask;
                    
                    // Asymmetric Journaling: Log the specific time-stop exit BEFORE closing
                    PrintFormat("TIME STOP TRIGGERED: Ticket #%d | Elapsed: %d mins | PnL: %.2f. Reason: Lack of momentum.", 
                                ticket, elapsedSeconds/60, pnl);
                                
                    bool closed = OrderClose(ticket, OrderLots(), closePrice, InpSlippage, clrRed);
                    if(!closed)
                    {
                        Print("Failed to close order via Time Stop. Error code: ", GetLastError());
                    }
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Coordinates the M5/M1 hierarchy for execution                    |
//+------------------------------------------------------------------+
void EvaluateEntry()
{
    // Step 1: Establish M5 Bias (Structure & Impulse)
    ENUM_MARKET_BIAS m5Bias = GetM5Bias();
    
    if(m5Bias == BIAS_NONE) 
        return; // M5 is chaotic or unclear. Pass.
        
    // Step 2: Validate M1 Entry (Retest/Reclaim)
    if(m5Bias == BIAS_LONG && ValidateM1Entry(BIAS_LONG))
    {
        ExecuteTrade(OP_BUY);
    }
    else if(m5Bias == BIAS_SHORT && ValidateM1Entry(BIAS_SHORT))
    {
        ExecuteTrade(OP_SELL);
    }
}

//+------------------------------------------------------------------+
//| PLACEHOLDER: Define your M5 structural sweep or displacement     |
//+------------------------------------------------------------------+
ENUM_MARKET_BIAS GetM5Bias()
{
    // Retrieve previous M5 candle data natively in MQL4
    double close_1 = iClose(Symbol(), PERIOD_M5, 1);
    double open_1  = iOpen(Symbol(), PERIOD_M5, 1);
    double high_1  = iHigh(Symbol(), PERIOD_M5, 1);
    double low_1   = iLow(Symbol(), PERIOD_M5, 1);
    
    /* 
       INJECT PRICE ACTION LOGIC HERE
       Example: Detect a strong bullish displacement (BoS) or a sweep of a key low.
    */
    
    double bodySize = MathAbs(open_1 - close_1);
    double totalSize = high_1 - low_1;
    
    if(totalSize > 0 && (bodySize / totalSize) > 0.8) // Strong full-bodied candle
    {
        if(close_1 > open_1) return BIAS_LONG;
        if(close_1 < open_1) return BIAS_SHORT;
    }

    return BIAS_NONE;
}

//+------------------------------------------------------------------+
//| PLACEHOLDER: Define your M1 execution trigger                    |
//+------------------------------------------------------------------+
bool ValidateM1Entry(ENUM_MARKET_BIAS bias)
{
    // Retrieve previous M1 candle data natively in MQL4
    double close_1 = iClose(Symbol(), PERIOD_M1, 1);
    double open_1  = iOpen(Symbol(), PERIOD_M1, 1);
    
    /* 
       INJECT ENTRY LOGIC HERE
       Example: Wait for a specific M1 pullback candle to close, 
       or an engulfing candle confirming the retest holds.
    */
    
    // Naive example: Require a small pullback/pause candle on M1 to hold
    if(bias == BIAS_LONG && close_1 > open_1) return true;
    if(bias == BIAS_SHORT && close_1 < open_1) return true;

    return false;
}

//+------------------------------------------------------------------+
//| Executes the trade with physical Hard Stop and TP                |
//+------------------------------------------------------------------+
void ExecuteTrade(int orderType)
{
    RefreshRates(); // Ensure Ask/Bid are up to date for precise execution
    
    double price = (orderType == OP_BUY) ? Ask : Bid;
    double sl = 0.0, tp = 0.0;
    
    if(orderType == OP_BUY)
    {
        sl = price - (InpStopLossPts * Point);
        tp = price + (InpTakeProfitPts * Point);
    }
    else
    {
        sl = price + (InpStopLossPts * Point);
        tp = price - (InpTakeProfitPts * Point);
    }
    
    // Send the order to the broker
    int ticket = OrderSend(Symbol(), orderType, InpLotSize, price, InpSlippage, sl, tp, InpTradeComment, InpMagicNumber, 0, (orderType == OP_BUY) ? clrBlue : clrRed);
    
    if(ticket > 0)
    {
        PrintFormat("ENTRY EXECUTED: %s at %.3f. Time Stop initialized for %d mins.", 
                    (orderType == OP_BUY) ? "BUY" : "SELL", price, InpTimeStopMins);
    }
    else
    {
        Print("OrderSend failed. Error code: ", GetLastError());
    }
}

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:57 pm
by PTScalper
Key Differences from the MQL5 Template

Procedural Execution: Notice the shift from m_trade.PositionOpen() to the procedural OrderSend() function.

Time Stop Checking: MQL4 uses the pool scan OrderSelect(i, SELECT_BY_POS, MODE_TRADES) to iterate through open tickets. The Time Stop function subtracts the native OrderOpenTime() from TimeCurrent() and closes out using the required Bid or Ask price.

Direct Time-Series Access: The complex array loading (CopyClose(), CopyHigh()) from MQL5 has been stripped down to MQL4’s native iClose(), iOpen(), iHigh(), and iLow(), pointing strictly at the current symbol and relevant timeframes (PERIOD_M5 and PERIOD_M1).

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:59 pm
by PTScalper
Here is the translation into TradingView’s Pine Script (v5).

Because Pine Script executes strictly top-to-bottom on every bar, the architecture differs from the event-driven loops of MQL4/5. To replicate the M5/M1 hierarchy, this script must be applied to the 1-minute (M1) chart.

By running it on M1, we can pull higher-timeframe M5 data using request.security() while treating "minutes" as "bars" for the Time Stop logic.

Re: Two-timeframe gold scalp: M5 bias, M1 entry, hard time stop

Posted: Sun Sep 27, 2026 2:59 pm
by PTScalper
The Pine Script Template

Code: Select all

//@version=5
strategy("Gold Scalp Template - Asymmetric Journaling", overlay=true, calc_on_every_tick=true, initial_capital=10000, currency=currency.USD)

// =========================================================================
// INPUTS
// =========================================================================
grpRisk = "Risk Management"
inpLotSize    = input.float(0.1, title="Lot Size (Qty)", group=grpRisk)
inpStopLoss   = input.int(200, title="Hard Stop Loss (Ticks/Points)", group=grpRisk)
inpTakeProfit = input.int(400, title="Take Profit (Ticks/Points)", group=grpRisk)

grpTime = "Time Stop Mechanics"
// Since this runs on the M1 chart, 1 bar exactly equals 1 minute.
inpTimeStopMins = input.int(15, title="Time Stop Window (Minutes)", group=grpTime)

// =========================================================================
// MODULE 1: M5 BIAS (STRUCTURE & IMPULSE)
// =========================================================================
// We request the LAST CLOSED M5 candle to prevent repainting/lookahead bias.
[m5Open, m5High, m5Low, m5Close] = request.security(syminfo.tickerid, "5", [open[1], high[1], low[1], close[1]], lookahead=barmerge.lookahead_off)

// PLACEHOLDER: Define your M5 structural sweep or displacement
// Replace this with your specific liquidity trap or BoS logic.
m5BodySize  = math.abs(m5Open - m5Close)
m5TotalSize = m5High - m5Low
m5IsStrong  = m5TotalSize > 0 and (m5BodySize / m5TotalSize) > 0.8

// Establish directional bias
bool m5BiasLong  = m5IsStrong and m5Close > m5Open
bool m5BiasShort = m5IsStrong and m5Close < m5Open

// =========================================================================
// MODULE 2: M1 ENTRY (RETEST / RECLAIM)
// =========================================================================
// PLACEHOLDER: Define your M1 execution trigger
// Example: Wait for a specific M1 pullback candle to close in your direction.
bool m1ValidLong  = close > open  // Naive bullish condition
bool m1ValidShort = close < open  // Naive bearish condition

// =========================================================================
// MODULE 3: EXECUTION & HARD STOPS
// =========================================================================
var string tradeId = "M1_Scalp"

// Only scan for entries if we are flat
if strategy.position_size == 0
    if m5BiasLong and m1ValidLong
        strategy.entry(tradeId, strategy.long, qty=inpLotSize)
        // Hard physical stops submitted to broker/tester immediately
        strategy.exit("SL/TP", from_entry=tradeId, loss=inpStopLoss, profit=inpTakeProfit)
        
    if m5BiasShort and m1ValidShort
        strategy.entry(tradeId, strategy.short, qty=inpLotSize)
        // Hard physical stops submitted to broker/tester immediately
        strategy.exit("SL/TP", from_entry=tradeId, loss=inpStopLoss, profit=inpTakeProfit)

// =========================================================================
// MODULE 4: STRICT TIME STOP MANAGEMENT
// =========================================================================
// If a position is open, track its duration in minutes (bars)
if strategy.position_size != 0
    // Get the bar index of the current active trade's entry
    entryBarIndex = strategy.opentrades.entry_bar_index(strategy.opentrades - 1)
    barsInTrade   = bar_index - entryBarIndex
    
    // If the trade has stalled past our designated window, cut it.
    if barsInTrade >= inpTimeStopMins
        // The specific comment separates time-stops from SL/TP in the journal
        strategy.close(tradeId, comment="Time Stop: Momentum Failed")

// =========================================================================
// DEBUGGING / VISUALIZATION (Optional)
// =========================================================================
// Plot a background color if a Time Stop is looming (e.g., 2 minutes away)
warningZone = strategy.position_size != 0 and (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1)) >= (inpTimeStopMins - 2)
bgcolor(warningZone ? color.new(color.maroon, 80) : na, title="Time Stop Warning")