sSaveSetFunctions

Download script
sSaveSetFunctions

This script is a utility designed for traders who perform "optimization" on their trading robots (Expert Advisors). When optimizing, traders test hundreds of different settings to find the most profitable combination. This script automates the process of saving every single result so that you don't lose your best configurations.

Core Purpose

The primary goal of this tool is to automatically capture and save the specific settings, profit results, and performance metrics of an Expert Advisor (EA) after every run during an optimization process. It creates a structured log of all tests, making it easy for the user to review which settings performed best without having to scroll through thousands of lines of raw data.

How It Works

The script functions by performing three main actions:

1. Automatic Code Generation When you run this script and provide the name of your Expert Advisor, it generates a new text file for you. This file contains specific blocks of code that you are instructed to copy and paste into your robot. By adding these pieces of code, you "hook" the saving logic into your robot's internal processes.

2. Performance Tracking & Logging Once the code is integrated, every time the robot finishes a trading cycle during optimization:

  • Data Snapshot: It captures key statistics including total profit, number of trades, profit factor, expected payoff, and maximum drawdown (both in currency and percentage).
  • Settings Backup: It automatically saves the specific input parameters used for that exact run into a unique .set file.
  • HTML Reporting: It builds an organized HTML report. This report acts like a summary table where you can see all your test results side-by-side in a clean, web-browser-friendly format.

3. Data Organization To keep things tidy, the script creates a dedicated folder for your specific robot. Inside this folder:

  • Each test result is numbered (e.g., 001.set, 002.set).
  • The HTML report contains clickable links to these files, allowing you to jump straight to the settings of any specific test result.

Key Benefits for the User

  • Never Lose a Good Result: You no longer have to manually write down "good" settings; the script saves every single one automatically.
  • Easy Comparison: The HTML report allows you to compare different strategies visually, showing you at a glance which ones had the highest profit vs. the highest risk (drawdown).
  • Reproducibility: Because it saves the .set files, you can instantly load the exact successful parameters back into your trading platform to start live trading.
Price Data Components
Series array that contains open time of each bar
Orders Execution
Checks for the total of closed orders
Miscellaneous
It issuies visual alerts to the screenUses files from the file systemIt writes information to fileIt reads information from a file
9 Views
1 Downloads
0 Favorites
sSaveSetFunctions
//+------------------------------------------------------------------+
//|                                            sSaveSetFunctions.mq4 |
//|                                                                * |
//|                                                                * |
//+------------------------------------------------------------------+

/*
   Ñêðèïò ãåíåðàòîð êîäà ôóíêöèè, ñîõðàíÿþùåé ôàéëû íàñòðîåê ñîâåòíèêà îò êàæäîãî ïðîãîíà
   ïðè îïòèìèçàöèè.
   
   Çàïóñêàåì ñêðèïò, ââîäèì èìÿ ôàéëà ýñïåðòà, ïîëó÷àåì ôàéë ñ êîäîì è èíñòðóêöèÿìè ïî
   åãî âñòàâêå â êîä ñîâåòíèêà (âñòàâèòü íå ñëîæíî).
   
   Â ïðîöåññå îïòèìèçàöèè, ïîñëå êàæäîãî ïðîõîäà, â êàòàëîãå 
   ...tester\files\SaveSet [èìÿ ýêñïåðòà] ñîõðàíÿþòñÿ
   ïðîíóìåðîâàííûå ôàéëû *.set, äåëàåòñÿ çàïèñü â ôàéë
   Report.htm î ðåçóëüòàòàõ êàæäîãî ïðîõîäà îïòèìèçàöèè (ïðèáûëü, 
   êîëè÷åñòâî ñäåëîê è ò.ï.) è äåëàåòñÿ êîïèÿ ôàéëà 
   [èìÿ ýêñïåðòà].ini (÷òîáû ìîæíî áûëî â äàëüíåéøåì âîñïðîèçâåñòè 
   ïàðàìåòðû îïòèìèçàöèè, íóæíî çàìåíèòü ôàéë ini íàõîäÿùèéñÿ â
   êàòàëîãå tester). Òàêèì îáðàç, ïîëå ïðîâåäåííîé îïòèìèçàöèè
   âñåãäà ìîæíî âåðíóòüñÿ ê åå ðåçóëüòàòì.
      
   
*/


#property copyright "http://dmffx.com"
#property link      "http://dmffx.com"
#import "kernel32.dll"
   int CopyFileA (string lpExistingFileName,string lpNewFileName,int bFailIfExists);
#import

#property show_inputs
extern string ExpFileName="";

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start(){

      if(fCreateSaveSetFunction(ExpFileName)){
         Alert("Ok! See file "+"\"SaveSet "+ExpFileName+".txt\"");
      }
   return(0);
}
//+------------------------------------------------------------------+

bool fCreateSaveSetFunction(string aExpertFileName){
   string tVarList[][3];
      if(!fGetExtVarList(aExpertFileName,tVarList)){
         return(false);
      }
   int th=FileOpen("SaveSet "+aExpertFileName+".txt",FILE_CSV|FILE_WRITE);

    FileWrite(th,"//+------------------------------------------------------------------+");
    FileWrite(th,"// Insert next to the most top of EA code:");
    FileWrite(th,"// Âñòàâüòå ñëåäóþùåå â ñàìûé âåðõ êîäà ýêñïåðòà:");
    FileWrite(th,"//+------------------------------------------------------------------+");
    FileWrite(th,"");    
    FileWrite(th,"#import \"kernel32.dll\"");
    FileWrite(th,"   int CopyFileA (string lpExistingFileName,string lpNewFileName,int bFailIfExists);");
    FileWrite(th,"#import");
    FileWrite(th,"");    
    FileWrite(th,"");  
    FileWrite(th,"");   
              
    FileWrite(th,"//+------------------------------------------------------------------+");              
    FileWrite(th,"// Insert next to the top or bottom of deinit() function code:");
    FileWrite(th,"// Âñòàâüòå ñëåäóþùåå ñâåðõó èëè ñíèçó â êîä ôóíêöèè deinit():");
    FileWrite(th,"//+------------------------------------------------------------------+");
    FileWrite(th,"");  
    FileWrite(th,"fSaveSet_CreateSetFile();");      
    FileWrite(th,"");    
    FileWrite(th,"");  
    FileWrite(th,"");                 
              
    FileWrite(th,"//+------------------------------------------------------------------+");                
    FileWrite(th,"// Insert next to the most top of start() function code:");
    FileWrite(th,"// Âñòàâüòå ñëåäóþùåå â ñàìûé âåðõ êîäà ôóíêöèè start():");
    FileWrite(th,"//+------------------------------------------------------------------+");
    FileWrite(th,"");  
    FileWrite(th,"fSaveSet_MaximalDrawDown();");      
    FileWrite(th,"");    
    FileWrite(th,"");  
    FileWrite(th,"");       
    
    FileWrite(th,"//+------------------------------------------------------------------+");
    FileWrite(th,"// Insert next to the most bottom of EA code: ");
    FileWrite(th,"// Âñòàâüòå ñëåäóþùåå â ñàìûé íèç êîäà ýêñïåðòà: ");
    FileWrite(th,"//+------------------------------------------------------------------+");
    FileWrite(th,"");    
    FileWrite(th,"void fSaveSet_CreateSetFile(){");
    FileWrite(th,"    CopyFileA(TerminalPath()+\"/tester/\"+WindowExpertName()+\".ini\",TerminalPath()+\"/tester/files/\"+\"SaveSet \"+WindowExpertName()+\"/\"+WindowExpertName()+\".ini\",0);");
    FileWrite(th,"    int th=FileOpen(\"SaveSet \"+WindowExpertName()+\"/\"+\"cnt.txt\",FILE_CSV|FILE_READ|FILE_WRITE);");
    FileWrite(th,"    int tCnt=StrToInteger(FileReadString(th))+1;");
    FileWrite(th,"    FileClose(th);");
    FileWrite(th,"    th=FileOpen(\"SaveSet \"+WindowExpertName()+\"/\"+\"cnt.txt\",FILE_CSV|FILE_WRITE);");
    FileWrite(th,"    FileWrite(th,tCnt);");
    FileWrite(th,"    FileClose(th);");
    FileWrite(th,"    double tProfit;");
    FileWrite(th,"    int tTotalTrades;");
    FileWrite(th,"    double tProfitFactor;");
    FileWrite(th,"    double tExpectedPayoff;");
    FileWrite(th,"    datetime tDateFrom;");
    FileWrite(th,"    datetime tDateTo;");
    FileWrite(th,"    fSaveSet_ShortTradeReport(tProfit,tTotalTrades,tProfitFactor,tExpectedPayoff,tDateFrom,tDateTo);");
    FileWrite(th,"    th=FileOpen(\"SaveSet \"+WindowExpertName()+\"/Report.htm\",FILE_CSV|FILE_READ|FILE_WRITE,\"\t\");");
    FileWrite(th,"        if(FileSize(th)==0){");
    FileWrite(th,"            FileWrite(th,\"<style>\");");
    FileWrite(th,"            FileWrite(th,\"p{background-color: #FFFFFF; font-family: Arial; font-size: 10pt; color: #000000}\");");
    FileWrite(th,"            FileWrite(th,\"A:visited{color: #0000FF; text-decoration: none;}\");");
    FileWrite(th,"            FileWrite(th,\"A:link{color: #0000FF; text-decoration: none;}\");");
    FileWrite(th,"            FileWrite(th,\"A:hover{color: #FF0000; text-decoration: none;}\");");
    FileWrite(th,"            FileWrite(th,\"A:active{color: #FF0000; text-decoration: none;}\");");
    FileWrite(th,"            FileWrite(th,\"tr.h{background-color: #E0E0E0; font-family: Arial; font-size: 8pt; font-weight: bold; color: #000000;}\");");
    FileWrite(th,"            FileWrite(th,\"tr.c{background-color: #F0F0F0; font-family: Arial; font-size: 8pt; color: #000000}</style>\");");
    FileWrite(th,"            FileWrite(th,\"<p class=p1><b>Expert:</b> \"+WindowExpertName()+\"<br><b>Chart:</b> \"+Symbol()+\" \"+Period()+\"<br><b>Time:</b> \"+TimeToStr(fSaveSet_StartTime())+\"-\"+TimeToStr(fSaveSet_EndTime())+\"</p>\");");
    FileWrite(th,"            FileWrite(th,\"<table border=0 cellspacing=2 cellpadding=1><tr class=h><td>¹</td><td>Profit</td><td>Total trades</td><td>Frofit factor</td><td>Expected Payoff</td><td>Drawdown $</td><td>Drawdown %</td><td>Set file</td></tr>\");");
    FileWrite(th,"        }");
      
    FileWrite(th,"    FileSeek(th,0,SEEK_END);");
    FileWrite(th,"    string tCntStr=tCnt;");
    FileWrite(th,"        while(StringLen(tCntStr)<8){");
    FileWrite(th,"            tCntStr=\"0\"+tCntStr;");
    FileWrite(th,"        }");
    string tstr;
    tstr="    FileWrite(th,\"<tr class=c><td>\"+tCnt+\"</td><td>\"+DoubleToStr(tProfit,2)+\"</td><td>\"+tTotalTrades+\"</td><td>\"+DoubleToStr(tProfitFactor,2)+\"</td><td>\"+DoubleToStr(tExpec";
    tstr=tstr+"tedPayoff,2)+\"</td><td>\"+DoubleToStr(fSaveSet_MaximalDrawDown(),2)+\"</td><td>\"+DoubleToStr(fSaveSet_MaximalDrawDownPerc(),2)+\"</td><td><a href=\"+tCntStr+\".set\"+\">\"+tCntStr+\".set\"+\"</a></td></tr>\");";
    FileWrite(th,tstr);
    FileWrite(th,"    FileClose(th);");
    FileWrite(th,"    th=FileOpen(\"SaveSet \"+WindowExpertName()+\"/\"+tCntStr+\".set\",FILE_CSV|FILE_WRITE);");
      for(int ti=0;ti<ArraySize(tVarList)/3;ti++){
         FileWrite(th,"    FileWrite(th,"+"\""+tVarList[ti][1]+"=\"+"+tVarList[ti][1]+");");
      }
   FileWrite(th,"}");      
   FileWrite(th,"");       


   FileWrite(th,"double fSaveSet_MaximalProfit(){");
   FileWrite(th,"   static double sMaxProfit=0;");
   FileWrite(th,"   sMaxProfit=MathMax(sMaxProfit,AccountEquity());");
   FileWrite(th,"   return(sMaxProfit);");
   FileWrite(th,"}");
   FileWrite(th,"");
   FileWrite(th,"double fSaveSet_MaximalDrawDown(){");
   FileWrite(th,"   static double sMaximalDrawDown=0;");
   FileWrite(th,"   sMaximalDrawDown=MathMax(sMaximalDrawDown,fSaveSet_MaximalProfit()-AccountEquity());");
   FileWrite(th,"   fSaveSet_StartTime();");
   FileWrite(th,"   fSaveSet_EndTime();");
   FileWrite(th,"   return(sMaximalDrawDown);");
   FileWrite(th,"}");
   FileWrite(th,"");
   FileWrite(th,"double fSaveSet_MaximalDrawDownPerc(){");
   FileWrite(th,"   return(100.0*fSaveSet_MaximalDrawDown()/fSaveSet_MaximalProfit());");
   FileWrite(th,"}");
   FileWrite(th,"");
   FileWrite(th,"datetime fSaveSet_StartTime(){");
   FileWrite(th,"   static datetime sStartTime=0;");
   FileWrite(th,"   if(sStartTime==0)sStartTime=TimeCurrent();");
   FileWrite(th,"   return(sStartTime);");
   FileWrite(th,"}");
   FileWrite(th,"");
   FileWrite(th,"datetime fSaveSet_EndTime(){");
   FileWrite(th,"   static datetime sEndTime=0;");
   FileWrite(th,"   sEndTime=MathMax(sEndTime,TimeCurrent());");
   FileWrite(th,"   return(sEndTime);");
   FileWrite(th,"}");
   FileWrite(th,"");
   FileWrite(th,"void fSaveSet_ShortTradeReport(double & aProfit, int & aTotalTrades,double & aProfitFactor,double & aExpectedPayoff,datetime & aDateFrom,datetime & aDateTo){");
   FileWrite(th,"   aProfit=0;");   
   FileWrite(th,"   aTotalTrades=0;");
   FileWrite(th,"   double tGrossProfit=0;");
   FileWrite(th,"   double tGrossLoss=0;");   
   FileWrite(th,"   double tProfitTrades=0;");
   FileWrite(th,"   double tLossTrades=0;");
   FileWrite(th,"   aDateFrom=0;");
   FileWrite(th,"   aDateTo=0;");
   FileWrite(th,"      for(int ti=0;ti<OrdersHistoryTotal();ti++){");
   FileWrite(th,"         OrderSelect(ti,SELECT_BY_POS,MODE_HISTORY);");
   FileWrite(th,"            if(OrderType()==OP_BUY || OrderType()==OP_SELL){");
   FileWrite(th,"                  if(aDateFrom==0){");
   FileWrite(th,"                     aDateFrom=OrderOpenTime();");
   FileWrite(th,"                  }");
   FileWrite(th,"               aDateTo=MathMax(aDateTo,OrderCloseTime());");
   FileWrite(th,"               double tProfit=OrderProfit()+OrderCommission()+OrderSwap();");
   FileWrite(th,"               aProfit+=tProfit;");
   FileWrite(th,"               aTotalTrades++;");
   FileWrite(th,"                  if(tProfit>0){");
   FileWrite(th,"                     tGrossProfit+=tProfit;");
   FileWrite(th,"                     tProfitTrades++;");
   FileWrite(th,"                  }");
   FileWrite(th,"                  if(tProfit<0){");
   FileWrite(th,"                     tGrossLoss+=-tProfit;");
   FileWrite(th,"                     tLossTrades++;");
   FileWrite(th,"                  }");
   FileWrite(th,"            }");
   FileWrite(th,"      }");
   FileWrite(th,"   aProfitFactor=-1;");
   FileWrite(th,"      if(NormalizeDouble(tGrossLoss,2)!=0){");
   FileWrite(th,"         aProfitFactor=tGrossProfit/tGrossLoss;");
   FileWrite(th,"      }");
   FileWrite(th,"   aExpectedPayoff=-1;");
   FileWrite(th,"      if(aTotalTrades!=0 && tProfitTrades!=0 && tLossTrades!=0){");
   FileWrite(th,"         aExpectedPayoff=(tProfitTrades/aTotalTrades)*(tGrossProfit/tProfitTrades)-(tLossTrades/aTotalTrades)*(tGrossLoss/tLossTrades);");
   FileWrite(th,"      }");
   FileWrite(th,"}");    
   FileClose(th);   
   return(true);   
}

bool fGetExtVarList(string aExpertFileName,string & aVarList[][3]){
   ArrayResize(aVarList,0);
   int tSize=0;
      if(!IsDllsAllowed()){
         Alert("Allow DLL");
         return(false);
      }
   string tFrom=TerminalPath()+"\\experts\\"+aExpertFileName;
   string tTo=TerminalPath()+"\\experts\\files\\tmp.tmp";
   int z=CopyFileA(tFrom,tTo,0);
         if(z==0){
            Alert("No file \""+tFrom+"\"");
            return(false);
         }
      int th=FileOpen("tmp.tmp",FILE_CSV|FILE_READ);
         while(!FileIsEnding(th)){
            string str=FileReadString(th);
            str=fStrTrim(str);
               if(str!=""){
                  if(StringFind(str,"extern",0)==0){
                     str=StringSubstr(str,6,StringLen(str)-6);
                     str=fStrTrim(str);
                     string tType="";
                     string tDefVal;
                        if(StringFind(str,"int",0)==0){
                           tType="int";
                           tDefVal="0";
                        }
                        if(StringFind(str,"double",0)==0){
                           tType="double";
                           tDefVal="0.0";
                        }
                        if(StringFind(str,"bool",0)==0){
                           tType="bool";
                           tDefVal="false";
                        }
                        if(StringFind(str,"string",0)==0){
                           tType="string";
                           tDefVal="";
                        }
                        if(StringFind(str,"color",0)==0){
                           tType="color";
                           tDefVal="CLR_NONE";
                        }
                        if(StringFind(str,"datetime",0)==0){
                           tType="datetime";
                           tDefVal="0";
                        }
                     str=StringSubstr(str,StringLen(tType),StringLen(str)-StringLen(tType));
                     str=fStrTrim(str);
                     string tmp3[];
                        if(tType=="string"){                           
                           str=fReplaceStrContent(str,tmp3);
                        }
                     string tmp[];
                     fStrSplit(str,tmp,",");
                     int tj=0;
                        for(int ti=0;ti<ArraySize(tmp);ti++){
                           ArrayResize(aVarList,tSize+1);
                           aVarList[tSize][0]=tType;
                           string tmp2[];
                           fStrSplit(tmp[ti],tmp2,"=");
                           aVarList[tSize][1]=fStrTrim(tmp2[0]);
                              if(tType=="string"){
                                 if(ArraySize(tmp2)>1){
                                    aVarList[tSize][2]=tmp3[tj];
                                    tj++; 
                                 }
                                 else{
                                    aVarList[tSize][2]=tDefVal;
                                 }                              
                              }
                              else{
                                 if(ArraySize(tmp2)>1){
                                    aVarList[tSize][2]=fStrTrim(tmp2[1]);
                                       if(tType=="bool"){
                                          if(aVarList[tSize][2]=="FALSE"){
                                             aVarList[tSize][2]="false";
                                          }
                                          if(aVarList[tSize][2]=="TRUE"){
                                             aVarList[tSize][2]="true";
                                          }                                          
                                       }
                                 }
                                 else{
                                    aVarList[tSize][2]=tDefVal;
                                 }
                              }
                           tSize++;   
                        }                        
                     

                  }

               }
         }
   FileClose(th);         
   FileDelete("tmp.tmp"); 
   return(true);           
}

string fReplaceStrContent(string aString,string & aArray[]){
   ArrayResize(aArray,0);
   int tQuteCounter=0;
   int tStart;
   int tEnd;
   string tStr=""; 
      for(int ti=0;ti<StringLen(aString);ti++){
         string tChar=StringSubstr(aString,ti,1);
               if(tChar=="\""){
                     if(tQuteCounter==0){
                        tStart=ti+1;
                     }
                     if(StringSubstr(aString,ti-1,1)!="\\"){
                        tQuteCounter++;
                           if(tQuteCounter==2){
                              tEnd=ti;
                              tQuteCounter=0;
                              tStr=tStr+"x";
                              ArrayResize(aArray,ArraySize(aArray)+1);
                                 if(tEnd-tStart==0){
                                    aArray[ArraySize(aArray)-1]="";
                                 }
                                 else{
                                    aArray[ArraySize(aArray)-1]=StringSubstr(aString,tStart,tEnd-tStart);
                                 }
                           }
                     }
                  continue;
               } 
               if(tQuteCounter==0){
                  tStr=tStr+tChar;        
               }
      }
   return(tStr);
}

void fStrSplit(string aString,string & aArray[],string aDelimiter){
   int tCounter=0;
   int tDelimiterLength=StringLen(aDelimiter);
   ArrayResize(aArray,tCounter);
   int tPos1=0;
   int tPos2=StringFind(aString,aDelimiter,0);
      while(tPos2!=-1){
            if(tPos2>=tPos1){
               tCounter++;
               ArrayResize(aArray,tCounter);
                  if(tPos2-tPos1==0){
                     aArray[tCounter-1]="";
                  }
                  else{
                     aArray[tCounter-1]=StringSubstr(aString,tPos1,tPos2-tPos1);
                  }
            }
         tPos1=tPos2+tDelimiterLength;
         tPos2=StringFind(aString,aDelimiter,tPos1);
      }
   tPos2=StringLen(aString);      
      if(tPos2>=tPos1){
         tCounter++;   
         ArrayResize(aArray,tCounter);
            if(tPos2-tPos1==0){
               aArray[tCounter-1]="";
            }
            else{
               aArray[tCounter-1]=StringSubstr(aString,tPos1,tPos2-tPos1);      
            }
      }
}

string fStrTrim(string aString){
   return(StringTrimLeft(StringTrimRight(aString)));
}

Comments