거래 로봇을 무료로 다운로드 하는 법을 시청해보세요
당사를 Twitter에서 찾아주십시오!
당사 팬 페이지에 가입하십시오
스크립트가 흥미로우신가요?
그렇다면 링크 to it -
하셔서 다른 이들이 평가할 수 있도록 해보세요
스크립트가 마음에 드시나요? MetaTrader 5 터미널에서 시도해보십시오
라이브러리

TradeGuard - Reliable Order Execution: No Duplicates, Safe Retries, Restart Recovery - MetaTrader 5용 라이브러리

Santiago Alarcon Zavala
Santiago Alarcon Zavala
MQL5 developer. I build Expert Advisors and indicators for MetaTrader 5, focused on Smart Money and ICT models, and I validate them before delivery.
How I work:
• A written specification first, so every rule is unambiguous.
• Clean, commented source code.
조회수:
76
게시됨:
tg_1.png (105.79 KB)
tg_2.png (121.68 KB)
\MQL5\Include\TradeGuard\
TradeGuard.mqh (80.76 KB) 조회
\MQL5\Experts\TradeGuard\
MQL5 프리랜스 이 코드를 기반으로 한 로봇이나 지표가 필요하신가요? 프리랜스로 주문하세요 프리랜스로 이동

TradeGuard handles how an Expert Advisor trades; your strategy only decides what to trade and when. It checks every request, normalises it to the broker's limits, sends it with safe retries, never opens the same signal twice, never touches the positions of other EAs and rebuilds its state after a restart. One include file, no DLL, and a test suite you can run in your own Strategy Tester.

Why

Most live failures of an EA are not strategy failures. An order is sent twice after a slow answer, a stop loss is refused because it is too close, a lot does not match the volume step, another EA's position is closed by mistake, or a daily loss limit resets when the VPS restarts in the middle of the day. TradeGuard handles each of these in one place.


Every request follows the same path. Only safe answers are retried, and an uncertain answer is searched on the server before anything is resent.

What it does

  • Pre-trade checks: trade permissions, session, quote age, spread, account and symbol limits, margin and OrderCheck.
  • Normalisation: volume to the minimum, maximum and step (always rounded down), prices to the tick size, stops to the stops level (widened with the lot recalculated, or refused), freeze level, filling mode and expiration.
  • Safe retries: every server answer is classified. Requotes, price changes and connection errors are retried with a fresh price; an uncertain answer (timeout, no answer) is searched on the server before anything is resent; fatal answers are logged and never retried.
  • One order per signal: each request carries an intent key, for example the signal bar time and the direction. The same key never opens twice, even after a restart, and a lock holds new orders while one is in flight, until the terminal shows the new position.
  • Isolation: positions, orders and history are always filtered by symbol and magic number. On netting accounts it refuses to trade a symbol held by a foreign position.
  • Restart recovery: on start it rebuilds positions, orders, intent keys, trades of the day, the day base and the limit status from the server. Only what cannot be derived is kept in terminal global variables.
  • Risk and limits: lot by risk with OrderCalcProfit (cross rates, indices, CFDs, stocks), an optional daily loss limit with a configurable day cut and an optional equity floor. Both stay active after a restart.
  • Log: one line per request with key, volume, prices, attempt, answer and latency.

Quick start

#include <TradeGuard\TradeGuard.mqh> CTradeGuard tg; int OnInit() { tg.Init(_Symbol,123456); // symbol and magic number tg.RiskPercent(0.5); // risk per trade, % of balance tg.DailyLossLimit(4.0,1); // optional: 4 % per day, day cut at 01:00 server time tg.EquityFloor(9000.0); // optional: equity floor return(tg.Recover() ? INIT_SUCCEEDED : INIT_FAILED); } void OnTick() { tg.OnTick(); if(MySignal() && tg.CanTrade()) tg.Buy(SignalKey(),StopLoss(),TakeProfit()); // lot by risk, normalised, never twice } void OnTradeTransaction(const MqlTradeTransaction &trans,const MqlTradeRequest &request,const MqlTradeResult &result) { tg.OnTradeTransaction(trans,request,result); }

MySignal, SignalKey, StopLoss and TakeProfit stand for your own strategy. TradeGuard_Demo.mq5 shows the same calls in a complete EA.

Main functions

Function

What it does

Init(symbol, magic)

Binds the instance to one symbol and one magic number

Recover()

Rebuilds the state from the server; call it at the end of OnInit

Buy, Sell(key, sl, tp, lots)

Market order; lots = 0 sizes the lot by risk from the stop loss

BuyLimit, SellLimit, BuyStop, SellStop(key, price, sl, tp, expiration, lots)

Pending order; if the symbol accepts no expiration time, TradeGuard deletes the order itself

Modify(ticket, sl, tp), ModifyOrder(ticket, price, sl, tp)

Changes own positions and orders only; requests without a change are not sent

Close, CloseAll, Delete, DeleteAll

Closes own positions or deletes own pending orders

CanTrade(), Reason()

Whether a new entry is allowed now, and why not

LotsForRisk(type, entry, sl)

The lot that loses the configured risk at the stop

PositionsCount, OrdersCount, TradesToday, DayBase, DayLoss

Own state, always derived from the server

OnTick(), OnTradeTransaction(...)

Call them from the EA handlers of the same name

Setting

Default

RiskPercent(percent, ofEquity) or RiskMoney(amount)

1 % of balance

MaxLot, CommissionPerLot

Off, 0

Deviation(points), MaxAttempts

10, 3

MaxSpread(points), MaxTickAge(seconds)

Off, 60

StopsPolicy

Widen to the broker minimum and recalculate the lot, or refuse

MaxPositions, MaxTradesPerDay

Off

DayResetHour(server hour)

0

DailyLossLimit(value, reset hour, percent, base, trigger)

Off; triggers at 90 % of the limit

EquityFloor(equity)

Off

LogLevel, CsvLog(file)

Requests and blocks; no CSV

How it was verified

Every number below comes from TradeGuardTests.mqh, run on FTMO symbols in the Strategy Tester (M5, August to October 2026). To repeat it, run TradeGuard_Demo in the tester with Verification mode set to unit tests or integration run. Results appear as TGTEST lines in the journal and in Common\Files\TG_*.csv; an integration run with and without simulated restarts must print the same dealHash.

Check

Result

Compiles

0 errors and 0 warnings for the library, the test suite and the demo EA

Unit tests

83 of 83 pass: all 42 answer codes, 5,000 keys without a collision, 6 day cuts, synthetic specifications with stops level 30 and freeze level 10, and volume, price and stops on EURUSD, USDJPY, XAUUSD, US100.cash and AAPL

Lot by risk

120 cases on those 5 symbols plus one with commission: the loss at the stop never exceeds the risk and stays within one volume step of it; the minimum lot is never forced

Bad requests

7,186 requests on EURUSD and US100.cash with random execution delays, odd volumes, stops inside the spread, volumes far above the maximum and pending prices on the market: 0 server rejections, and 62,048 attempts stopped before sending, each with its reason in the log

Duplicates

4,876 keys accepted, none twice; 91,172 repeated requests blocked

Restarts

With a simulated restart every 35 minutes (1,756 restarts), the same 4,025 deals as without restarts; the day base matched an independent calculation on all 240,553 ticks

Isolation

Another EA traded the same symbol in every run; none of its positions was counted, modified or closed

Daily limit and floor

A 1 % daily limit was reached 37 times and a 9,850 equity floor once: 0 own entries and 0 own open positions after the block, with identical results with and without restarts

Cost

0.2 to 0.8 µs per tick for OnTick plus CanTrade


The nine acceptance checks. The test suite is included, so the numbers can be reproduced on any broker.

What the tests found

  • A real bug, fixed before publication. On a stock CFD where 1 lot is 1 share, rounding the loss to cents made 10 of 24 risk-based lots exceed the risk by a few cents. The loss is now computed on a large reference volume and checked again with the exact lot.
  • Expired pending orders lose their comment. The server replaces it with «expired [date]», so the intent key of such an order survives only in the terminal global variables. That is why TradeGuard keeps the keys there as well.

Limitations

  • The Strategy Tester does not emulate requotes or timeouts with market execution. The retry and uncertain-answer paths are covered by the unit tests of the answer classes, not by a failing live server.
  • Netting accounts: the rule is in the code but was not tested, because the test account is hedging.
  • The risk is measured at the stop loss. Gaps, slippage and swaps can make a loss larger, and commissions count only if you set CommissionPerLot.
  • One symbol and one magic number per instance. Breakeven, trailing stops and partial closes are not included.
  • With several EAs on one account, each instance closes only its own positions when a limit is reached.

Files

  • TradeGuard.mqh (Include\TradeGuard): the library.
  • TradeGuardTests.mqh (Include\TradeGuard): the test suite, used only in Verification mode.
  • TradeGuard_Demo.mq5 (Experts\TradeGuard): an example EA. Its moving average cross is a placeholder that shows the calls; it is not a trading system.

Rolling VWAP Deviation Regime Filter Rolling VWAP Deviation Regime Filter

A regime-classification oscillator that measures how far, and how persistently, price deviates from a rolling volume-weighted VWAP in standard-deviation units, separating trending conditions from ranging ones.

AlertKit, one alert per event and bar, no alert spam AlertKit, one alert per event and bar, no alert spam

A small include class that stops indicator alerts from firing on every tick. One alert per event and bar, silent about history on start, popup, push, email or sound, and an optional log of every decision. Comes with a working range break indicator as an example

Risk Lot Sizing Library - four risk bases, tick-value scaling, margin cap, daily limit Risk Lot Sizing Library - four risk bases, tick-value scaling, margin cap, daily limit

A stop distance in points is not money until the tick size and tick value make it one. This library turns four risk bases into a lot size, floors it to the volume step, caps it against free margin and tracks a daily loss limit. Two MQL5 headers, no DLL.

Auto Fibo Extended Auto Fibo Extended

Auto Fibo Extended is a MetaTrader 5 indicator designed to automatically identify significant swing highs and swing lows and draw Fibonacci Retracement and Extension levels directly on the chart.