<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Omais Ali</title>
    <description>The latest articles on DEV Community by Omais Ali (@omaisali).</description>
    <link>https://dev.to/omaisali</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4173524%2F25bad014-e6df-4e8d-ad5f-db874f3b23fc.png</url>
      <title>DEV Community: Omais Ali</title>
      <link>https://dev.to/omaisali</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/omaisali"/>
    <language>en</language>
    <item>
      <title>Measuring how long your MQL5 OnTick really takes</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Fri, 20 Nov 2026 06:24:29 +0000</pubDate>
      <link>https://dev.to/omaisali/measuring-how-long-your-mql5-ontick-really-takes-e3d</link>
      <guid>https://dev.to/omaisali/measuring-how-long-your-mql5-ontick-really-takes-e3d</guid>
      <description>&lt;p&gt;When an Expert Advisor feels slow on a VPS, people often guess at the cause. A better approach is to measure it. MQL5 gives you GetMicrosecondCount, which is enough to profile OnTick without any external tools.&lt;/p&gt;

&lt;h2&gt;
  
  
  The basic pattern
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="n"&gt;ulong&lt;/span&gt; &lt;span class="n"&gt;g_total_us&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;ulong&lt;/span&gt; &lt;span class="n"&gt;g_max_us&lt;/span&gt;   &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kt"&gt;long&lt;/span&gt;  &lt;span class="n"&gt;g_calls&lt;/span&gt;    &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;OnTick&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="n"&gt;ulong&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GetMicrosecondCount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

   &lt;span class="nc"&gt;RunStrategy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// your existing logic&lt;/span&gt;

   &lt;span class="n"&gt;ulong&lt;/span&gt; &lt;span class="n"&gt;took&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GetMicrosecondCount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="n"&gt;g_total_us&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;took&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="n"&gt;g_calls&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;took&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;g_max_us&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="n"&gt;g_max_us&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;took&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;OnDeinit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reason&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_calls&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="nc"&gt;PrintFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"OnTick calls=%I64d avg=%.1f us max=%I64u us"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                  &lt;span class="n"&gt;g_calls&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;double&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;g_total_us&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;g_calls&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;g_max_us&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The average tells you the normal cost. The maximum tells you about the spikes, and the spikes are usually what hurts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Time the pieces, not just the whole
&lt;/h2&gt;

&lt;p&gt;Once you know OnTick is slow, wrap the suspects separately: indicator buffer copies, history selection, file writes and order sending. A common finding is that HistorySelect over the full account history on every tick costs far more than the strategy logic itself. Restrict the range, or cache results and refresh only on a new bar.&lt;/p&gt;

&lt;h2&gt;
  
  
  Log slow ticks as they happen
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;took&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;50000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;// 50 ms&lt;/span&gt;
   &lt;span class="nc"&gt;PrintFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Slow tick: %I64u us at %s"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;took&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TimeToString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TimeCurrent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;TIME_SECONDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep the threshold high enough that the journal does not fill up, because printing is itself slow.&lt;/p&gt;

&lt;h2&gt;
  
  
  A few things to remember
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Measure on the same VPS the EA runs on. A desktop machine can be several times faster.&lt;/li&gt;
&lt;li&gt;Remove or reduce the profiling once you have your answer, or guard it behind an input flag.&lt;/li&gt;
&lt;li&gt;The Strategy Tester runs your code differently from live, so confirm timings on a demo chart too.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Knowing the real numbers turns a vague complaint about lag into a specific fix.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>metatrader</category>
      <category>algotrading</category>
      <category>performance</category>
    </item>
    <item>
      <title>Running one MQL5 EA on several symbols without missing new bars</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Thu, 19 Nov 2026 06:18:17 +0000</pubDate>
      <link>https://dev.to/omaisali/running-one-mql5-ea-on-several-symbols-without-missing-new-bars-2nml</link>
      <guid>https://dev.to/omaisali/running-one-mql5-ea-on-several-symbols-without-missing-new-bars-2nml</guid>
      <description>&lt;p&gt;A common request is an Expert Advisor that sits on one chart but trades a basket, for example EURUSD, GBPUSD and USDJPY. The first version usually puts all the logic in OnTick and checks every symbol there. It works in a quick test and then misbehaves on a live account. This post explains why, and shows a small pattern that has held up well for me.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why OnTick is the wrong clock for a basket
&lt;/h2&gt;

&lt;p&gt;OnTick fires only for ticks of the chart symbol. If the EA is attached to EURUSD and EURUSD goes quiet for twenty seconds, your GBPUSD and USDJPY logic also waits twenty seconds, even if those markets are moving. Worse, if your rule is "act once when a new bar opens", a slow chart symbol can make you see the GBPUSD new bar late, or in rare cases skip it when two bars pass between checks.&lt;/p&gt;

&lt;p&gt;The fix is to drive the basket from a timer and to track the last bar time separately for each symbol.&lt;/p&gt;

&lt;h2&gt;
  
  
  The pattern
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="nc"&gt;InpSymbols&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"EURUSD,GBPUSD,USDJPY"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="no"&gt;ENUM_TIMEFRAMES&lt;/span&gt; &lt;span class="nc"&gt;InpTf&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;PERIOD_M15&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;string&lt;/span&gt;   &lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="n"&gt;g_lastBar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nc"&gt;OnInit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;StringSplit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InpSymbols&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;','&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="no"&gt;INIT_PARAMETERS_INCORRECT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="nc"&gt;ArrayResize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_lastBar&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nc"&gt;StringTrimLeft&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="nc"&gt;StringTrimRight&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nc"&gt;SymbolSelect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="p"&gt;{&lt;/span&gt;
         &lt;span class="nc"&gt;Print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Cannot select "&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="no"&gt;INIT_FAILED&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
      &lt;span class="n"&gt;g_lastBar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="nc"&gt;EventSetTimer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="no"&gt;INIT_SUCCEEDED&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;OnDeinit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reason&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;EventKillTimer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;OnTimer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nc"&gt;ArraySize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;iTime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;InpTf&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;              &lt;span class="c1"&gt;// history not ready yet&lt;/span&gt;
      &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_lastBar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;g_lastBar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
      &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;g_lastBar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="p"&gt;{&lt;/span&gt;
         &lt;span class="n"&gt;g_lastBar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="nc"&gt;OnNewBar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g_syms&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;OnTick&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;OnTimer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;OnNewBar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;sym&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="nc"&gt;Print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sym&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;" new bar at "&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TimeToString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;iTime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sym&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;InpTf&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="c1"&gt;// signal and order logic for sym goes here&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Details that matter
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The first pass only records the bar time. Without that, a restart would treat the current bar as new on every symbol and fire a burst of entries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;iTime can return 0 while history for a symbol is still loading, especially right after the terminal starts. Skipping that pass is safer than acting on missing data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Calling the same routine from OnTick keeps the chart symbol responsive, and the per symbol bar time makes double processing harmless.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Every symbol needs its own spread, stops level and volume step. Never reuse values read from the chart symbol. Read them with SymbolInfoDouble and SymbolInfoInteger for the symbol you are about to trade.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use one magic number for the EA and filter positions by both magic and symbol, so the exit logic for USDJPY never touches the GBPUSD position.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Broker suffixes are real. If the broker lists EURUSD.m, the input list must match, so validate each name in OnInit and fail loudly rather than trading two symbols out of three.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Testing it
&lt;/h2&gt;

&lt;p&gt;In the Strategy Tester, choose "Every tick based on real ticks" and make sure every symbol in the list has history downloaded. The tester loads extra symbols on demand, and a missing one usually shows up as a silent lack of trades rather than an error, so check the journal for each name.&lt;/p&gt;

&lt;p&gt;A one second timer is plenty for bar based logic. If you need tick level reactions on several symbols, that is a different design and usually calls for one EA instance per chart instead.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>metatrader</category>
      <category>algotrading</category>
    </item>
    <item>
      <title>What the MQL5 CTrade class does for you, and what it quietly does not</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Tue, 17 Nov 2026 06:38:38 +0000</pubDate>
      <link>https://dev.to/omaisali/what-the-mql5-ctrade-class-does-for-you-and-what-it-quietly-does-not-42bn</link>
      <guid>https://dev.to/omaisali/what-the-mql5-ctrade-class-does-for-you-and-what-it-quietly-does-not-42bn</guid>
      <description>&lt;p&gt;Most MQL5 code samples use the CTrade class from the standard library. It is a good choice, but a lot of EA bugs come from assuming it does more than it does. Here is what it actually handles and where you still need your own code.&lt;/p&gt;

&lt;h2&gt;
  
  
  What CTrade handles
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Filling the MqlTradeRequest structure for you. Buy, Sell, PositionClose and PositionModify build the request with the right action and fields.&lt;/li&gt;
&lt;li&gt;Setting the magic number and deviation once with SetExpertMagicNumber and SetDeviationInPoints.&lt;/li&gt;
&lt;li&gt;Choosing a filling type if you call SetTypeFillingBySymbol with the symbol.&lt;/li&gt;
&lt;li&gt;Keeping the last result, which you can read with ResultRetcode, ResultOrder and ResultDeal.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What it does not handle
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;It does not normalize your lot size to the volume step or check minimum and maximum volume. Pass 0.123 lots and the broker rejects it.&lt;/li&gt;
&lt;li&gt;It does not check stop distance against SYMBOL_TRADE_STOPS_LEVEL. A stop too close to price gets rejected with invalid stops.&lt;/li&gt;
&lt;li&gt;It does not retry. If the server returns a requote or price changed, the call simply fails.&lt;/li&gt;
&lt;li&gt;The boolean return value is not the fill result. True means the request passed basic checks and was sent.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  A pattern that covers the gaps
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nc"&gt;OpenBuy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CTrade&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;trade&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="n"&gt;lots&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="n"&gt;sl&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="n"&gt;tp&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="n"&gt;lots&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;NormalizeLots&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_Symbol&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;lots&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;           &lt;span class="c1"&gt;// your own step rounding&lt;/span&gt;
   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lots&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;trade&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Buy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lots&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_Symbol&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sl&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tp&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nc"&gt;PrintFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Buy send failed: %u %s"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ResultRetcode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ResultRetcodeDescription&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="n"&gt;uint&lt;/span&gt; &lt;span class="n"&gt;rc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;trade&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ResultRetcode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rc&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_DONE&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;rc&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_PLACED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nc"&gt;PrintFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Buy not filled: %u %s"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rc&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;trade&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ResultRetcodeDescription&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Takeaway
&lt;/h2&gt;

&lt;p&gt;Use CTrade for the request plumbing, but keep lot normalization, stop level checks, retry rules and retcode checks in your own code. Those four gaps cause most of the "it worked in the tester" support tickets.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>metatrader</category>
      <category>algotrading</category>
    </item>
    <item>
      <title>Stop your MQL5 EA from firing orders into a closed market</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Mon, 16 Nov 2026 06:24:18 +0000</pubDate>
      <link>https://dev.to/omaisali/stop-your-mql5-ea-from-firing-orders-into-a-closed-market-bc5</link>
      <guid>https://dev.to/omaisali/stop-your-mql5-ea-from-firing-orders-into-a-closed-market-bc5</guid>
      <description>&lt;p&gt;If your EA has ever filled its log with retcode 10018 (TRADE_RETCODE_MARKET_CLOSED), you know the pattern. A signal appears during the daily break, on a holiday, or a few seconds before the weekend close, and the EA tries again on every tick. Nothing is lost on that request, but retry logic, counters and alerts all get confused, and on a busy account it can look like the EA is broken.&lt;/p&gt;

&lt;p&gt;MT5 already knows the trading sessions for each symbol. You only have to ask.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reading the trade sessions
&lt;/h2&gt;

&lt;p&gt;SymbolInfoSessionTrade returns the start and end of each trading session for a given weekday. The times come back as seconds from midnight in server time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nc"&gt;IsInTradeSession&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;symbol&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="n"&gt;serverNow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TimeTradeServer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="nc"&gt;MqlDateTime&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="nc"&gt;TimeToStruct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;serverNow&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="no"&gt;ENUM_DAY_OF_WEEK&lt;/span&gt; &lt;span class="n"&gt;day&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;ENUM_DAY_OF_WEEK&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;day_of_week&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;secondsNow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;serverNow&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;86400&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// seconds since midnight&lt;/span&gt;

   &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;uint&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nc"&gt;SymbolInfoSessionTrade&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;symbol&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;day&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;          &lt;span class="c1"&gt;// 24:00 comes back as 86400&lt;/span&gt;
      &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;secondsNow&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;secondsNow&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
         &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A symbol can have several sessions per day, which is why the loop keeps asking for the next index until the call returns false.&lt;/p&gt;

&lt;h2&gt;
  
  
  Check the trade mode too
&lt;/h2&gt;

&lt;p&gt;Sessions say when the market is open. They do not say whether you are allowed to open a position. Check SYMBOL_TRADE_MODE as well:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nc"&gt;CanOpen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;symbol&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;mode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SymbolInfoInteger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;symbol&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;SYMBOL_TRADE_MODE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mode&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="no"&gt;SYMBOL_TRADE_MODE_DISABLED&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;mode&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="no"&gt;SYMBOL_TRADE_MODE_CLOSEONLY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nc"&gt;TerminalInfoInteger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;TERMINAL_CONNECTED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;IsInTradeSession&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;symbol&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Close only mode shows up more often than people expect, for example on expiring contracts or symbols a broker is retiring.&lt;/p&gt;

&lt;h2&gt;
  
  
  Leave a margin near the edges
&lt;/h2&gt;

&lt;p&gt;Quotes often stop a little before the session officially ends, and the first seconds after the open can have wide spreads. A simple rule is to refuse new entries in the last five minutes before a session end and the first two minutes after a start. Exits should still be allowed whenever the market accepts them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Still handle 10018
&lt;/h2&gt;

&lt;p&gt;The session table comes from the broker and holidays are not always reflected in it. So keep a handler for TRADE_RETCODE_MARKET_CLOSED anyway: do not retry on every tick, pause new entries for that symbol for a few minutes, and write one log line instead of hundreds.&lt;/p&gt;

&lt;h2&gt;
  
  
  Test note
&lt;/h2&gt;

&lt;p&gt;The strategy tester uses the session settings of the symbol, so you can confirm the filter by running a week that includes a holiday and checking that no orders are attempted while the market is shut.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>metatrader</category>
      <category>algotrading</category>
    </item>
    <item>
      <title>Which MQL5 OrderSend failures are safe to retry, and which are not</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Sun, 15 Nov 2026 06:27:45 +0000</pubDate>
      <link>https://dev.to/omaisali/which-mql5-ordersend-failures-are-safe-to-retry-and-which-are-not-1mon</link>
      <guid>https://dev.to/omaisali/which-mql5-ordersend-failures-are-safe-to-retry-and-which-are-not-1mon</guid>
      <description>&lt;p&gt;A lot of Expert Advisors handle a failed OrderSend in one of two bad ways. Either they give up on the first error and miss the trade, or they retry everything in a loop and turn a "not enough money" error into fifty log lines and a frozen chart.&lt;/p&gt;

&lt;p&gt;The trade server tells you which case you are in through result.retcode. Here is how I sort them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Retry with a fresh price
&lt;/h2&gt;

&lt;p&gt;These mean the market moved or the quote went stale between your calculation and the server receiving the request. Refresh the price and try again, a small number of times.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;TRADE_RETCODE_REQUOTE (10004)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_PRICE_CHANGED (10020)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_PRICE_OFF (10021)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Retry after a short wait
&lt;/h2&gt;

&lt;p&gt;These are about the connection or the server being busy, not your request.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;TRADE_RETCODE_TIMEOUT (10012), but check first whether the order actually went through&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_CONNECTION (10031)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_TOO_MANY_REQUESTS (10024)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Never retry blindly
&lt;/h2&gt;

&lt;p&gt;These mean the request itself is wrong or the account cannot take it. Retrying sends the same bad request again.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;TRADE_RETCODE_INVALID_VOLUME (10014)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_INVALID_STOPS (10016)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_NO_MONEY (10019)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_MARKET_CLOSED (10018)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_TRADE_DISABLED (10017)&lt;/li&gt;
&lt;li&gt;TRADE_RETCODE_INVALID_FILL (10030)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Log them clearly and stop for this signal.&lt;/p&gt;

&lt;h2&gt;
  
  
  Putting it together
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nc"&gt;SendWithRetry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MqlTradeRequest&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;MqlTradeResult&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;maxTries&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;maxTries&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
   &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;action&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="no"&gt;TRADE_ACTION_DEAL&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
         &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;type&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="no"&gt;ORDER_TYPE_BUY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                     &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nc"&gt;SymbolInfoDouble&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;symbol&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;SYMBOL_ASK&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                     &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;SymbolInfoDouble&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;symbol&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;SYMBOL_BID&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

      &lt;span class="nc"&gt;ZeroMemory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;sent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;OrderSend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

      &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sent&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retcode&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_DONE&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt;
                  &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retcode&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_PLACED&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt;
                  &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retcode&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_DONE_PARTIAL&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
         &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

      &lt;span class="k"&gt;switch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retcode&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="p"&gt;{&lt;/span&gt;
         &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_REQUOTE&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
         &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_PRICE_CHANGED&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
         &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_PRICE_OFF&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                       &lt;span class="c1"&gt;// fresh price on next loop&lt;/span&gt;
         &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_CONNECTION&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
         &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="no"&gt;TRADE_RETCODE_TOO_MANY_REQUESTS&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nc"&gt;Sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nc"&gt;PrintFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"OrderSend stopped: retcode %u %s"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                        &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retcode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;comment&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                   &lt;span class="c1"&gt;// do not retry&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
   &lt;span class="nc"&gt;PrintFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"OrderSend gave up after %d tries, last retcode %u"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
               &lt;span class="n"&gt;maxTries&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retcode&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A few notes on this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Keep maxTries small. Three is plenty. If the market is moving that fast, your signal price is already wrong.&lt;/li&gt;
&lt;li&gt;Timeout is deliberately not retried here. After a timeout, look at open positions and recent deals for your magic number before sending again, or you can end up with two positions.&lt;/li&gt;
&lt;li&gt;Do not call Sleep inside the Strategy Tester loop if you can avoid it. It slows testing and does nothing useful there.&lt;/li&gt;
&lt;li&gt;Log the retcode as a number and the comment. The comment from the server often explains things the enum name does not.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Sorting failures this way makes an EA both more persistent when it should be and quieter when it should give up.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>metatrader</category>
    </item>
    <item>
      <title>A daily log file for your MQL5 EA that you can actually read after a bad day</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Sat, 14 Nov 2026 06:23:36 +0000</pubDate>
      <link>https://dev.to/omaisali/a-daily-log-file-for-your-mql5-ea-that-you-can-actually-read-after-a-bad-day-388</link>
      <guid>https://dev.to/omaisali/a-daily-log-file-for-your-mql5-ea-that-you-can-actually-read-after-a-bad-day-388</guid>
      <description>&lt;p&gt;When an Expert Advisor does something strange at 3 am, the Experts tab is rarely enough. It mixes every EA on the terminal, it is cleared on restart, and the journal files are hard to filter. A small log of your own, one file per day per EA instance, makes post mortems much faster.&lt;/p&gt;

&lt;h2&gt;
  
  
  What to log
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Every input value at OnInit, so you know exactly which settings were running.&lt;/li&gt;
&lt;li&gt;Every trade request you send and the full result: retcode, deal ticket, price, volume and the comment from the server.&lt;/li&gt;
&lt;li&gt;Every signal you skipped, with the reason, for example spread too wide or daily loss limit reached.&lt;/li&gt;
&lt;li&gt;Every error from functions such as CopyBuffer or OrderCalcMargin.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The skipped signals are the most useful part. Most questions after a quiet day are "why did it not trade", and the answer is sitting in that file.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;input long InpMagic = 260514;

int    g_log     = INVALID_HANDLE;
string g_logDate = "";

void LogLine(const string text)
{
   string day = TimeToString(TimeCurrent(), TIME_DATE);
   if(day != g_logDate)
   {
      if(g_log != INVALID_HANDLE)
         FileClose(g_log);
      StringReplace(day, ".", "");
      string name = "ea_logs\\" + _Symbol + "_" + IntegerToString(InpMagic) + "_" + day + ".log";
      g_log = FileOpen(name, FILE_READ|FILE_WRITE|FILE_TXT|FILE_ANSI|FILE_SHARE_READ);
      if(g_log == INVALID_HANDLE)
      {
         Print("log open failed, error ", GetLastError());
         return;
      }
      FileSeek(g_log, 0, SEEK_END);
      g_logDate = TimeToString(TimeCurrent(), TIME_DATE);
   }
   string stamp = TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS);
   FileWriteString(g_log, stamp + " " + text + "\r\n");
   FileFlush(g_log);
}

void OnDeinit(const int reason)
{
   LogLine("deinit reason " + IntegerToString(reason));
   if(g_log != INVALID_HANDLE)
      FileClose(g_log);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A few details worth knowing:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;FILE_READ together with FILE_WRITE opens an existing file without truncating it, and FileSeek to SEEK_END appends. Without that, a restart in the middle of the day would wipe the morning.&lt;/li&gt;
&lt;li&gt;FILE_SHARE_READ lets you open the file in a text viewer while the EA is still running.&lt;/li&gt;
&lt;li&gt;The file name includes the symbol and magic number, so two instances on different charts never write to the same file.&lt;/li&gt;
&lt;li&gt;Files land in MQL5\Files\ea_logs of the terminal data folder. In the Strategy Tester they go to the tester agent folder instead, which is handy because test logs never mix with live ones.&lt;/li&gt;
&lt;li&gt;FileFlush on every line costs a little disk activity. For an EA that logs a few lines per bar that is nothing, and it means the last line is on disk even if the terminal crashes.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Logging a trade result
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MqlTradeRequest req = {};
MqlTradeResult  res = {};
// fill req here
bool sent = OrderSend(req, res);
LogLine(StringFormat("send type=%d vol=%.2f price=%.5f sent=%d retcode=%u deal=%I64u comment=%s",
        req.type, req.volume, req.price, sent, res.retcode, res.deal, res.comment));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep the format boring and consistent, one event per line. Then a quick search for retcode or skip tells you the story of the day in seconds.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>algotrading</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>PositionSelect is lying to your MQL5 EA on a hedging account</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Fri, 13 Nov 2026 06:25:26 +0000</pubDate>
      <link>https://dev.to/omaisali/positionselect-is-lying-to-your-mql5-ea-on-a-hedging-account-425o</link>
      <guid>https://dev.to/omaisali/positionselect-is-lying-to-your-mql5-ea-on-a-hedging-account-425o</guid>
      <description>&lt;p&gt;A lot of MQL5 code found online was written for netting accounts, where there is at most one position per symbol. Run the same EA on a hedging account, which is what most retail forex brokers give you, and some functions start returning answers that look right but are not.&lt;/p&gt;

&lt;h2&gt;
  
  
  The trap
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(PositionSelect(_Symbol))
{
   double vol = PositionGetDouble(POSITION_VOLUME);
   // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On a netting account this selects the single position on the symbol. On a hedging account there can be several positions on the same symbol, from this EA, from another EA, or opened by hand. PositionSelect then picks one of them, and the documentation does not promise which. Your EA may read the volume, profit or stop loss of a position it never opened.&lt;/p&gt;

&lt;h2&gt;
  
  
  Check the account mode first
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bool IsHedging()
{
   return (ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE)
          == ACCOUNT_MARGIN_MODE_RETAIL_HEDGING;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Log it in OnInit so you always know which world the EA is running in.&lt;/p&gt;

&lt;h2&gt;
  
  
  Loop by ticket and filter by magic number
&lt;/h2&gt;

&lt;p&gt;The pattern that works on both account types is to walk every open position and keep only the ones that belong to this EA:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;input long InpMagic = 260113;

int CollectMyPositions(ulong &amp;amp;tickets[])
{
   ArrayResize(tickets, 0);
   int total = PositionsTotal();
   for(int i = total - 1; i &amp;gt;= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);   // also selects it
      if(ticket == 0) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      if(PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
      int n = ArraySize(tickets);
      ArrayResize(tickets, n + 1);
      tickets[n] = ticket;
   }
   return ArraySize(tickets);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then work with PositionSelectByTicket(ticket) whenever you need a specific one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Closing and modifying
&lt;/h2&gt;

&lt;p&gt;On a hedging account a close request must name the position:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MqlTradeRequest req = {};
MqlTradeResult  res = {};
req.action   = TRADE_ACTION_DEAL;
req.position = ticket;               // without this a new opposite position opens
req.symbol   = _Symbol;
req.volume   = PositionGetDouble(POSITION_VOLUME);
req.type     = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
               ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
req.price    = (req.type == ORDER_TYPE_SELL)
               ? SymbolInfoDouble(_Symbol, SYMBOL_BID)
               : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
req.deviation = 20;
req.magic    = InpMagic;
if(!OrderSend(req, res))
   PrintFormat("close %I64u failed, retcode %u", ticket, res.retcode);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you leave req.position empty on a hedging account, the broker treats the sell as a brand new short. You end up hedged instead of flat, with double the swap and margin. The CTrade class does this for you with PositionClose(ticket), which is one more reason to prefer it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Net exposure is your job now
&lt;/h2&gt;

&lt;p&gt;On netting accounts the terminal nets buys and sells for you. On hedging accounts your EA must add up its own long and short volume if it has a maximum exposure rule. Sum the volume from CollectMyPositions with a sign per position type and compare that with the limit before every new entry.&lt;/p&gt;

&lt;h2&gt;
  
  
  Checklist
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Log the margin mode in OnInit.&lt;/li&gt;
&lt;li&gt;Never rely on PositionSelect(symbol) when the account can hold more than one position.&lt;/li&gt;
&lt;li&gt;Filter every loop by symbol and magic number.&lt;/li&gt;
&lt;li&gt;Always pass the position ticket when closing or modifying.&lt;/li&gt;
&lt;li&gt;Compute net exposure yourself.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These five lines prevent most of the "my EA closed the wrong trade" reports I see.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>metatrader</category>
      <category>algotrading</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>A heartbeat file for an MQL5 EA so you know it is still alive</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Thu, 12 Nov 2026 06:24:28 +0000</pubDate>
      <link>https://dev.to/omaisali/a-heartbeat-file-for-an-mql5-ea-so-you-know-it-is-still-alive-59l6</link>
      <guid>https://dev.to/omaisali/a-heartbeat-file-for-an-mql5-ea-so-you-know-it-is-still-alive-59l6</guid>
      <description>&lt;p&gt;An EA that has stopped working usually looks exactly like an EA that is waiting for a signal. No trades, no errors in front of you, just a quiet chart. The terminal may have lost its connection, the VPS may have restarted, AutoTrading may have been switched off, or the EA may have been removed by a profile change. You find out days later.&lt;/p&gt;

&lt;p&gt;A heartbeat file fixes that. Every minute the EA writes the current time and a few status values to a small file. Anything outside the terminal (a script, a cron job, a monitoring tool) reads the file and raises an alarm when the timestamp gets old.&lt;/p&gt;

&lt;h2&gt;
  
  
  What to write
&lt;/h2&gt;

&lt;p&gt;Keep it to one line so the reader never has to parse much:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Local time of the write, as a Unix timestamp.&lt;/li&gt;
&lt;li&gt;Whether the terminal is connected to the trade server.&lt;/li&gt;
&lt;li&gt;Whether trading is allowed for the terminal and for this EA.&lt;/li&gt;
&lt;li&gt;Account equity.&lt;/li&gt;
&lt;li&gt;Number of open positions with this EA's magic number.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The code
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;input long InpMagic = 20261112;

int OnInit()
{
   if(!EventSetTimer(60))
   {
      Print("EventSetTimer failed: ", GetLastError());
      return INIT_FAILED;
   }
   WriteHeartbeat();
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   EventKillTimer();
   WriteHeartbeat(reason);
}

void OnTimer()
{
   WriteHeartbeat();
}

int CountMyPositions()
{
   int n = 0;
   for(int i = PositionsTotal() - 1; i &amp;gt;= 0; i--)
   {
      if(PositionGetTicket(i) == 0) continue;
      if(PositionGetInteger(POSITION_MAGIC) == InpMagic) n++;
   }
   return n;
}

void WriteHeartbeat(const int deinitReason = -1)
{
   string name = "heartbeat_" + _Symbol + "_" + (string)InpMagic + ".txt";
   int h = FileOpen(name, FILE_WRITE | FILE_TXT | FILE_COMMON | FILE_ANSI);
   if(h == INVALID_HANDLE)
   {
      Print("Heartbeat open failed: ", GetLastError());
      return;
   }
   string line = StringFormat("%I64d;%d;%d;%d;%.2f;%d;%d",
      (long)TimeLocal(),
      (int)TerminalInfoInteger(TERMINAL_CONNECTED),
      (int)TerminalInfoInteger(TERMINAL_TRADE_ALLOWED),
      (int)MQLInfoInteger(MQL_TRADE_ALLOWED),
      AccountInfoDouble(ACCOUNT_EQUITY),
      CountMyPositions(),
      deinitReason);
   FileWriteString(h, line + "\r\n");
   FileClose(h);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A few details that matter:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;FILE_COMMON puts the file in the shared Common\Files folder, so the path does not depend on which terminal instance is running. That makes the external checker simpler.&lt;/li&gt;
&lt;li&gt;The file is opened with FILE_WRITE each time, which truncates it. There is always exactly one current line, not a growing log.&lt;/li&gt;
&lt;li&gt;FileClose flushes the write. Without closing (or FileFlush) the line can sit in a buffer.&lt;/li&gt;
&lt;li&gt;The deinit reason is written on the way out. If the last line shows reason 1 (REASON_REMOVE), someone removed the EA. A stale file with reason -1 means the terminal itself stopped.&lt;/li&gt;
&lt;li&gt;TimeLocal is used on purpose. TimeCurrent only moves when quotes arrive, so on a quiet market or a weekend it stands still and the heartbeat would look stale for the wrong reason.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The checker
&lt;/h2&gt;

&lt;p&gt;The reader only needs to compare the timestamp with the clock. In Python:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt;

&lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="s2"&gt;"C:\Users\YOU\AppData\Roaming\MetaQuotes\Terminal\Common\Files\heartbeat_EURUSD_20261112.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;fields&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;split&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;";"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;connected&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;terminal_ok&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ea_ok&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;age&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;180&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"ALERT: heartbeat is"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;age&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"seconds old"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;connected&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"1"&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;terminal_ok&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"1"&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;ea_ok&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"1"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"ALERT: EA alive but cannot trade"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"OK"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that TimeLocal and Python's time.time both come from the same machine clock when the checker runs on the same VPS, so there is no time zone math. Run the checker on another machine and you will need to account for the clock offset.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three minutes is a good threshold
&lt;/h2&gt;

&lt;p&gt;With a 60 second timer, allow at least two missed writes before alarming. A timer event is not queued if one is already waiting, so a slow OnTimer can skip a beat now and then. Alerting on one missed beat produces false alarms, and false alarms get ignored.&lt;/p&gt;

&lt;p&gt;The heartbeat does not tell you the strategy is good. It tells you the strategy is actually running, which is the question you want answered first.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>algotrading</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>A daily loss guard for an MQL5 EA that counts closed deals and open equity</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Wed, 11 Nov 2026 06:29:07 +0000</pubDate>
      <link>https://dev.to/omaisali/a-daily-loss-guard-for-an-mql5-ea-that-counts-closed-deals-and-open-equity-pan</link>
      <guid>https://dev.to/omaisali/a-daily-loss-guard-for-an-mql5-ea-that-counts-closed-deals-and-open-equity-pan</guid>
      <description>&lt;p&gt;Most EAs that blow an account do it in one bad day, not over a month. A daily loss guard is the simplest protection against that, and it is also what most prop firm rules require. The tricky part is measuring the day's loss correctly. Two common mistakes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Comparing current balance with yesterday's balance. That ignores open trades, so the EA can sit on a large floating loss and keep opening new positions.&lt;/li&gt;
&lt;li&gt;Using the PC clock for the start of the day. The trading day follows the broker server time, which is often two or three hours away from yours.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The approach below records the equity at the start of each server day and blocks new entries once equity falls a set percentage below it. It can also close everything when the limit is hit.&lt;/p&gt;

&lt;h2&gt;
  
  
  Inputs and state
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;input double InpMaxDailyLossPct = 3.0;   // max loss per day, percent of start equity
input bool   InpCloseOnLimit    = true;  // close open positions when hit
input long   InpMagic           = 12345; // this EA's magic number

double   g_dayStartEquity = 0.0;
datetime g_dayStart       = 0;
bool     g_blockedToday   = false;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Detecting the new server day
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;datetime ServerDayStart()
{
   MqlDateTime t;
   TimeToStruct(TimeTradeServer(), t);
   t.hour = 0; t.min = 0; t.sec = 0;
   return StructToTime(t);
}

void UpdateDay()
{
   datetime d = ServerDayStart();
   if(d != g_dayStart)
   {
      g_dayStart       = d;
      g_dayStartEquity = AccountInfoDouble(ACCOUNT_EQUITY);
      g_blockedToday   = false;
      PrintFormat("New server day %s, start equity %.2f",
                  TimeToString(d, TIME_DATE), g_dayStartEquity);
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Taking a snapshot of equity rather than balance means a trade carried overnight is counted from where it stood at midnight, which is what most prop firm rules do.&lt;/p&gt;

&lt;h2&gt;
  
  
  The check
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bool DailyLossHit()
{
   if(g_blockedToday) return true;
   double eq    = AccountInfoDouble(ACCOUNT_EQUITY);
   double limit = g_dayStartEquity * (1.0 - InpMaxDailyLossPct / 100.0);
   if(eq &amp;lt;= limit)
   {
      g_blockedToday = true;
      PrintFormat("Daily loss limit hit: equity %.2f, limit %.2f", eq, limit);
      if(InpCloseOnLimit) CloseAllMine();
      return true;
   }
   return false;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;CloseAllMine&lt;/code&gt; is whatever routine your EA already uses to close its own positions, filtered by magic number and symbol.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using it in OnTick
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void OnTick()
{
   UpdateDay();
   if(DailyLossHit()) return;   // no new entries today

   // normal signal and entry logic below
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the check before the signal logic so a blocked day never reaches OrderSend.&lt;/p&gt;

&lt;h2&gt;
  
  
  Surviving a restart
&lt;/h2&gt;

&lt;p&gt;If the terminal restarts in the middle of the day, &lt;code&gt;g_dayStartEquity&lt;/code&gt; resets to the current equity and the EA forgets the morning's losses. Save the two values in terminal global variables so a restart picks them up:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void SaveDay()
{
   GlobalVariableSet("DLG_start_" + (string)InpMagic, (double)g_dayStart);
   GlobalVariableSet("DLG_eq_"    + (string)InpMagic, g_dayStartEquity);
}

void LoadDay()
{
   string k1 = "DLG_start_" + (string)InpMagic;
   string k2 = "DLG_eq_"    + (string)InpMagic;
   if(GlobalVariableCheck(k1) &amp;amp;&amp;amp; (datetime)GlobalVariableGet(k1) == ServerDayStart())
   {
      g_dayStart       = (datetime)GlobalVariableGet(k1);
      g_dayStartEquity = GlobalVariableGet(k2);
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Call &lt;code&gt;LoadDay()&lt;/code&gt; in OnInit and &lt;code&gt;SaveDay()&lt;/code&gt; whenever a new day starts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Things to test
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Run the Strategy Tester over a period that includes a sharp drop and confirm the log shows the limit line and no entries after it.&lt;/li&gt;
&lt;li&gt;Test with a position held over midnight and check the start equity includes its floating result.&lt;/li&gt;
&lt;li&gt;Restart the terminal halfway through a losing day and check the EA still remembers the start equity.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A guard like this will not make a strategy profitable, but it caps how much one broken day can cost.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>algotrading</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Parsing a TradingView alert message in MQL5 so a bad alert never becomes a trade</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Tue, 10 Nov 2026 06:28:15 +0000</pubDate>
      <link>https://dev.to/omaisali/parsing-a-tradingview-alert-message-in-mql5-so-a-bad-alert-never-becomes-a-trade-43k2</link>
      <guid>https://dev.to/omaisali/parsing-a-tradingview-alert-message-in-mql5-so-a-bad-alert-never-becomes-a-trade-43k2</guid>
      <description>&lt;p&gt;A TradingView to MT5 bridge has two halves. One half gets the alert from TradingView to the terminal, usually a webhook to a small server that the EA polls. The other half decides what the alert means. Most bridge failures I see are in the second half: a typo in the message template, a symbol that does not exist on the broker, a missing stop loss, or the same alert delivered twice. Each of those can turn into a wrong trade if the EA trusts the text.&lt;/p&gt;

&lt;p&gt;This post shows a small parser and validator for a plain key and value message. It does not cover the transport, only what happens once the EA has the string.&lt;/p&gt;

&lt;h1&gt;
  
  
  The message format
&lt;/h1&gt;

&lt;p&gt;Keep the format simple enough to read in a log. In the TradingView alert message box:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;id={{ticker}}_{{timenow}};action={{strategy.order.action}};symbol={{ticker}};risk=0.5;sl={{plot_0}}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which gives a message like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;id=EURUSD_2026-11-10T06:00:00Z;action=buy;symbol=EURUSD;risk=0.5;sl=1.0820
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fields are separated by semicolons and each field is a key, an equals sign and a value. The id must be unique per alert, which is why it combines the ticker and the alert time.&lt;/p&gt;

&lt;h1&gt;
  
  
  Parsing
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;input string SymbolSuffix = "";    // broker suffix, for example ".m"
input double MaxRiskPct   = 1.0;   // reject alerts asking for more

struct Signal
{
   string id;
   string action;    // buy, sell or close
   string symbol;
   double riskPct;
   double slPrice;
};

string g_lastId = "";

string Trimmed(string s)
{
   StringTrimLeft(s);
   StringTrimRight(s);
   return s;
}

bool ParseSignal(const string msg, Signal &amp;amp;s, string &amp;amp;reason)
{
   s.id = ""; s.action = ""; s.symbol = ""; s.riskPct = 0.0; s.slPrice = 0.0;

   string parts[];
   int n = StringSplit(Trimmed(msg), ';', parts);
   if(n &amp;lt; 2)
   {
      reason = "not a key=value message";
      return false;
   }
   for(int i = 0; i &amp;lt; n; i++)
   {
      if(Trimmed(parts[i]) == "")
         continue;                       // tolerate a trailing semicolon
      string kv[];
      if(StringSplit(parts[i], '=', kv) != 2)
      {
         reason = "bad field '" + parts[i] + "'";
         return false;
      }
      string key = Trimmed(kv[0]);
      string val = Trimmed(kv[1]);
      StringToLower(key);

      if(key == "id")
         s.id = val;
      else if(key == "action")
      {
         StringToLower(val);
         s.action = val;
      }
      else if(key == "symbol")
         s.symbol = val;
      else if(key == "risk")
         s.riskPct = StringToDouble(val);
      else if(key == "sl")
         s.slPrice = StringToDouble(val);
      else
         PrintFormat("Ignoring unknown key '%s'", key);
   }
   return true;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that StringToDouble returns 0 for text it cannot read. That is why the validator below treats zero risk and a zero stop as errors instead of defaults.&lt;/p&gt;

&lt;h1&gt;
  
  
  Mapping the symbol
&lt;/h1&gt;

&lt;p&gt;TradingView tickers and broker symbols rarely match exactly. Some alerts include an exchange prefix such as FX:EURUSD, and many brokers add a suffix.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;string MapSymbol(string tv)
{
   int colon = StringFind(tv, ":");
   if(colon &amp;gt;= 0)
      tv = StringSubstr(tv, colon + 1);
   StringToUpper(tv);
   return tv + SymbolSuffix;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If a broker uses completely different names, such as GOLD for XAUUSD, replace this with a small lookup table loaded from inputs or a file.&lt;/p&gt;

&lt;h1&gt;
  
  
  Validating
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bool ValidateSignal(Signal &amp;amp;s, string &amp;amp;reason)
{
   if(s.id == "")
   {
      reason = "missing id";
      return false;
   }
   if(s.id == g_lastId)
   {
      reason = "duplicate id";
      return false;
   }
   if(s.action != "buy" &amp;amp;&amp;amp; s.action != "sell" &amp;amp;&amp;amp; s.action != "close")
   {
      reason = "unknown action '" + s.action + "'";
      return false;
   }

   string sym = MapSymbol(s.symbol);
   if(s.symbol == "" || !SymbolSelect(sym, true))
   {
      reason = "unknown symbol '" + s.symbol + "' mapped to '" + sym + "'";
      return false;
   }
   s.symbol = sym;

   if(s.action == "close")
      return true;

   if(s.riskPct &amp;lt;= 0.0 || s.riskPct &amp;gt; MaxRiskPct)
   {
      reason = StringFormat("risk %.2f outside 0 to %.2f", s.riskPct, MaxRiskPct);
      return false;
   }
   if(s.slPrice &amp;lt;= 0.0)
   {
      reason = "missing or unreadable stop loss";
      return false;
   }
   double bid = SymbolInfoDouble(sym, SYMBOL_BID);
   double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
   if(s.action == "buy" &amp;amp;&amp;amp; s.slPrice &amp;gt;= bid)
   {
      reason = "buy stop loss is not below price";
      return false;
   }
   if(s.action == "sell" &amp;amp;&amp;amp; s.slPrice &amp;lt;= ask)
   {
      reason = "sell stop loss is not above price";
      return false;
   }
   return true;
}

void HandleAlert(const string msg)
{
   Signal s;
   string reason = "";
   if(!ParseSignal(msg, s, reason) || !ValidateSignal(s, reason))
   {
      PrintFormat("Alert rejected (%s): %s", reason, msg);
      return;
   }
   g_lastId = s.id;
   int digits = (int)SymbolInfoInteger(s.symbol, SYMBOL_DIGITS);
   PrintFormat("Alert accepted: %s %s risk %.2f%% sl %s",
               s.action, s.symbol, s.riskPct, DoubleToString(s.slPrice, digits));
   // pass s to the order code from here
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every rejection prints the reason and the raw message, so a broken template shows up in the Experts tab the first time it fires instead of after a week of missed trades.&lt;/p&gt;

&lt;h1&gt;
  
  
  Practical points
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Remember more than one id. Webhook retries can deliver an older alert after a newer one, so keep the last few dozen ids in an array, and save them to a file so a restart does not forget them.&lt;/li&gt;
&lt;li&gt;Reject stale alerts. Have the server stamp each alert with the time it arrived and let the EA drop anything older than a set number of seconds. An entry signal from ten minutes ago is not the same signal.&lt;/li&gt;
&lt;li&gt;Never put account numbers, passwords or API keys in the alert text. The message passes through TradingView and your server logs.&lt;/li&gt;
&lt;li&gt;Test the parser with a script before connecting it to real orders. Feed it a list of good and deliberately broken messages and check that each broken one is rejected with a clear reason.&lt;/li&gt;
&lt;li&gt;Keep the stop loss in the alert even if the EA also computes one. Comparing the two is a cheap check that the chart and the terminal agree on price.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A parser like this is not glamorous, but it is the part of the bridge that decides whether a typo becomes a log line or a position.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>tradingview</category>
      <category>algotrading</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Measuring the real spread by hour of day with CopyTicks in MQL5</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Mon, 09 Nov 2026 06:42:50 +0000</pubDate>
      <link>https://dev.to/omaisali/measuring-the-real-spread-by-hour-of-day-with-copyticks-in-mql5-5big</link>
      <guid>https://dev.to/omaisali/measuring-the-real-spread-by-hour-of-day-with-copyticks-in-mql5-5big</guid>
      <description>&lt;p&gt;A spread filter needs a threshold, and most people guess it. The Market Watch spread you see while writing code is the daytime spread. The spread at rollover, before major news, or in the thin hour after the US close can be several times wider. A short script that reads the tick history and groups the spread by hour of day gives you real numbers to put into the filter and into the tester settings.&lt;/p&gt;

&lt;h1&gt;
  
  
  What the script does
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Reads the most recent bid and ask changes with CopyTicks and COPY_TICKS_INFO. Passing 0 as the start time asks for the latest ticks, so no date math is needed.&lt;/li&gt;
&lt;li&gt;Converts each tick's spread to points.&lt;/li&gt;
&lt;li&gt;Groups the ticks by hour in broker server time and prints the tick count, average spread and maximum spread for each hour.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  The script
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#property script_show_inputs

input int MaxTicks = 1000000;   // most recent ticks to read

void OnStart()
{
   MqlTick ticks[];
   // from = 0 means "the most recent MaxTicks ticks"
   int n = CopyTicks(_Symbol, ticks, COPY_TICKS_INFO, 0, MaxTicks);
   if(n &amp;lt;= 0)
   {
      Print("CopyTicks returned ", n, ", error ", GetLastError(), ". Tick history may still be downloading.");
      return;
   }

   double sum[24];
   double mx[24];
   int    cnt[24];
   ArrayInitialize(sum, 0.0);
   ArrayInitialize(mx, 0.0);
   ArrayInitialize(cnt, 0);

   MqlDateTime dt;
   for(int i = 0; i &amp;lt; n; i++)
   {
      if(ticks[i].bid &amp;lt;= 0.0 || ticks[i].ask &amp;lt;= 0.0)
         continue;
      double pts = (ticks[i].ask - ticks[i].bid) / _Point;
      TimeToStruct(ticks[i].time, dt);
      sum[dt.hour] += pts;
      cnt[dt.hour]++;
      if(pts &amp;gt; mx[dt.hour])
         mx[dt.hour] = pts;
   }

   PrintFormat("%s spread by server hour, %d ticks from %s to %s", _Symbol, n, TimeToString(ticks[0].time), TimeToString(ticks[n - 1].time));
   for(int h = 0; h &amp;lt; 24; h++)
   {
      if(cnt[h] == 0)
         continue;
      PrintFormat("hour %02d  ticks %7d  avg %6.1f  max %6.1f points", h, cnt[h], sum[h] / cnt[h], mx[h]);
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run it on the chart of the symbol you trade. The output goes to the Experts tab.&lt;/p&gt;

&lt;h1&gt;
  
  
  Reading the output
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;The average shows the normal cost of trading in that hour. If it is far above your strategy's average profit per trade, that hour is a cost center, whatever the signal says.&lt;/li&gt;
&lt;li&gt;The maximum shows the spikes your filter must survive. A spike at the daily rollover is normal on most brokers. Spikes elsewhere often line up with news.&lt;/li&gt;
&lt;li&gt;Hours with very few ticks are thin markets. Fills there are worse than the spread alone suggests.&lt;/li&gt;
&lt;li&gt;Hours are in server time. If the broker shifts its server clock for daylight saving, run the script again after the change, because the rollover hour moves.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Practical points
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Check the time range printed in the first line. On a busy symbol a million ticks may cover only a day or two; on a quiet one it can cover weeks. You want at least a full week so every hour appears several times.&lt;/li&gt;
&lt;li&gt;Tick history is downloaded on demand. The first call can return fewer ticks or an error; running the script a second time usually fixes it.&lt;/li&gt;
&lt;li&gt;Start with a modest MaxTicks. Very large requests use a lot of memory and take a while to load. If you need a specific date range, CopyTicksRange takes start and end times in milliseconds instead.&lt;/li&gt;
&lt;li&gt;Spread is not the whole cost. Add commission per lot from your account type to get the full round trip.&lt;/li&gt;
&lt;li&gt;Use the numbers twice: as the threshold in the EA's spread filter, and as a check on your backtest. If the test data shows a much tighter spread in your trading hours than the script measured on your live account, the backtest is cheaper than real trading and its results are too optimistic.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Measuring the spread takes a few minutes. Guessing it wrong shows up in every trade.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>algotrading</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Writing an MQL5 trade journal to CSV with FileOpen so every EA fill is on record</title>
      <dc:creator>Omais Ali</dc:creator>
      <pubDate>Sun, 08 Nov 2026 06:28:57 +0000</pubDate>
      <link>https://dev.to/omaisali/writing-an-mql5-trade-journal-to-csv-with-fileopen-so-every-ea-fill-is-on-record-2hch</link>
      <guid>https://dev.to/omaisali/writing-an-mql5-trade-journal-to-csv-with-fileopen-so-every-ea-fill-is-on-record-2hch</guid>
      <description>&lt;p&gt;The Experts log scrolls away, and the terminal history does not record why the EA took a trade. A small CSV journal fixes both. Every time a deal is added, the EA writes one line with the time, symbol, direction, volume, price, profit, and a reason string. You can open the file in a spreadsheet, compare it with the backtest, and answer questions like "why did it buy here" a week later.&lt;/p&gt;

&lt;h1&gt;
  
  
  Where the file goes
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;FileOpen without FILE_COMMON writes to MQL5/Files inside the terminal data folder. In the Strategy Tester that becomes the agent's own sandbox folder, which is deleted or hard to find.&lt;/li&gt;
&lt;li&gt;With FILE_COMMON the file lands in the shared Terminal/Common/Files folder. Every terminal on the machine and the tester agents can reach it, so it is the easiest place for a journal.&lt;/li&gt;
&lt;li&gt;MQL5 cannot write outside these sandboxes. Paths like C:\Logs are refused by design.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  The journal code
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;input string JournalName = "ea_journal.csv";

string g_lastReason = "";

bool JournalWrite(const string &amp;amp;fields[])
{
   int h = FileOpen(JournalName, FILE_READ | FILE_WRITE | FILE_CSV | FILE_COMMON | FILE_SHARE_READ, ',');
   if(h == INVALID_HANDLE)
   {
      Print("Journal open failed, error ", GetLastError());
      return false;
   }

   bool isNew = (FileSize(h) == 0);
   FileSeek(h, 0, SEEK_END);

   if(isNew)
      FileWrite(h, "time", "symbol", "type", "volume", "price", "profit", "magic", "reason");

   FileWrite(h, fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], fields[7]);
   FileClose(h);
   return true;
}

void OnTradeTransaction(const MqlTradeTransaction &amp;amp;trans,
                        const MqlTradeRequest &amp;amp;request,
                        const MqlTradeResult &amp;amp;result)
{
   if(trans.type != TRADE_TRANSACTION_DEAL_ADD)
      return;
   if(!HistoryDealSelect(trans.deal))
      return;

   string fields[8];
   fields[0] = TimeToString((datetime)HistoryDealGetInteger(trans.deal, DEAL_TIME), TIME_DATE | TIME_SECONDS);
   fields[1] = HistoryDealGetString(trans.deal, DEAL_SYMBOL);
   fields[2] = (HistoryDealGetInteger(trans.deal, DEAL_TYPE) == DEAL_TYPE_BUY) ? "buy" : "sell";
   fields[3] = DoubleToString(HistoryDealGetDouble(trans.deal, DEAL_VOLUME), 2);
   fields[4] = DoubleToString(HistoryDealGetDouble(trans.deal, DEAL_PRICE), (int)SymbolInfoInteger(fields[1], SYMBOL_DIGITS));
   fields[5] = DoubleToString(HistoryDealGetDouble(trans.deal, DEAL_PROFIT), 2);
   fields[6] = IntegerToString(HistoryDealGetInteger(trans.deal, DEAL_MAGIC));
   fields[7] = g_lastReason;

   JournalWrite(fields);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before calling OrderSend, set g_lastReason to something short and specific, such as "breakout above 20 bar high" or "time exit after 12 bars". That string is the part the terminal history will never give you.&lt;/p&gt;

&lt;h1&gt;
  
  
  Practical points
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Open, append, and close on each write. Holding the handle open for days risks losing buffered lines if the terminal crashes, and it blocks other programs from reading the file.&lt;/li&gt;
&lt;li&gt;FILE_SHARE_READ lets you open the CSV in a spreadsheet while the EA is still running. Close the spreadsheet before the EA writes, or use a copy, because some editors lock the file.&lt;/li&gt;
&lt;li&gt;Use a comma delimiter and avoid commas inside the reason text, or wrap the reason in quotes yourself.&lt;/li&gt;
&lt;li&gt;Put the symbol and magic number in the file name if several EAs or charts share the Common folder, so two instances never append to the same file at once.&lt;/li&gt;
&lt;li&gt;In the tester, write a different file name per run so optimization passes do not interleave lines.&lt;/li&gt;
&lt;li&gt;Check FileOpen for INVALID_HANDLE and print the error. Error 5004 usually means a wrong path or a file locked by another program.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A journal that records the reason next to each fill turns "the EA did something odd" into a line you can read, sort, and compare with the backtest.&lt;/p&gt;

</description>
      <category>mql5</category>
      <category>programming</category>
      <category>algotrading</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
