Turnstile Order Gateway

An MQL5 library between your Expert Advisor and OrderSend. Each request passes 9 gates (connection, Algo Trading, symbol mode, session, order-type flags, volume, stops, margin, OrderCheck) before sending. Closes and modifications blocked by the freeze level, a closed session or a lost connection are queued and sent later. It never trades on its own. You receive the compiled Turnstile_Order_Gateway.ex5; this page is the full API reference.

Quick Start

  1. Copy Turnstile_Order_Gateway.ex5 to MQL5/Libraries (File > Open Data Folder).
  2. Paste the #import block below into your EA or script.
  3. Optional: TOG_Configure in OnInit (defaults 20, 3, 300, true, false).
  4. Call TOG_ProcessQueue in OnTick or OnTimer.
  5. Trade with TOG_Open, TOG_Modify, TOG_Close. On 0 or false, print TOG_ReasonText(TOG_LastReason()).
  6. Verify: run the example below in the Strategy Tester; the log shows ticket and reason. Live, enable Algo Trading or checks return -3.

Import Declaration (Copy-Paste Ready)

#import "Turnstile_Order_Gateway.ex5"
   void   TOG_Configure(int deviation, int retries, int delay_ms, bool adjust_stops, bool verbose);
   double TOG_NormalizeVolume(string symbol, double volume);
   double TOG_NormalizePrice(string symbol, double price);
   double TOG_RiskVolume(string symbol, ENUM_ORDER_TYPE type, double entry, double sl, double risk_money);
   double TOG_MaxVolume(string symbol, ENUM_ORDER_TYPE type, double share);
   ENUM_ORDER_TYPE_FILLING TOG_FillingMode(string symbol);
   int    TOG_CheckMarket(string symbol, ENUM_ORDER_TYPE type);
   int    TOG_CheckStops(string symbol, ENUM_ORDER_TYPE type, double price, double sl, double tp);
   int    TOG_CheckFreeze(ulong ticket);
   int    TOG_Preflight(string symbol, ENUM_ORDER_TYPE type, double volume, double price, double sl, double tp);
   ulong  TOG_Open(string symbol, ENUM_ORDER_TYPE type, double volume, double price, double sl, double tp, ulong magic, string comment);
   bool   TOG_Modify(ulong ticket, double price, double sl, double tp);
   bool   TOG_Close(ulong ticket, double volume);
   int    TOG_CloseAll(string symbol, long magic, bool pending);
   int    TOG_ProcessQueue();
   int    TOG_QueueCount();
   void   TOG_ClearQueue();
   int    TOG_LastReason();
   uint   TOG_LastRetcode();
   string TOG_ReasonText(int reason);
   int    TOG_RetcodeClass(uint retcode);
   int    TOG_GetStats(long &stats[]);
#import 

Reason Codes

TOG_LastReason gives the code, TOG_ReasonText the text in capitals.

  • 0 OK; 1 NO CHANGE (equal values, nothing sent); 2 DEFERRED (queued).
  • -1 BAD PARAMETERS: unknown symbol or type, pending price 0, volume 0.
  • -2 NO CONNECTION: disconnected or no quotes.
  • -3 TRADING DISABLED: Algo Trading or account trading off.
  • -4 SYMBOL MODE: disabled, close-only, long-only or short-only.
  • -5 MARKET CLOSED: outside the trading sessions.
  • -6 INVALID VOLUME: outside min/max, off step or over the volume limit.
  • -7 INVALID STOPS: SL, TP or pending price wrong side or inside the stop level.
  • -8 FREEZE ZONE: price within the freeze level.
  • -9 NO MARGIN: market order margin above free margin.
  • -10 ORDER TYPE BLOCKED: type or SL/TP not allowed, or pending-order limit reached.
  • -11 ORDERCHECK FAILED and -12 SERVER REJECTED: see TOG_LastRetcode.
  • -13 TICKET NOT FOUND; -14 QUEUE FULL (256 waiting).

API Reference

type: ORDER_TYPE_BUY, ORDER_TYPE_SELL, ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT, ORDER_TYPE_BUY_STOP or ORDER_TYPE_SELL_STOP (stop-limit returns -1). Prices are absolute; sl or tp 0 means none.

TOG_Configure

deviation: slippage points, 0 or more (invalid: 20). retries: 0-10 (invalid: 3). delay_ms: 0-5000 between retries (invalid: 300). adjust_stops: true moves an SL/TP that is on the correct side but inside the stop level to the nearest legal price plus one tick (plus the spread if the server still refuses); false returns -7. verbose: logs blocks, retries and deferrals with the prefix [TOG].

TOG_NormalizeVolume

Rounds down to the volume step, caps at the maximum. 0.0 below the minimum, for volume 0 or an unknown symbol.

TOG_NormalizePrice

Rounds to tick size and digits. 0.0 for price 0, so an empty SL stays 0.

TOG_RiskVolume

Volume that loses risk_money (account currency) at sl, via OrderCalcProfit (works for crosses, metals, indices, stocks), rounded down. entry 0 = Ask for buy types, Bid for sell types. 0.0 with -6 if the minimum volume risks more, -7 if sl is on the wrong side, -1 for bad inputs.

double lots = TOG_RiskVolume(_Symbol, ORDER_TYPE_BUY, 0, sl, AccountInfoDouble(ACCOUNT_BALANCE) * 0.01); 

TOG_MaxVolume

Largest valid volume whose margin fits in free margin x share (0-1, else 1), within the maximum and the remaining volume limit. 0.0 with -9 if the minimum does not fit.

TOG_FillingMode

Market filling: FOK if allowed, else IOC, else RETURN. TOG_Open switches if the server refuses it.

TOG_CheckMarket

Gates 1-4 for opening: connection and quotes, Algo Trading, symbol mode for this direction, session (server time against the session table; no table counts as open). Returns 0 or -1 to -5.

TOG_CheckStops

Market: sl and tp on the correct side of Bid (buy) or Ask (sell), at least SYMBOL_TRADE_STOPS_LEVEL away. Pending: price likewise from the market, sl and tp from price. Returns 0, -7, -1 or -2.

TOG_CheckFreeze

-8 when Bid (buy) or Ask (sell) is within SYMBOL_TRADE_FREEZE_LEVEL of the position's SL or TP, or the market is that close to a pending order's price. 0 if the level is 0, -13 for an unknown ticket.

TOG_Preflight

All 9 gates in order, nothing sent: market gates, order-type flags and pending limit, volume, stops, margin (market orders), OrderCheck. Returns the first failure or 0.

if(TOG_Preflight(_Symbol, ORDER_TYPE_SELL, 0.10, 0, sl, tp) != 0) Print(TOG_ReasonText(TOG_LastReason())); 

TOG_Open

Normalizes volume and prices, adjusts stops if enabled, runs TOG_Preflight, sends. Market orders (price 0) retry requotes, price changes, timeouts and connection errors with fresh prices. Pending orders use GTC, or DAY if GTC is not allowed. Returns the position ticket (market), order ticket (pending) or 0. Never queued.

TOG_Modify

SL/TP of a position, or price/SL/TP of a pending order (price 0 keeps it). Equal values: true, reason 1. Blocked by the freeze zone, a closed session or no connection: false, reason 2, queued; a newer call for the ticket replaces it.

TOG_Close

Closes a position or deletes a pending order. volume 0 or the full volume closes all; less closes part (rounded down); a remainder below the minimum closes all. Blocked as above: false, reason 2, queued (replacing a queued modify).

TOG_CloseAll

TOG_Close for each position (and pending order if pending) matching symbol ("" = all) and magic (-1 = any). Returns how many closed now.

TOG_ProcessQueue

Sends queued actions once unblocked; call it in OnTick or OnTimer. An action leaves the queue on success, when its ticket is gone or on another failure; after a server refusal it waits one second. Returns the number completed.

TOG_QueueCount and TOG_ClearQueue

Waiting actions (maximum 256); discard all without sending.

TOG_LastReason, TOG_LastRetcode and TOG_ReasonText

Reason of the last call; last server retcode (0 if nothing was sent); text of a reason code ("UNKNOWN" otherwise).

TOG_RetcodeClass

0 DONE (placed, done, partial, no changes, position closed), 1 RETRY (requote, reject, error, timeout, price changed or invalid, off quotes, too many requests, locked, connection), 2 FIX (invalid request, volume, stops, expiration, fill, order), 3 WAIT (market closed, frozen), 4 FATAL (others, e.g. no money).

TOG_GetStats

Fills stats[] with 10 counters, returns 10: 0 requests, 1 sent, 2 done, 3 blocked, 4 retries, 5 deferred, 6 done from queue, 7 refused, 8 stops adjusted, 9 dropped.

Working Integration Example

#import "Turnstile_Order_Gateway.ex5"
   double TOG_RiskVolume(string symbol, ENUM_ORDER_TYPE type, double entry, double sl, double risk_money);
   ulong  TOG_Open(string symbol, ENUM_ORDER_TYPE type, double volume, double price, double sl, double tp, ulong magic, string comment);
   bool   TOG_Close(ulong ticket, double volume);
   int    TOG_ProcessQueue();
   int    TOG_LastReason();
   string TOG_ReasonText(int reason);
#import

ulong ticket = 0;
bool  tried  = false;

void OnTick()
{
   TOG_ProcessQueue();
   if(!tried)
   {
      tried = true;
      double sl   = SymbolInfoDouble(_Symbol, SYMBOL_BID) - 300 * _Point;
      double lots = TOG_RiskVolume(_Symbol, ORDER_TYPE_BUY, 0, sl, 10.0);
      ticket = TOG_Open(_Symbol, ORDER_TYPE_BUY, lots, 0, sl, 0, 7001, "turnstile");
      Print("open ", ticket, ": ", TOG_ReasonText(TOG_LastReason()));
   }
   if(ticket > 0 && PositionSelectByTicket(ticket) && PositionGetDouble(POSITION_PROFIT) > 5.0)
      Print("close: ", TOG_Close(ticket, 0), " ", TOG_ReasonText(TOG_LastReason()));
} 

Architecture and Notes

  • Each importing program has its own settings, statistics and in-memory queue (lost when the EA is removed or the terminal restarts).
  • Checks only read terminal data; only TOG_Open, TOG_Modify, TOG_Close, TOG_CloseAll and TOG_ProcessQueue send, synchronously.
  • Setups: validator safety = defaults plus TOG_ProcessQueue in OnTick; strict stops = adjust_stops false; development = verbose true and TOG_GetStats on your panel.
  • MetaTrader 5, netting and hedging, any symbol; EAs and scripts only. Safe in the Strategy Tester, optimization and MQL5 Cloud Network (no DLLs, files, web requests; no retry pause in the tester).
  • No chart objects, timers, files or global variables; may add a symbol to Market Watch for quotes.
  • A holiday missing from the session table is caught from the server reply as -5.
  • Not supported: stop-limit orders, close-by, OrderSendAsync.

Risk Notice

The library checks and sends the requests your code makes. It does not choose entries or guarantee fills, prices or profits. Test on a demo account first.

More from author
EA Budak Ubat
Syarief Azman Bin Rosli
4 (3)
Download Trial EA Budak Ubat Channel Limited Time Price! The price will increase by 10 USD after every 10 purchases! How it works When the EA is active, it will analyze the chart based on the Execution Mode parameter. If there are no existing positions on the chart, the EA will enter a trade based on the parameter. If the trend is bullish, it will enter a buy trade and if it is bearish it will enter a sell trade. And it will also set a Stop loss order at a certain distance from the opened trad
EA Budak Ubat MT5
Syarief Azman Bin Rosli
EA Budak Ubat MT5 is an automated grid-trading Expert Advisor designed for MetaTrader 5. It combines technical trend analysis, dynamic volatility scaling, and multi-layered risk management to trade ranging and trending market conditions. Optimized for the M5 timeframe on major forex pairs and metals (XAUUSD / Gold). ### Key Features • 4 Selectable Analysis Methods:   1. Classic Candle: Directional momentum from candle patterns.   2. SMA20: 20-period Simple Moving Average crossover.   3. Allig
Indi RBO
Syarief Azman Bin Rosli
Input: Range Start Time : The starting time of the range creation Range End Time : The ending time of range creation Trade End Time : The time where the line of range zone high/low will be extended to Minimum Size : The minimum size of the range in point Maximum Size : The maximum size of the range in point If the range size is between the minimum and maximum, indicator will print the 1st color (blue).
Apex Flow Reversion
Syarief Azman Bin Rosli
# Apex Flow Reversion MT4 Apex Flow Reversion is an automated trading system developed for MetaTrader 4 that executes an intraday statistical mean-reversion strategy. The system monitors price deviation from a dynamic Volume-Weighted Average Price benchmark and identifies exhaustion points using standard deviation bands, Relative Strength Index momentum filtration, and Average True Range volatility constraints. ## Strategy Overview The algorithm computes a rolling intraday VWAP curve weighte
Vortex Confluence Radar
Syarief Azman Bin Rosli
Vortex Confluence Radar MT4 Vortex Confluence Radar is a multi-oscillator confluence scoring engine developed natively for MetaTrader 4. It fuses three distinct technical oscillators—Relative Vigor Index (RVI), Commodity Channel Index (CCI), and Williams % Percent Range (WPR)—into a unified momentum histogram with a smoothed signal line and automated crossover alert signals. Understanding the Indicator Architecture The indicator operates in a separate sub-window and renders several distinct visu
Kinetix Speed Commander
Syarief Azman Bin Rosli
Kinetix Speed Commander MT4 Kinetix Speed Commander   is an institutional-grade, on-chart one-click trade execution cockpit, dynamic position sizing calculator, and risk-to-reward order management terminal engineered natively for MetaTrader 4. Built specifically for proprietary trading firm challengers, fast-paced scalpers, and systematic day traders, Kinetix Speed Commander eliminates manual calculation delays, human execution errors, and over-leveraged risk exposure. Operating via a high-perfo
Prism Candle Forge
Syarief Azman Bin Rosli
Prism Candle Forge — Candlestick Pattern Recognition Engine for MT4 Prism Candle Forge is a native MQL4 library that detects and validates 20+ Japanese candlestick patterns using ATR-weighted geometric analysis. It provides pattern identification, directional confidence scoring, candle morphology classification, and trend context validation — all through 8 exported functions callable from any Expert Advisor, Indicator, or Script. Zero DLLs, zero external dependencies, pure MQL4 computation. Dist
Sigma Squeeze Reactor
Syarief Azman Bin Rosli
Sigma Squeeze Reactor Bollinger-Keltner Volatility Squeeze Breakout Expert Advisor Sigma Squeeze Reactor is an intelligent breakout Expert Advisor for MetaTrader 4 that identifies and trades explosive volatility expansion moves. It detects when Bollinger Bands contract inside Keltner Channels (the classic volatility squeeze) and executes precise entries when the compression releases, confirmed by momentum oscillator direction. The EA is engineered with a   Dual-Engine Breakout Architecture   tha
Fulcrum Value Profile
Syarief Azman Bin Rosli
Fulcrum Value Profile is a MetaTrader 4 indicator that builds a tick-volume profile for every session, marks its Point of Control (POC) and value area, draws the developing POC/VAH/VAL as lines, tracks naked POCs and flags two value-area setups on closed bars: re-entry into the prior value area (80% rule) and acceptance outside it (breakout). It never opens, modifies or closes trades. Quick Start Attach the indicator to an M5, M15 or M30 chart. Keep Profile Period = Daily session, or choose Cust
Filament Tripline Console
Syarief Azman Bin Rosli
Filament Tripline Console turns your own horizontal lines and trendlines into armed triplines. When price touches a line, or a bar closes beyond it, the tripline fires its action: an alert, a market BUY or SELL with automatic lot size, stop loss and take profit, or an EXIT that closes positions. It never trades on its own analysis; it only acts on lines you arm. Quick Start Attach the utility to any chart. For BUY, SELL and EXIT actions enable Algo Trading in the toolbar and Allow live trading o
Spectra Trend Ribbon
Syarief Azman Bin Rosli
Spectra Trend Ribbon is a multi-tier trend direction and volatility expansion indicator developed natively for MetaTrader 5. It combines an adaptive smoothed central trend baseline with dynamic volatility envelope bands and automated momentum breakout signals. Understanding the Visual Signals: 1. Central Adaptive Baseline (Color Line) - Green Color: Indicates that the market price is trading above the baseline and the baseline slope is positive, representing an active bullish trend regime. -
Aegis Risk Sentinel
Syarief Azman Bin Rosli
Aegis Risk Sentinel MT5 Aegis Risk Sentinel   is an institutional-grade, real-time equity protection and risk management utility developed natively for MetaTrader 5. Engineered for proprietary trading firm challengers, professional fund managers, and retail day traders, Aegis enforces mathematical discipline on your trading account, preventing catastrophic drawdowns, emotional revenge trading, and over-leveraged margin calls. The utility features an ultra-responsive on-chart Head-Up Display (HUD
Stratos Momentum Engine
Syarief Azman Bin Rosli
Stratos Momentum Engine MT5 Stratos Momentum Engine is a fully automated multi-timeframe momentum breakout trading system designed for MetaTrader 5. The Expert Advisor combines structural trend identification on the higher timeframe (H1) with precision momentum timing and breakout confirmation on the lower timeframe (M15). The system utilizes mathematical least-squares linear regression slope to define primary directional bias, Stochastic oscillator dynamics to identify optimal entry points with
Nexus Quant Matrix
Syarief Azman Bin Rosli
Nexus Quant Matrix — Quantitative Computing Engine for MT5 Nexus Quant Matrix is a high-performance quantitative library built natively in MQL5. It delivers institutional-grade Kalman filtering, Cornish-Fisher VaR, Expected Shortfall (CVaR), Kelly Criterion sizing, margin-protected lot calculation, and Pearson correlation directly into your Expert Advisors — zero DLLs, zero external dependencies. Distributed as a compiled binary (Nexus_Quant_Matrix.ex5). This description is your complete API ref
Quasar Regime Cloud
Syarief Azman Bin Rosli
Quasar Regime Cloud is a market regime indicator for MetaTrader 5. It measures whether price is currently trending or chopping, then shows the result directly on the chart through a fractal-adaptive cloud. Signals are only produced while the market is classified as trending, which filters out many of the false crossovers that occur in sideways conditions. How It Works 1. Fractal Dimension Estimate For every bar the indicator estimates the fractal dimension (D) of price over a configurable window
Isobar Event Shield
Syarief Azman Bin Rosli
Isobar Event Shield protects your trades from economic news in MetaTrader 5. It reads the terminal's built-in economic calendar, counts down to every release that affects your symbols and, shortly before each release, applies the protection you choose to the positions and pending orders that you or your other Expert Advisors already have. It never opens trades of its own. Quick Start Attach the utility to one chart (one copy per terminal) and enable Algo Trading in the terminal toolbar. The bas
Riptide Sweep Reclaimer
Syarief Azman Bin Rosli
Riptide Sweep Reclaimer is a MetaTrader 5 Expert Advisor that trades liquidity sweeps of a quiet-session range: it measures the high and low of a window you choose (default 00:00-08:00 server time), waits for the next session to push through one side and fades the move once a candle closes back inside, targeting the midpoint and the opposite side. One position at a time on the chart symbol; no grid, martingale or averaging. Quick Start Attach the EA to one chart of the symbol (any timeframe; th
Filter:
No reviews
Reply to review