Tuesday, December 2, 2025
HomeStockMQL5 Embody file Converts any In a single day Buying and selling...

MQL5 Embody file Converts any In a single day Buying and selling System into Intraday – Different – 1 December 2025

no_overnight_trades.mqh   >> The file is in a zipped folder on the finish of this text.

Add this MQL5 .mqh embody file to your EA if you wish to convert it to no in a single day trades.

This isn’t made for a multi-symbol EA. One Image loaded solely.

Helpful if eager to see in case your technique would work below the constraints of no in a single day trades.

Many futures prop companies do not permit in a single day trades. Take a look at in case your CFD technique would work with their guidelines..

This embody file will:

  • Shut your trades earlier than market shut; (enter market_close) minus (enter close_offset_min)   
  • Re-open your trades after market open; (enter market_open) plus (enter open_offset_min)

Offset inputs are in minutes. You possibly can set your brokers’ open and shutting time. 

  1. It takes a snapshot of the EA’s open trades close to the market shut, shops it in merchandise[] array,
  2.  Sends these trades in JSON format to a database .sqlite file saved in MQL5> File… listing
  3.  In the marketplace open EA will:

i) seek for open trades (in a single day trades) and excludes them from being reopened.

ii) seems on the market open value and excludes trades that both would have hit SL or TP in a single day,

usually occurs with value gap-up and gap-downs.

iii) re-opens all trades in the newest database entry that haven’t been excluded . These trades are saved within the hold[] array.

iv) the re-opened trades will copy; lot measurement, cease loss, take revenue and remark of every commerce within the .sqlite database. Clearly the open value of the commerce shall be completely different than earlier than.

The place to position no_overnight_trades.mqh in your EA   . 









#embody 




int OnInit()
{
        TS_Init(order_magic);   

        
        return(INIT_SUCCEEDED);
}




void OnDeinit(const int purpose)
{
      
      TS_Deinit();    
}




void OnTick()
{
        TS_OnTick();   

        

}

 no_overnight_trades.mqh





#property strict
#property copyright " (c)2025 Philip Sang-Nelson"
#embody 

enter lengthy   order_magic       = 123456;      
enter string market_open       = "16:35";     
enter int    open_offset_min   = 5;           
enter string market_close      = "22:55";     
enter int    close_offset_min  = 5;           
enter bool   debug_logging     = true;

int     g_db_handle = INVALID_HANDLE;
bool    g_db_ready  = false;
string  g_db_name   = "";
string  g_symbol    = "";
CTrade  commerce;
int     last_snapshot_day = -1;
int     last_reopen_day   = -1;


struct TradeItem
{
   lengthy   ticket;
   double heaps;
   double sl;
   double tp;
   string remark;
};


void Log(string s)
{
   if(debug_logging) PrintFormat("TS_DB: %s", s);
}


int HourFromStr(const string s) { return (int)(StringToInteger(StringSubstr(s,0,2))); }
int MinFromStr (const string s) { return (int)(StringToInteger(StringSubstr(s,3,2))); }
datetime TimeTodayAt(int h,int m)
{
   datetime now = TimeCurrent();
   MqlDateTime dt; TimeToStruct(now,dt);
   dt.hour = h; dt.min = m; dt.sec = 0;
   return StructToTime(dt);
}


string StringTrim(string pstring)
{
   StringTrimLeft(pstring);
   StringTrimRight(pstring);
   return pstring;
}


bool TS_Init(lengthy magic)
{
   commerce.SetExpertMagicNumber(order_magic);
   g_symbol = Image();
   g_db_name = StringFormat("%d_percents_trading_state.sqlite",(int)magic,g_symbol);

   g_db_handle = DatabaseOpen(g_db_name,
                              DATABASE_OPEN_READWRITE | DATABASE_OPEN_CREATE);
   if(g_db_handle == INVALID_HANDLE)
   {
      PrintFormat("TS_DB: Did not open DB '%s' (err %d)", g_db_name, GetLastError());
      g_db_ready = false;
      return false;
   }
   g_db_ready = true;

   string sql =
      "CREATE TABLE IF NOT EXISTS batches ("
      "id INTEGER PRIMARY KEY AUTOINCREMENT,"
      "ts INTEGER,"
      "path INTEGER,"     
      "knowledge TEXT,"
      "reopened INTEGER DEFAULT 0"
      ");";
   if(!DatabaseExecute(g_db_handle, sql))
   {
      PrintFormat("TS_DB: Create desk failed (err %d)", GetLastError());
      g_db_ready = false;
      return false;
   }
   Log("DB opened: " + g_db_name);
   return true;
}

void TS_Deinit()
{
   if(g_db_handle != INVALID_HANDLE)
      DatabaseClose(g_db_handle);
   g_db_handle = INVALID_HANDLE;
   g_db_ready = false;
   Log("DB closed.");
}


bool TS_InsertBatch(int path,string json_data)
{
   if(!g_db_ready) return false;
   int ts = (int)TimeCurrent();
   StringReplace(json_data,"'","''");
   string sql = StringFormat("INSERT INTO batches(ts,path,knowledge,reopened) VALUES(%d,%d,'%s',0);",
                             ts,path,json_data);
   if(!DatabaseExecute(g_db_handle,sql))
   {
      PrintFormat("TS_DB: Insert failed (err %d)",GetLastError());
      return false;
   }
   return true;
}


bool TS_LoadMostRecentBatch(int path, int &batch_id, string &json_out)
{
   batch_id = -1;
   json_out = "";
   if(!g_db_ready) return false;

   string sql = StringFormat("SELECT id,knowledge FROM batches WHERE path=%d ORDER BY ts DESC LIMIT 1;", path);
   int stmt = DatabasePrepare(g_db_handle, sql);
   if(stmt == INVALID_HANDLE)
   {
      PrintFormat("TS_DB: Put together failed (err %d)", GetLastError());
      return false;
   }

   int temp_id;
   if(DatabaseRead(stmt))
   {
      if(DatabaseColumnInteger(stmt, 0, temp_id))
         batch_id = temp_id;

      DatabaseColumnText(stmt, 1, json_out);
   }

   DatabaseFinalize(stmt);
   return (batch_id != -1 && StringLen(json_out) > 0);
}



void TS_ParseItem(const string json, TradeItem &out_item)


void TS_ParseArray(const string json, TradeItem &objects[])
{
   ArrayResize(objects,0);
   int pos=0;
   whereas(true)
   {
      int begin=StringFind(json,"{",pos);
      if(begin<0) break;
      int finish=StringFind(json,"}",begin);
      if(finish<0) break;
      string chunk=StringSubstr(json,begin,end-start+1);
      TradeItem merchandise;
      TS_ParseItem(chunk,merchandise);
      int newSize=ArraySize(objects)+1;
      ArrayResize(objects,newSize);
      objects[newSize-1]=merchandise;
      pos=finish+1;
   }
}


string TS_BuildJSON(TradeItem &merchandise)
{
   return StringFormat("{"ticket":%d, "heaps":%.2f, "sl":%.10g, "tp":%.10g, "remark":"%s"}",
                       merchandise.ticket,merchandise.heaps,merchandise.sl,merchandise.tp,merchandise.remark);
}

string TS_BuildJSONArray(TradeItem &objects[])
{
   int n=ArraySize(objects);
   if(n==0) return "[]";
   string out="[";
   for(int i=0;iif(i1) out+=",";
   }
   out+="]";
   return out;
}


double TS_GetTodayOpenPrice()
{
   double val=iOpen(g_symbol,PERIOD_M5,0);
   if(val<=0) val=SymbolInfoDouble(g_symbol,SYMBOL_BID);
   if(val<=0) val=SymbolInfoDouble(g_symbol,SYMBOL_ASK);
   return val;
}


string TS_SerializeOpenTrades(int path)
{
   string out="[";
   bool first=true;
   int total=PositionsTotal();
   for(int i=0;iif(!PositionGetTicket(i)) continue;
      if(PositionGetString(POSITION_SYMBOL)!=g_symbol) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=(long)order_magic) continue;
      int dir=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)?1:-1;
      if(dir!=direction) continue;
      TradeItem item;
      item.ticket=(long)PositionGetInteger(POSITION_TICKET);
      item.lots=PositionGetDouble(POSITION_VOLUME);
      item.sl=PositionGetDouble(POSITION_SL);
      item.tp=PositionGetDouble(POSITION_TP);
      item.comment=PositionGetString(POSITION_COMMENT);
      string row=TS_BuildJSON(item);
      if(first){ out+=row; first=false;} else out+=","+row;
   }
   out+="]";
   return out;
}


void TS_CloseAllFor(int path)
{
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      if(!PositionGetTicket(i)) proceed;
      if(PositionGetString(POSITION_SYMBOL)!=g_symbol) proceed;
      if(PositionGetInteger(POSITION_MAGIC)!=(lengthy)order_magic) proceed;
      int dir=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)?1:-1;
      if(dir!=path) proceed;
      ulong ticket=(ulong)PositionGetInteger(POSITION_TICKET);
      if(!commerce.PositionClose(ticket))
         PrintFormat("TS_DB: Shut failed ticket %d error %d",ticket,GetLastError());
      else Log("Closed ticket "+(string)ticket);
   }
}


void TS_SnapshotAndClose()
{
   for(int d=0;d<2;d++)
   {
      int dir=(d==0)?1:-1;
      string json=TS_SerializeOpenTrades(dir);
      TS_InsertBatch(dir,json);
      TS_CloseAllFor(dir);
      Log("Snapshot saved for dir="+IntegerToString(dir));
   }
}


void TS_FilterByOpen(TradeItem &in_items[], TradeItem &out_items[], int path)
{
   ArrayResize(out_items,0);
   double open_price=TS_GetTodayOpenPrice();
   for(int i=0;i<ArraySize(in_items);i++)
   {
      bool stopped=false;
      if(path==1 && open_price<=in_items[i].sl) stopped=true;
      if(path==-1 && open_price>=in_items[i].sl) stopped=true;
      if(path==1 && open_price>= in_items[i].tp) stopped=true;
      if(path==-1 && open_price<=in_items[i].tp) stopped=true;
      if(!stopped)
      {
         int newSize=ArraySize(out_items)+1;
         ArrayResize(out_items,newSize);
         out_items[newSize-1]=in_items[i];
      }
   }
}


void TS_ReopenTrades(TradeItem &objects[], int path)
{
   for(int i = 0; i < ArraySize(objects); i++)
   {
      bool already_open = false;
      

      
      for(int p = 0; p < PositionsTotal(); p++)
      {
         if(!PositionGetTicket(p)) proceed;
         
         if(PositionGetString(POSITION_SYMBOL) != g_symbol) proceed;
         if(PositionGetInteger(POSITION_MAGIC) != (lengthy)order_magic) proceed;

         int dir = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? 1 : -1;
         if(dir != path) proceed;

         
         if(PositionGetInteger(POSITION_TICKET) == objects[i].ticket)
         {
            already_open = true;
            break;
         }
      }

      if(already_open) proceed;

      
      bool okay = false;

      if(path == 1)
      {
         double ask = SymbolInfoDouble(g_symbol, SYMBOL_ASK);
         okay = commerce.Purchase(objects[i].heaps, g_symbol, ask, objects[i].sl, objects[i].tp, objects[i].remark);
      }
      else
      {
         double bid = SymbolInfoDouble(g_symbol, SYMBOL_BID);
         okay = commerce.Promote(objects[i].heaps, g_symbol, bid, objects[i].sl, objects[i].tp, objects[i].remark);
      }

      if(okay)
         Log("Reopened commerce from hold[] index " + (string)i);
      else
         PrintFormat("Reopen failed for hold[%d], error %d", i, GetLastError());
   }
}



void TS_ReopenFromMostRecent()
{
   for(int d=0;d<2;d++)
   {
      int path=(d==0)?1:-1;
      int batch_id; string json;
      if(!TS_LoadMostRecentBatch(path,batch_id,json)) {Log("No batch for dir "+IntegerToString(path)); proceed;}
      TradeItem objects[]; TS_ParseArray(json,objects);
      if(ArraySize(objects)==0) {Log("Empty batch"); proceed;}
      TradeItem hold[]; TS_FilterByOpen(objects,hold,path);
      string new_json=TS_BuildJSONArray(hold);
      TS_InsertBatch(path,new_json);
      TS_ReopenTrades(hold,path);
      string mark_sql=StringFormat("UPDATE batches SET reopened=1 WHERE id=%d;",batch_id);
      DatabaseExecute(g_db_handle,mark_sql);
   }
}


void TS_OnTick()
{
   if(!g_db_ready) return;

   int open_h=HourFromStr(market_open);
   int open_m=MinFromStr(market_open);
   int close_h=HourFromStr(market_close);
   int close_m=MinFromStr(market_close);

   datetime open_dt=TimeTodayAt(open_h,open_m);
   datetime reopen_dt=open_dt+open_offset_min*60;
   datetime close_dt=TimeTodayAt(close_h,close_m);
   datetime snapshot_dt=close_dt-close_offset_min*60;

   MqlDateTime tm; TimeToStruct(TimeCurrent(),tm);
   int in the present day=tm.day;

   if(in the present day!=last_snapshot_day && TimeCurrent()>=snapshot_dt)
   TIME_SECONDS));
      TS_SnapshotAndClose();
      last_snapshot_day=in the present day;
   

   if(in the present day!=last_reopen_day && TimeCurrent()>=reopen_dt)

   TIME_SECONDS));
      TS_ReopenFromMostRecent();
      last_reopen_day=in the present day;
   
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments