RTATC2011 — Day 7 — Reboot Safety & Trading Conditions

Last time, I’ve modified (with the help of a fellow Japanese MQL coder) the standard Trade.mqh library to use the order and position size limits set in the ATC 2011 rules. I’ve also promised to discuss the process of dealing with the harsh trading conditions of the championship in the next journal issue. But, since it required some forward-testing, and, in its turn, forward-testing required some way to save and load the state of the expert advisor, I will expand this journal entry with the matter of restoring the inner variables of the EA in case the platform restarts.
Sending Orders Through Bad Trading Conditions
The rules of the Automated Trading Championship 2011 promise the following problems for our expert advisors: floating spreads, trade request processing time from 2 to 7 seconds, requotes, changing market conditions (as far as I understand this one, it means that the minimum distance between the stop-loss/take-profit and the market price will fluctuate) and slippage. It’s the usual set that Forex traders encounter almost daily with their brokers. It is important to “teach” your expert advisor to trade with all these obstacles.
The first thing that I’ve done was to prevent the EA from trying to trade when the trade isn’t allowed. I’ve added the following lines of code in the beginning of my OnChartEvent() handler:

if (TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) == false) return;
if (AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) == false) return;
if (AccountInfoInteger(ACCOUNT_TRADE_EXPERT) == false) return;
if (SymbolInfoInteger(sparam, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_DISABLED) return;

It works well, but not perfect – the EA still tries to send the orders during the weekends, but that doesn’t result in any serious troubles.
The second thing is to make sure that all orders are sent with a some level of slippage tolerance. It’s very simple. First, we introduce the input parameters for slippage:

input int Slippage1 = 100; 	
input int Slippage2 = 100;

(100 fractional pips = 10 standard pips). Then we use the standard method of the Trade class to set the slippage tolerance:

Trade.SetDeviationInPoints(Slip);

Next, we need to make sure that the orders we send are getting executed (due to requote, slippage or a similar error), and they aren’t we should try to execute them again (example is shown for the Buy order without Virtual Trading functions):

for (int i = 0; i < 10; i++)
{
	Ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
  	Bid = SymbolInfoDouble(symbol, SYMBOL_BID);
  	// Bid and Ask are swapped to preserve the probabilities and decrease/increase profit/loss size
  	double SL = NormalizeDouble(Bid - ATR[0], digits);
 
  	Trade.PositionOpen(symbol, ORDER_TYPE_BUY, Lots, Ask, SL, 0);
  	Sleep(7000);
  	if ((Trade.ResultRetcode() != 10008) && (Trade.ResultRetcode() != 10009) && (Trade.ResultRetcode() != 10010))
	  	Print(symbol, " - Long Position Open Return Code: ", Trade.ResultRetcodeDescription());
  	else return;
}

As you see, there is a cycle of maximum 10 attempts to execute the order. There’s a delay of 7 seconds before the result of the trade is checked. If the order was executed the cycle is exited, else the error is outputted and a new try commences.
A similar approach is used in the trailing stop functions, which sends TRADE_ACTION_SLTP orders:

for (int i = 0; i < 10; i++)
{
	Trade.PositionModify(symbol, SL, TP);
	if ((Trade.ResultRetcode() != 10008) && (Trade.ResultRetcode() != 10009) && (Trade.ResultRetcode() != 10010))
		Print("Short Position Modify Return Code: ", Trade.ResultRetcodeDescription());
	else return;
}

The main difference here is that we don’t use a delay, since it’s not required. If the order gets executed more than once there will be no problem for the trading results. If it doesn’t get executed at all on this tick, it will probably get executed on the next one – after all, it’s a trailing stop.
Save & Load
Since I had to test these modifications, I registered a separate demo account on MQL demo server to forward-test my EA for at least one week. Unfortunately, the conditions on the common demo account aren’t as hard as the ones on the ATC account, but I had no other choice for my forward-testing. But, if I didn’t want to keep my PC running without reboots for 120 hours or hire a MetaTrader VPS for this purpose, I had to implement some system for my EA to restore its inner variables after restarting the trading platform. I wouldn’t need this restoring system if not for the Z-Score optimization that is used for the EUR/GBP pair in my expert advisor. But, since all the virtual trading variables are lost the moment the platform is closed, I had to add it.
The MetaTrader 5 platform allows creation, writing and reading files only in the Files subfolder of MQL5 subfolder (or a subfolder of a respective testing agent for a back-test). I’ve chosen to use the binary file type and store all the variables as structures – a separate structure for each currency pair. File handle is declared as a global variable to be used by all the currency pair objects. At the currency pair initialization, it should try loading the data from the file. After a loading attempt, the file should be opened for writing (only once). During the execution, every change in the virtual trading variables should be recorded to the file. On deinitialization the file is closed.
Opening file for writing (located in OnInit() handler):

fh = FileOpen("atc.txt", FILE_WRITE|FILE_BIN);

File loading method:

void CMCPriceAction::LoadFile()
{
   fh = FileOpen("atc.txt", FILE_READ|FILE_BIN);
   FileSeek(fh, (number - 1) * sizeof(VirtualTrading), SEEK_SET);
   FileReadStruct(fh, VirtualTrading, sizeof(VirtualTrading));
   FileClose(fh);
}

File saving method:

void CMCPriceAction::SaveFile()
{
   FileSeek(fh, (number - 1) * sizeof(VirtualTrading), SEEK_SET);
   FileWriteStruct(fh, VirtualTrading, sizeof(VirtualTrading));
}

Downloads
Implementing all these changes didn’t alter the back-testing results. The forward-test wasn’t profitable, but it was only one week and the purpose of the test was to check the ability of the EA to trade on demo and to restore its virtual trading variables after restarting the platform. You can download the whole EA with all the latest modifications here:

  • Test EA + Variable Lots + Z-Score Optimization + Multi-Currency + Position Sizing + Save & Load
  • In the next issue of the RTATC2011 series, I hope to share more of the forward-testing and back-testing results for a more-or-less final version of my ATC 2011 expert advisor.
    If you are wondering what RTATC2011 is, you can proceed to reading the first entry in the journal.
    P.S.: 1 month and 16 days left for registration in ATC 2011. 1353 participants registered so far. Let’s hope that at least 1/4 of them will submit a working EA for the championship.

    If you have any questions or comments regarding my methods of saving the EA state and to execute orders through the ATC trading conditions, please feel free to reply using the form below.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    + eighty six = ninety six