OnTesterInit issues and the command line - page 3

 
angevoyageur:
I wrote you, you do not believe me ? ;-)
I believe it. My message may have come accross wrong. I am pretty exicited to be able to automatically optimize from the command line, so I am looking forward to the next build.
 

Optimisation is able to work.

I need to export the best tester results to a *.*set file however my exported file does not include the best results.

Here is my code for this EA:

//+------------------------------------------------------------------+
//|                                              Moving Averages.mq5 |
//|                   Copyright 2009-2013, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2009-2013, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"

#include <Trade\Trade.mqh>
#include <MQL_Settings.mqh>

static double __result;

input double MaximumRisk        = 0.02;    // Maximum Risk in percentage
input double DecreaseFactor     = 3;       // Descrease factor
input int    MovingPeriod       = 12;      // Moving Average period
input int    MovingShift        = 6;       // Moving Average shift
//---
int   ExtHandle=0;
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double TradeSizeOptimized(void)
  {
   double price=0.0;
   double margin=0.0;
//--- select lot size
   if(!SymbolInfoDouble(_Symbol,SYMBOL_ASK,price))               return(0.0);
   if(!OrderCalcMargin(ORDER_TYPE_BUY,_Symbol,1.0,price,margin)) return(0.0);
   if(margin<=0.0)                                               return(0.0);

   double lot=NormalizeDouble(AccountInfoDouble(ACCOUNT_FREEMARGIN)*MaximumRisk/margin,2);
//--- calculate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      //--- select history for access
      HistorySelect(0,TimeCurrent());
      //---
      int    orders=HistoryDealsTotal();  // total history deals
      int    losses=0;                    // number of losses orders without a break

      for(int i=orders-1;i>=0;i--)
        {
         ulong ticket=HistoryDealGetTicket(i);
         if(ticket==0)
           {
            Print("HistoryDealGetTicket failed, no trade history");
            break;
           }
         //--- check symbol
         if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=_Symbol) continue;
         //--- check profit
         double profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
         if(profit>0.0) break;
         if(profit<0.0) losses++;
        }
      //---
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- normalize and check limits
   double stepvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   lot=stepvol*NormalizeDouble(lot/stepvol,0);

   double minvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   if(lot<minvol) lot=minvol;

   double maxvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
   if(lot>maxvol) lot=maxvol;
//--- return trading volume
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   MqlRates rt[2];
//--- go trading only for first ticks of new bar
   if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
     {
      Print("CopyRates of ",_Symbol," failed, no history");
      return;
     }
   if(rt[1].tick_volume>1) return;
//--- get current Moving Average 
   double   ma[1];
   if(CopyBuffer(ExtHandle,0,0,1,ma)!=1)
     {
      Print("CopyBuffer from iMA failed, no data");
      return;
     }
//--- check signals
   ENUM_ORDER_TYPE signal=WRONG_VALUE;

   if(rt[0].open>ma[0] && rt[0].close<ma[0]) signal=ORDER_TYPE_SELL;    // sell conditions
   else
      if(rt[0].open<ma[0] && rt[0].close>ma[0]) signal=ORDER_TYPE_BUY;  // buy conditions
//--- additional checking
   if(signal!=WRONG_VALUE)
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
         if(Bars(_Symbol,_Period)>100)
           {
            CTrade trade;
            trade.PositionOpen(_Symbol,signal,TradeSizeOptimized(),
                               SymbolInfoDouble(_Symbol,signal==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK),
                               0,0);
           }
//---
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   MqlRates rt[2];
//--- go trading only for first ticks of new bar
   if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
     {
      Print("CopyRates of ",_Symbol," failed, no history");
      return;
     }
   if(rt[1].tick_volume>1) return;
//--- get current Moving Average 
   double   ma[1];
   if(CopyBuffer(ExtHandle,0,0,1,ma)!=1)
     {
      Print("CopyBuffer from iMA failed, no data");
      return;
     }
//--- positions already selected before
   bool signal=false;
   long type=PositionGetInteger(POSITION_TYPE);

   if(type==(long)POSITION_TYPE_BUY   && rt[0].open>ma[0] && rt[0].close<ma[0]) signal=true;
   if(type==(long)POSITION_TYPE_SELL  && rt[0].open<ma[0] && rt[0].close>ma[0]) signal=true;
//--- additional checking
   if(signal)
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
         if(Bars(_Symbol,_Period)>100)
           {
            CTrade trade;
            trade.PositionClose(_Symbol,3);
           }
//---
  }
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   ExtHandle=iMA(_Symbol,_Period,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE);
   if(ExtHandle==INVALID_HANDLE)
     {
      printf("Error creating MA indicator");
      return(-1);
     }
   __result = 0.0;
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(PositionSelect(_Symbol)) CheckForClose();
   else                        CheckForOpen();
//---
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }
//+------------------------------------------------------------------+
 void OnTesterInit()
 {
 }
 
//+------------------------------------------------------------------+
//| Tester function                                                  |
//+------------------------------------------------------------------+
double OnTester()
   {
      double _result = TesterStatistics(STAT_PROFIT);
      if(_result > __result)
      {
         string _settings[4];
         /*
         
         //TRIED USING THIS AS WELL BUT RESULTS WERE BUGGY...
         
         bool _enable;
         string _name = "MaximumRisk";
         long _par1,_par1_start,_par1_step,_par1_stop;
         ParameterGetRange(_name,_enable,_par1,_par1_start,_par1_step,_par1_stop);
         _settings[0] = DoubleToString(_par1,2);
         _name = "DecreaseFactor";
         long _par2,_par2_start,_par2_step,_par2_stop;
         ParameterGetRange(_name,_enable,_par2,_par2_start,_par2_step,_par2_stop);
         _settings[1] = DoubleToString(_par2,2);
         _name = "MovingPeriod";
         long _par3,_par3_start,_par3_step,_par3_stop;
         ParameterGetRange(_name,_enable,_par3,_par3_start,_par3_step,_par3_stop);
         _settings[2] = IntegerToString(_par3);
         _name = "MovingShift";
         long _par4,_par4_start,_par4_step,_par4_stop;
         ParameterGetRange(_name,_enable,_par4,_par4_start,_par4_step,_par4_stop);
         _settings[3] = IntegerToString(_par4);
         
         */
         
         //WITH THIS RESULTS ARE NOT AS BUGGY BUT ARE INCORRECT. 
         //THE BEST RESULT IS NOT EXPORTED
         
         _settings[0] = DoubleToString(MaximumRisk,2);
         _settings[1] = DoubleToString(DecreaseFactor,2);
         _settings[2] = IntegerToString(MovingPeriod);
         _settings[3] = IntegerToString(MovingShift);
         
         Export(Symbol(),Period(),_settings);
         
         __result = _result;
      }
      return(_result);
   }

void OnTesterPass()
 {
 
 
 }
void OnTesterDeinit()
 {
 }

This is the code for exporting the setting which is included:

//+------------------------------------------------------------------+
//|                                                  MQL_Results.mqh |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
//+------------------------------------------------------------------+
//| defines                                                          |
//+------------------------------------------------------------------+
// #define MacrosHello   "Hello, world!"
// #define MacrosYear    2010
//+------------------------------------------------------------------+
//| DLL imports                                                      |
//+------------------------------------------------------------------+
// #import "user32.dll"
//   int      SendMessageA(int hWnd,int Msg,int wParam,int lParam);
// #import "my_expert.dll"
//   int      ExpertRecalculate(int wParam,int lParam);
// #import


void Export(string TesterSymbol,ENUM_TIMEFRAMES TesterTimeframe,string &Settings[])
   {
         ResetLastError();
         int _handle = FileOpen(TesterSymbol+"_"+EnumToString(TesterTimeframe)+"_settings.set",FILE_WRITE|FILE_CSV|FILE_COMMON);
         if(_handle!=INVALID_HANDLE)
         {
            FileWriteString(_handle,"MaximumRisk="+Settings[0]+"||0.01||0.002000||0.03||Y"+"\r\n");
            FileWriteString(_handle,"DecreaseFactor="+Settings[1]+"||2||0.1||5||Y"+"\r\n");
            FileWriteString(_handle,"MovingPeriod="+Settings[2]+"||6||1||18||Y"+"\r\n");
            FileWriteString(_handle,"MovingShift="+Settings[3]+"||0||1||12||Y"+"\r\n");
         }
         else
         {
            printf(__FUNCSIG__+" failed to create write handle with err: "+IntegerToString(GetLastError()));
         }
   }
//+------------------------------------------------------------------+
//| EX5 imports                                                      |
//+------------------------------------------------------------------+
// #import "stdlib.ex5"
//   string ErrorDescription(int error_code);
// #import
//+------------------------------------------------------------------+

And this is my ini:

[Common]
Login=9768793
Password=rvuls6tb
ProxyEnable=1
ProxyType=0
ProxyAddress=
ProxyLogin=10
ProxyPassword=10
KeepPrivate=1
NewsEnable=1
CertInstall=1
 
[Charts]
ProfileLast=Euro
MaxBars=50000
PrintColor=0
SaveDeleted=1
 
[Experts]
AllowLiveTrading=0
AllowDllImport=0
Enabled=1
Account=0
Profile=0
 
[Objects]
ShowPropertiesOnCreate=0
SelectOneClick=0
MagnetSens=10
 
;+------------------------------------------------------------------------------
;| Start testing or optimization of the specified Expert Advisor                |
;+------------------------------------------------------------------------------
[Tester]
;--- The EA is located in terminal_data_directory\MQL5\Experts\Examples\Moving Average
Expert=Examples\Moving Average\Moving Average
;--- The symbol for testing/optimization
Symbol=EURUSD
;--- The timeframe for testing/optimization
Period=H1
;--- Initial deposit
Deposit=100000
;--- Leverage for testing
Leverage=1:100
;--- The "1 minute OHLC" mode
Model=1
;--- Execution of trade orders with a random delay
ExecutionMode=0
;--- Genetic optimization This is what triggers the error if it is set to anthing but 0
Optimization=2
;--- Optimization criterion - Maximum balance drawdown value
OptimizationCriterion=0
;--- Start and end dates of the testing range
FromDate=2013.03.20
ToDate=2013.03.23
;--- Custom mode of forward testing
ForwardMode=0
;--- Start date of forward testing
ForwardDate=2011.03.01
;--- A file with a report will be saved in terminal_installation_folder
Report=opti-eurusd
;--- If the specified report already exists, it will be overwritten
ReplaceReport=1
ExpertParameters=MA_TEST.set
;--- Set automatic terminal shutdown upon completion of testing/optimization
ShutdownTerminal=0

What am I missing?

Reason: