Trading Window and Spread Guard MT4
- Utilities
-
Kazuma Uezono
MQL5 / MQL4 / Pine Script v6 developer and active trader.
Seller on the MQL5 Market (indicators for MT4/MT5).
Services:
- TradingView Pine Script to MT5/MT4 conversion (bar-by-bar matching, with tester report)
- MT4 to MT5 migration - Version: 1.1
- Activations: 5
Trading Window and Spread Guard is a utility for MetaTrader 4 that tells your own Expert Advisors when not to open new trades. You set up to five stop windows (day of week and time, for example the daily rollover, thin overnight hours or hours when your broker's spreads are wide) and a spread limit. While a window is active, or while the spread of a symbol is above your limit, the guard raises a flag that your EAs can read. As an option, it can also close positions that were opened while new trades were blocked.
It is a tool to pause trading, not a trading strategy. It does not look for good times to trade, gives no buy or sell signals and never opens a position or places an order on a real or demo account. It does not prevent losses: it can only make your EAs skip new entries, or close a new position after it was opened. Which hours to avoid, and whether and how you trade, remains your decision.
With the default settings nothing is active: no windows, spread limit OFF, closing OFF. Until you fill in the inputs, the guard only shows its panel.
Important: your EAs must read the flag. An EA that does not check the flag keeps trading as before. The check is a few lines of code (below). For an EA you cannot change, only the option "Close positions opened while blocked" works, and it closes the position after it was opened, which costs spread and commission.
Features
- Up to 5 stop windows. Formats: 12:00-12:30 (every day), Mon-Fri 23:50-01:15 (starts on each listed day and may cross midnight), Mon,Wed,Fri 08:00-08:30, Fri 21:00-Mon 01:00 (one span across days). Day names in English (Mon or Monday, any case) or Japanese; All = every day. The end may be 24:00. Windows that touch or overlap are joined.
- Window times in server time (default) or this computer's time.
- Spread limit in points: one value for all symbols, plus optional values per symbol (for example GOLD=50,US30=300).
- Symbols: the chart symbol (default), a list, or * = all symbols in Market Watch (up to 100).
- Flags for your EAs as terminal global variables, with ready-made reader functions (TWG_Reader.mqh).
- Optional: close positions opened while blocked, only for the symbols and magic numbers you choose. Positions that already existed when the guard started are never touched.
- Panel: state (OK or BLOCKED and the reason), next window with countdown, your windows, spread and limit, closing settings, flag names and the last message. English or Japanese (automatic from the terminal language). Collapse button.
- Optional popup alerts and push notifications when a stop starts or ends, a spread becomes too wide, or a position is closed.
Main Inputs
- Stop windows: times of the windows are in (server time / computer time), Window 1 to Window 5 (empty = OFF).
- Spread limit: ON/OFF (default OFF), max spread in points (default 30), per-symbol max.
- Symbols and positions: symbols (empty = this chart, * = all in Market Watch, or a list), close positions opened while blocked (default OFF), close only these magic numbers (empty = all, 0 = manual trades).
- Flags: global variable name prefix (default "TWG").
- Alerts (popup, push), Panel (show, language, corner, offsets, font size), max slippage when closing, Strategy Tester demo.
- 23 inputs. MetaTrader 4 shows them as one list without group titles, in the order above.
How It Works
- The guard checks every 250 ms and writes the flags about once per second, so your EA sees a change about 1 to 2 seconds later.
- Flags (terminal global variables; values are UTC times in seconds; "TWG" is the default prefix):
- TWG.TIME: end of the current stop window, 0 outside windows.
- TWG.SPR.<symbol> (for example TWG.SPR.EURUSD): ahead of the current time while that symbol's spread is above the limit. One flag per watched symbol.
- TWG.NEXT: start of the next stop window. TWG.HB: last update (shows that the guard is running).
- A flag is ON while its value is greater than TimeGMT().
- Basic check for your EA (same logic as TWG_Reader.mqh with the default prefix):
bool GuardBlocks(const string sym)
{
if(MQLInfoInteger(MQL_TESTER)) return false;
double now = (double)TimeGMT();
if(GlobalVariableGet("TWG.HB") < now - 30) return false; // guard not running
return GlobalVariableGet("TWG.TIME") > now || GlobalVariableGet("TWG.SPR." + sym) > now;
}
Before each new entry: if(GuardBlocks(_Symbol)) return;
- TWG_Reader.mqh adds TWG_IsBlocked, TWG_TimeBlocked, TWG_SpreadBlocked, TWG_SecondsLeft and TWG_GuardRunning. The Market download contains only the EA; the full text of this file is posted in the comments of this product. In the Strategy Tester these functions always answer "not blocked", so your backtests do not change.
- The day of week is the day the window starts. "Mon-Fri 23:50-01:15" makes five windows that start on Monday 23:50 ... Friday 23:50 and end at 01:15 on the next day. It does not cover Monday 00:00-01:15, because that part would start on Sunday. To cover the weekend and Monday morning, add a second window such as Fri 21:00-Mon 01:15. (With Fri 21:00-Mon 01:00, Monday 01:00-01:15 stays open.)
- "Opened while blocked" means: the position's open time is inside a stop window, or the spread of its symbol was above the limit at that moment (checked for positions up to 10 minutes old).
- The close is sent at the next check (every 250 ms, or on the next tick).
- You can run the guard on several charts with the same prefix (for example to watch different symbols). The flags then keep the longest value. Use different prefixes if groups of EAs need different rules.
Notes and Limits
- Not a guarantee. The guard does not block orders by itself. Only EAs that check the flag skip new entries.
- Removing the last guard lifts the stop. When you remove it or close its chart, it clears its flags at once. If the terminal stops unexpectedly, the reader treats the guard as stopped after 30 seconds. By default the reader then allows trading. If your EA should wait when the guard is not running, call TWG_IsBlocked(_Symbol, "TWG", true) (blockIfGuardStopped = true).
- The flags lag about 1 to 2 seconds. An order sent in the first second of a window, or the first second of a spread spike, can still go through. Spread spikes shorter than one check can be missed.
- Pending orders are not deleted or changed. A pending order that fills during a stop opens a new position, which is closed only if the closing option is ON and the position is in scope.
- With the magic number filter empty, the closing option also closes trades you open by hand in scope (magic 0 = manual trades). Each close costs spread and commission and can end in a loss. The guard cannot stop another EA from sending orders; if an EA keeps opening trades during a stop, each one is closed.
- Spread flags exist only for the watched symbols. If your EA trades other symbols, add them to the list or use *.
- Window times follow the clock you choose. Server time moves with your broker's daylight saving time; computer time follows this PC.
- Terminal global variables belong to one terminal. Run the guard in the same MetaTrader 4 terminal as your EAs.
- The guard works only while MetaTrader 4 is running and connected. Closing also needs AutoTrading ON (toolbar button) and live trading allowed in the EA settings.
- Right after a terminal restart, MetaTrader 4 sometimes cannot create the timer for a few seconds. The guard retries every 3 seconds on the next tick or chart event, and until then the panel shows a red line "Timer not created - updates on ticks only (retrying)".
- MetaTrader 4 has no server clock function. The guard estimates server time from incoming ticks; right after the start, until a new tick arrives, it uses the time of the last quote. Choose computer time if you prefer your PC clock.
- The panel is redrawn with incoming ticks. When no ticks come (for example at the weekend) it can look older than it is; the flags are still updated on the timer. Panel lines are cut at about 63 bytes (Japanese text is cut sooner).
- Strategy Tester: the flags are kept in memory only. With the input "Tester only: demo window and small demo positions" ON (default), the guard opens small demo positions (minimum lot, magic 73190): one before a window, which the guard leaves open, and one inside it, which the guard closes at once (the demo cleans up its positions a few minutes later). If no window is set, it uses a demonstration window (30 minutes or 2 bars, at most once a day). The tester report shows only this demonstration and is not a trading result; it can be a small loss. With very small deposits (for example 10 USD) there may be no demo trades. The demonstration never runs on a real or demo account.
Compatibility and Support
- MetaTrader 4 only. The MetaTrader 5 edition is sold separately. Attach it to one chart; add more charts only if you need them.
- No DLLs, no internet, no outside server.
- Try all settings on a demo account first.
- Support through MQL5 messages, reply within 3 business days: installation, settings, bug reports and how to call the reader functions. We cannot advise which hours or spreads to avoid, give market views or trade decisions, or edit your EA for you.
- No result of your trading is promised or implied.
