Watch how to download trading robots for free
Find us on Telegram!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Libraries

TradeGateway: Fake Broker for Trade Management Tests - library for MetaTrader 5

Rico Hehl
Rico Hehl
  • Principal Software Engineer & Lead Cybersecurity Architect at  Posido Trading Solutions
  • Spain
  • 546
I'm a software architect based in Spain. I develop, fix, port and test Expert Advisors for MetaTrader 4 and MetaTrader 5 in MQL4 and MQL5.
Views:
35
Rating:
(1)
Published:
\MQL5\Include\TradeGateway\
TradeGateway.mqh (13.11 KB) view
FakeGateway.mqh (28.04 KB) view
LiveGateway.mqh (12.23 KB) view
BreakEvenRule.mqh (22.23 KB) view
TestKit.mqh (10.02 KB) view
\MQL5\Scripts\TradeGateway\
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

What it does

Code that moves stops or closes positions is hard to test. In the Strategy Tester and on a demo account a rejection such as "Market closed" or "Too many requests" comes when the server sends it, not when the test needs it. TradeGateway puts the calls that such code makes behind an interface, ITradeGateway: list and read positions, read the data of a symbol, change stop loss and take profit, close a position completely or in part. The rule is written against the interface and gets the gateway as a pointer in its constructor.

Two classes implement the interface. CLiveGateway passes the calls to CTrade of the Standard Library and to the position functions. CFakeGateway is a fake broker in memory: the test gives it symbols, quotes, positions and the time, and it answers each request with the retcode a server would send, or with one the test has queued. It logs every request with the prices at that moment, so a test can check what was sent, when and how often. Nothing goes to the trade server.

CBreakEvenRule is an example rule built on the interface. It moves the stop loss to the open price plus an offset once a position has reached a profit in points. It sends no request that the stops level or the freeze level forbids, waits after a rejection, does not count a closed market as an attempt and gives up after a set number of rejections. The script TradeGatewayTests runs 26 cases against the fake broker, the rule and the helper functions and prints PASS or FAIL for each.

The Experts tab after a run of TradeGatewayTests: 26 test cases against the fake broker

The Experts tab after a run of TradeGatewayTests: 26 test cases against the fake broker

How the fake broker answers

The fake runs its checks in this order, and the first one that fails sets the retcode. The rules for the levels and the volume follow the article "The checks a trading robot must pass before publication in the Market".

Step Request Answer when the check fails
1 all the next retcode that the test queued with PushRetcode
2 all POSITION_CLOSED (10036): the ticket is not open
3 all PRICE_OFF (10021): the symbol has no quote
4 modify INVALID_STOPS (10016): a stop is below 0 or off the tick grid of the symbol
5 modify NO_CHANGES (10025): stop loss and take profit are those the position has
6 modify FROZEN (10029): the current stop loss or take profit lies within the freeze level
7 modify INVALID_STOPS (10016): a new stop is closer to the price than the stops level, or on the wrong side
4 partial close INVALID_VOLUME (10014): the volume is outside the limits or off the step of the symbol
5 partial close INVALID_CLOSE_VOLUME (10038): the volume is above the volume of the position
6 partial close INVALID (10013): the fake is set to a netting account

When all checks pass, the answer is DONE (10009): a modify request sets the stops, a close removes the position, and a partial close reduces its volume or removes it when the whole volume is closed. Distances are measured to the closing price, Bid for a buy and Ask for a sell. The stops level checks both stops of the request, also one that stays as it is, and a distance equal to the level passes. The freeze level checks the stops the position has now, and a distance equal to the level blocks.

Testing a rule

The script below gives the fake one symbol and one buy that is 50 points in profit, queues a rejection and calls the rule three times. The first request is rejected, the second call sends nothing because the rule waits 10 seconds, and after the fake time has moved on the retry succeeds.

#include <TradeGateway\FakeGateway.mqh>
#include <TradeGateway\BreakEvenRule.mqh>

void OnStart()
  {
   CFakeGateway *fake = new CFakeGateway();
   fake.AddSymbol("EURUSD", 5, 0.00001, 0, 0, 0.01, 100.0, 0.01);
   fake.SetTime(D'2026.11.20 10:00');
   fake.SetQuote("EURUSD", 1.10050, 1.10060);
   fake.SetEcho(true);
   const ulong ticket = fake.AddPosition("EURUSD", POSITION_TYPE_BUY, 1.0, 1.10000, 1.09500, 0.0, 1);
   CBreakEvenRule rule(fake);
   rule.Init(50, 2, BE_ANY_MAGIC, "", 10, 3);
//--- the server rejects the first request
   fake.PushRetcode(TRADE_RETCODE_INVALID_STOPS);
   rule.Process();
   rule.Process();             // within retry_seconds: no request
   fake.AdvanceTime(10);
   rule.Process();             // the retry succeeds
   PrintFormat("requests: %d, state: %s", fake.RequestCount(), EnumToString(rule.State(ticket)));
   delete fake;
  }

The Experts tab then shows:

CFakeGateway #1 MODIFY ticket=1001 sl=1.10002 tp=0.00000 volume=0.00 bid=1.10050 ask=1.10060 -> 10016 INVALID_STOPS (forced)
CBreakEvenRule: ticket 1001: rejected with INVALID_STOPS, attempt 1 of 3
CFakeGateway #2 MODIFY ticket=1001 sl=1.10002 tp=0.00000 volume=0.00 bid=1.10050 ask=1.10060 -> 10009 DONE
CBreakEvenRule: ticket 1001: stop loss moved to 1.10002
requests: 2, state: BE_STATE_DONE

In a real test the checks go through CTestReport of TestKit.mqh instead of PrintFormat, as in TradeGatewayTests: each case creates its own fake, runs the rule and compares the request log, the position and the state of the rule with the expected values.

Using it in an Expert Advisor

In an Expert Advisor the same rule gets a CLiveGateway. Create the gateway first and delete it last, through its own type, CLiveGateway or CFakeGateway, never through an ITradeGateway pointer. The rule only borrows the pointer and never deletes it.

#include <TradeGateway\LiveGateway.mqh>
#include <TradeGateway\BreakEvenRule.mqh>

CLiveGateway   *g_gateway = NULL;
CBreakEvenRule *g_rule    = NULL;

int OnInit()
  {
   g_gateway = new CLiveGateway();
   g_gateway.Configure(7001, 10);
   g_rule = new CBreakEvenRule(g_gateway);
   if(!g_rule.Init(150, 10, 7001, _Symbol, 30, 3))
      return INIT_PARAMETERS_INCORRECT;
   return INIT_SUCCEEDED;
  }

void OnTick()
  {
   g_rule.Process();
  }

void OnDeinit(const int reason)
  {
   delete g_rule;
   delete g_gateway;
  }

ITradeGateway

TradeGateway.mqh declares the interface and two structures. SGatewayPosition holds ticket, symbol, magic, type, volume, open price, stop loss, take profit and open time. SGatewaySymbol holds digits, point, tick size, stops level, freeze level, volume limits and step, and the current Bid and Ask. The three requests, ModifyStops, ClosePosition and ClosePartial, return true for PLACED, DONE and DONE_PARTIAL and false for every other retcode; LastRetcode then tells which one came.

Method What it does
int PositionCount() Number of open positions.
ulong PositionTicketAt(index) Ticket of the position at the index, 0 if there is none.
bool PositionRead(ticket, position) Fills SGatewayPosition; false if the ticket is not open.
bool SymbolRead(symbol, data) Fills SGatewaySymbol with the specification and the current prices; false if the symbol has no quote or a property cannot be read.
datetime TimeNow() Server time: TimeCurrent in CLiveGateway, the time set by the test in CFakeGateway.
bool ModifyStops(ticket, sl, tp) Changes stop loss and take profit; 0 means not set.
bool ClosePosition(ticket) Closes the whole position.
bool ClosePartial(ticket, volume) Closes a part of the position.
uint LastRetcode() Retcode of the last request.

CFakeGateway

Method What it does
bool AddSymbol(symbol, digits, tick_size, stops_level, freeze_level, volume_min, volume_max, volume_step) Adds a symbol without a quote. The point is 10 to the power of -digits.
bool SetQuote(symbol, bid, ask) Sets the prices; needs bid above 0 and ask not below bid.
bool SetLevels(symbol, stops_level, freeze_level) Changes the levels, in points.
ulong AddPosition(symbol, type, volume, price_open, sl, tp, magic) Opens a fake position and returns its ticket, 1001 for the first; 0 if a value is invalid. The prices are rounded to the digits of the symbol, not to its tick grid.
bool RemovePosition(ticket) Removes a position without a request, as if it had been closed on the server.
void SetTime(time), void AdvanceTime(seconds) Sets or moves the fake time. Prices and time change only through these calls.
bool PushRetcode(retcode, count = 1) Answers the next count requests with this retcode, before any check. 0 and the success codes are refused.
void SetHedging(hedging) false: ClosePartial answers INVALID, as CLiveGateway does on a netting account.
int RequestCount(), bool RequestAt(index, request), void ClearRequests() The request log. SGatewayRequest holds number, time, kind, ticket, stop loss, take profit, volume, Bid and Ask at arrival, retcode and whether the answer was forced.
void SetEcho(echo) Prints every request in one line to the Experts tab.

Every setup method prints the reason when it refuses a value. Reading positions and symbols is not a request and is not logged.

CLiveGateway

Method What it does
void Configure(magic, deviation_points) Magic number and deviation of every request, passed to CTrade.
void SetLogLevel(level) How much CTrade prints about every request.

CLiveGateway normalizes prices to the digits of the symbol and volumes to 8 decimals, but moves nothing onto the tick grid; GatewayRoundUp and GatewayRoundDown do that. It sets some retcodes itself, without sending a request: POSITION_CLOSED when the position does not exist, and for ClosePartial, in the same order as the fake, PRICE_OFF without a quote, INVALID_VOLUME, INVALID_CLOSE_VOLUME and INVALID on a netting account. A retcode of 0 after a failed call means that no request was sent and the server gave no answer; the reason is then in GetLastError.

CBreakEvenRule

Method What it does
CBreakEvenRule(gateway) Stores the gateway; the rule does nothing until Init succeeds.
bool Init(trigger_points, offset_points, magic, symbol, retry_seconds, max_attempts) trigger_points above 0; offset_points from 0 to below trigger_points; magic BE_ANY_MAGIC (-1) for all positions; symbol "" for all symbols; retry_seconds 0 or more; max_attempts 1 or more. Clears the memory and the counters. If a value is invalid, it prints the reason and the rule stays off.
void SetVerbose(verbose) Switches the messages of the rule on (the default) or off.
int Process() Handles every open position once and returns the number of requests sent. Call it on every tick or from a timer.
ENUM_BE_STATE State(ticket), int Attempts(ticket), uint LastRetcode(ticket) State from the last Process call, counted rejections in a row, retcode of the last request of that ticket.
int RequestsSent(), int StopsMoved(), int Rejections(), int TicketsGivenUp() Counters since the last Init.

The new stop loss is the open price plus the offset for a buy, rounded up to the tick grid, and minus the offset for a sell, rounded down, so it never ends worse than the offset. The profit is counted in whole points to the closing price. After an answer that is not a success the rule waits retry_seconds. MARKET_CLOSED, TRADE_DISABLED, CONNECTION, TOO_MANY_REQUESTS, SERVER_DISABLES_AT and CLIENT_DISABLES_AT count as a pause, not as an attempt; every other answer counts, also a retcode of 0 from CLiveGateway, and after max_attempts of them the rule gives up on the ticket.

State Meaning
BE_STATE_UNKNOWN The rule has not seen the ticket, or has forgotten it after it closed.
BE_STATE_IDLE The profit is below the trigger.
BE_STATE_NO_QUOTE The symbol or its quote could not be read.
BE_STATE_BLOCKED The stops level or the freeze level forbids the move; no request is sent.
BE_STATE_RETRY Waiting retry_seconds after a rejection or a pause.
BE_STATE_DONE The stop loss is at break-even or better.
BE_STATE_GAVE_UP Too many rejections; this lasts until the position closes or Init is called again.

Helper functions

Function What it does
bool GatewayRetcodeIsSuccess(retcode) true for PLACED, DONE and DONE_PARTIAL.
string GatewayRetcodeText(retcode) Short name such as INVALID_STOPS, or RETCODE_ and the number.
bool GatewayVolumeIsValid(volume, volume_min, volume_max, volume_step) Within the limits and a multiple of the step, counted from 0. A step of 0 fails.
double GatewayRoundUp(price, tick_size), double GatewayRoundDown(price, tick_size) Rounds to the tick grid. Pass the result through NormalizeDouble with the digits of the symbol.
bool GatewayOnTickGrid(price, tick_size) true if the price is a multiple of the tick size.
bool GatewayFreezeBlocks(type, sl, tp, bid, ask, point, freeze_level) true if the freeze level forbids changing the current stops.
bool GatewayStopsLevelOk(type, sl, tp, bid, ask, point, stops_level) true if the new stops keep the stops level and lie on the right side of the price.

The rule and the fake use the same three level functions, so a rule that checks with them sends no request that the fake would refuse for its levels. TestKit.mqh adds CTestReport, which counts the cases and prints "PASS NN name" or "FAIL NN name: first failed check", and short helpers such as ExpectModify, ExpectClose and ExpectPartial that send one request and check its answer.

The test script

TradeGatewayTests has two inputs, both for reading along in the Experts tab.

Input Default Meaning
InpPrintRequests false Print every request the fake broker receives
InpRuleMessages false Print the messages of the break-even rule
Case What it checks
01 Fake: position and symbol are read back with all fields
02 Fake: stops level 30 of a buy, measured from Bid, and the side of the price
03 Fake: stops level 30 of a sell, measured from Ask, and the side of the price
04 Fake: the same SL and TP again gives NO_CHANGES
05 Fake: freeze level 20 of a buy blocks up to 20 points from Bid, 21 is free
06 Fake: freeze level 20 of a sell blocks up to 20 points from Ask, 21 is free
07 Fake: a stop off the 0.25 tick grid of US500 is invalid
08 Fake: partial close volumes: minimum, step, maximum, position volume
09 Fake: on a netting account a partial close is INVALID, a full close works
10 Fake: unknown ticket and symbol without a quote, for all three requests
11 Fake: forced, grid, NO_CHANGES, freeze and stops level come in this order
12 Fake: forced retcodes and the request log
13 Rule: 49 points in profit with trigger 50 sends nothing
14 Rule: a buy at 50 points gets one request and no more
15 Rule: a sell on US500 rounds down to the tick grid and uses Ask
16 Rule: stops level 60 blocks at 50 points, sends at 62
17 Rule: freeze level 20 with a TP 10 points away blocks the request
18 Rule: a rejection waits retry_seconds, then the retry succeeds
19 Rule: three rejections end in GAVE_UP, which lasts, and no further request
20 Rule: MARKET_CLOSED five times waits each time, counts no attempt, then moves
21 Rule: magic and symbol filters, and a stop that is better already
22 Rule: POSITION_CLOSED counts as an attempt, a closed ticket is forgotten
23 Rule: a symbol without a quote gives NO_QUOTE and no request
24 Rule: a refused Init disables the rule, and a new Init clears the memory
25 Rule: a sell is blocked by the stops level from Ask and by the freeze level
26 Helpers: retcode names, rounding to the tick grid, volume check

The negative cases also print the refusal messages of the library, for example "CBreakEvenRule::Init: trigger_points must be above 0". Those lines belong to the test. Two of the cases were checked against the code they guard: with the GAVE_UP check moved back behind the profit check, case 19 fails, and with an Init that keeps the rule on after a refusal, case 24 fails.

CLiveGateway in the Strategy Tester

CLiveGateway was checked in the Strategy Tester of MetaTrader 5 build 6320 on a demo hedging account, EURUSD H1, with a helper Expert Advisor that is not part of this upload; all 45 checks passed. They compare PositionRead, SymbolRead, PositionCount, PositionTicketAt and TimeNow with the terminal functions and check the retcodes 10016 for a stop loss above Bid, 10036 for a missing ticket, 10014 for a volume off the step and 10038 for a volume above the position. Then CBreakEvenRule moves a stop loss through the gateway, 0.05 of 0.10 lots are closed on the same ticket, and the rest is closed.

How to use it

  1. Copy the five .mqh files to MQL5\Include\TradeGateway\ and TradeGatewayTests.mq5 to MQL5\Scripts\TradeGateway\, and compile the script.
  2. Run the script on any chart. It needs no price history and no permission to trade; its symbols exist only in the fake broker, and the chart symbol is not used. The Experts tab shows one line per case and the summary.
  3. For a rule of your own: write it against ITradeGateway, give it the gateway in the constructor, and write test cases in a script that includes TestKit.mqh, as in TradeGatewayTests. In the Expert Advisor the rule gets a CLiveGateway.

Related articles

The article "The Repository Pattern in MQL5: Abstracting Trade History Access for Testable EA Logic" (article 22958) puts the reading of the trade history behind an interface with a live and a mock implementation, so that analytics code can be tested without a broker connection. TradeGateway uses the same separation for the other direction: the requests that change positions and the answers of the server to them. The fake broker checks a request and can reject it; the history in that article has no requests to answer.

The article "A Reusable Breakeven Manager in MQL5 with Spread Compensation" (article 23755) builds a break-even manager that adds the current spread to the new stop and sends the change with OrderSend. Its script TestBreakevenManager.mq5 checks the pip conversion, the formulas for buy and sell, the activation and the flag of a moved position with plain numbers, and the article names the missing retry after a failed modification as a limit. In TradeGateway the break-even rule is only the example: the subject is the gateway and the fake broker, and the test cases are about what happens around the request. The rule does not compensate the spread. TradeGateway uses no code from either article.

Limits

  • MetaTrader 5 only. The library handles open positions; pending orders, opening positions, margin, commission and swap are not part of it.
  • The fake answers like a server in the points listed above, and real servers differ in details: where exactly a level begins, whether both stops are checked, how the volume step is counted. The check of the tick grid is the fake's own choice.
  • A stops level of 0 in the specification does not always mean that the server accepts any distance; some servers apply a floating level that the terminal does not report. The fake treats 0 as no limit, so test a rule also with a level above 0.
  • The fake never triggers a stop loss or a take profit when the price moves, and it does not merge positions on a netting account. A partial close does not check whether the rest is below the minimal volume.
  • CLiveGateway closes in part only on a hedging account; on a netting account it answers INVALID without sending a request, as CTrade does not close in part there.
  • The Strategy Tester cannot provoke the pause retcodes, nor the case in which CLiveGateway sends nothing and returns a retcode of 0. The reaction of the rule to the pause retcodes is tested with the fake; the retcode 0 path of CLiveGateway is not tested.
  • While the market is closed, the rule sends at most one request per retry_seconds for each position that has reached the trigger. It counts the seconds by TimeNow, which in CLiveGateway is TimeCurrent and moves only with new ticks. Choose retry_seconds with that in mind.
  • A ticket the rule gave up on stays GAVE_UP until the position closes or Init is called again, whatever the price does in the meantime.
Trailing Stop That Starts at the Take-Profit Level Trailing Stop That Starts at the Take-Profit Level

Starts a trailing stop when the price reaches the take-profit zone of a position you already have open. The take profit is removed, extended or kept. It never opens trades.

Gold MACD Divergence Map Gold MACD Divergence Map

MACD regular and hidden divergences on closed bars with an honest first-touch statistics panel. Not a trading signal.

Accelerator Oscillator (AC) Accelerator Oscillator (AC)

The Acceleration/Deceleration Indicator (AC) measures acceleration and deceleration of the current driving force.

MACD Signals MACD Signals

Indicator edition for new platform.