<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Angelo Homen, CQF on Medium]]></title>
        <description><![CDATA[Stories by Angelo Homen, CQF on Medium]]></description>
        <link>https://medium.com/@angelohomen?source=rss-9bbd7c8c5876------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xpfE5C4NN7SpsKazJYg9jw.jpeg</url>
            <title>Stories by Angelo Homen, CQF on Medium</title>
            <link>https://medium.com/@angelohomen?source=rss-9bbd7c8c5876------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:38:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@angelohomen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to store your own data and build fancy backtests]]></title>
            <link>https://angelohomen.medium.com/how-to-store-your-own-data-and-build-fancy-backtests-fd7abbfc479a?source=rss-9bbd7c8c5876------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd7abbfc479a</guid>
            <category><![CDATA[algotrading]]></category>
            <category><![CDATA[metatrader]]></category>
            <category><![CDATA[electronic-trading]]></category>
            <category><![CDATA[backtest]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Angelo Homen, CQF]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 16:52:44 GMT</pubDate>
            <atom:updated>2023-04-03T16:52:44.293Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Data is gold.</blockquote><p>On my last article, I’ve discussed some methods of backtesting and choosing the best optimization result to a trading strategy, being as less subjective as possible. I didn’t give any code examples because, like I said, I’m lazy about building backtests — there are a lot of tools that do a great job on it.</p><p>Now, my motivation is to show you an investment! Yes, an investment. But not the traditional ones, this one is <em>gold</em>. I’m talking about having your own intraday data to backtest your strategies. One can think: come on, there are thousands of API’s that distribute market data to their users. Yeah, you’re right. I’ve been using some APIs, and I’ll be honest: there are lots of cons about them. Starting for paying — almost always there is a fee based on the number of requests. You could say: make just 1 historical request and increment on each day. Alright, it is a good argument, but this data has orders book snapshot? I’m pretty sure you thought “no”. Our solution can save book data too, awesome, right?</p><h3>Code</h3><p>I think you’ve already discovered that I’m a big fan of MetaTrader5. My logic is simple: you have a world of possibilities there, that is why I like this platform. You can do literally anything, and that is awesome. Again, you just need to find a broker that distributes it (it must be free), download and use!</p><p>Here I’ve done two code snippets: one using MQL5 and the other using Python (finally, right?).</p><p>Starting with MQL5:</p><pre>//+------------------------------------------------------------------+<br>//|                                                   MemoryTick.mq5 |<br>//|                                          Angelo R. L. Homen, CQF |<br>//|                                             https://www.mql5.com |<br>//+------------------------------------------------------------------+<br>#property copyright &quot;Angelo R. L. Homen, CQF&quot;<br>#property link      &quot;https://www.mql5.com&quot;<br>#property version   &quot;1.00&quot;<br><br>//+------------------------------------------------------------------+<br>//| Global variables                                                 |<br>//+------------------------------------------------------------------+<br>MqlRates last_tick[];<br>int filehandle = INVALID_HANDLE;<br>string symbol;<br>string filename;<br>ulong memory;<br>int columns=1;<br>datetime last_date;<br>uint init_trade_hour;<br>uint init_trade_min;<br>uint end_trade_hour;<br>uint end_trade_min;<br>MqlRates daily_bar[];<br>MqlBookInfo struct_book[];<br>double bids[];<br>double asks[];<br>uint book_levels;<br><br>//+------------------------------------------------------------------+<br>//| Inputs                                                           |<br>//+------------------------------------------------------------------+<br>input string                  input_symbol               = &quot;PETR4&quot;;           //Symbol to memory<br>input uint                    input_book_levels          = 1;                 //Number of book lines<br>input uint                    input_seconds_times        = 5;                 //Timer seconds<br>input string                  input_init_trade_time      = &quot;10:00&quot;;           //Time to initialize<br>input string                  input_end_trade_time       = &quot;17:00&quot;;           //Time to end<br><br>//+------------------------------------------------------------------+<br>//| Expert initialization function                                   |<br>//+------------------------------------------------------------------+<br>int OnInit()<br>  {<br>   if(!ValidInitialization())<br>      return INIT_PARAMETERS_INCORRECT;<br><br>   if(!InitializeArrays())<br>      return INIT_FAILED;<br><br>   if(!InitializeFile())<br>      return INIT_FAILED;<br><br>   if(!MarketBookAdd(symbol))<br>      return INIT_FAILED;<br><br>   EventSetTimer(input_seconds_times);<br><br>   return(INIT_SUCCEEDED);<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Expert deinitialization function                                 |<br>//+------------------------------------------------------------------+<br>void OnDeinit(const int reason)<br>  {<br>   MarketBookRelease(symbol);<br>   EventKillTimer();<br>   FileClose(filehandle);<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Expert tick function                                             |<br>//+------------------------------------------------------------------+<br>void OnTick()<br>  {<br><br>  }<br><br>//+------------------------------------------------------------------+<br>//| Timer function                                                   |<br>//+------------------------------------------------------------------+<br>void OnTimer()<br>  {<br>   if(TimeToCheck())<br>     {<br>      if(CopyRates(symbol,PERIOD_M1,0,1,last_tick)&lt;1)<br>         return;<br><br>      if(last_tick[0].time&lt;=last_date)<br>         return;<br><br>      if(!GetBook())<br>         return;<br><br>      string time_to_print = TimeToString(TimeTradeServer(),TIME_DATE)+&quot; &quot;+TimeToString(TimeTradeServer(),TIME_SECONDS);<br><br>      int book_size = (int)book_levels;<br>      string to_append = time_to_print + &quot;,&quot; + DoubleToString(last_tick[0].close) + &quot;,&quot;;<br>      for(int i = 0; i &lt; book_size; i++)<br>        {<br>         if(i == book_size - 1)<br>           {<br>            to_append += DoubleToString(bids[i]) + &quot;,&quot; + DoubleToString(asks[i]);<br>            break;<br>           }<br>         to_append += DoubleToString(bids[i]) + &quot;,&quot; + DoubleToString(asks[i]) + &quot;,&quot;;<br>        }<br>      FileWrite(filehandle, to_append);<br>      memory =+ FileSize(filehandle);<br>     }<br>  }<br><br><br>//+------------------------------------------------------------------+<br>//| GetBook                                                          |<br>//+------------------------------------------------------------------+<br>bool GetBook()<br>  {<br>   if(!MarketBookGet(symbol, struct_book))<br>     {<br>      Print(GetLastError());<br>      return false;<br>     }<br><br>   int size = ArraySize(struct_book);<br>   int mid = size / 2;<br><br>   ArrayRemove(bids, 0, WHOLE_ARRAY);<br>   ArrayRemove(asks, 0, WHOLE_ARRAY);<br><br>   ArrayResize(bids, mid);<br>   ArrayResize(asks, mid);<br><br>// Bids<br>   for(int i = mid - 1; i &gt;= 0; i--)<br>     {<br>      bids[i] = struct_book[i].price;<br>     }<br>   ArraySort(bids);<br><br>//Asks<br>   for(int i = mid; i &lt; size; i++)<br>     {<br>      asks[i - mid] = struct_book[i].price;<br>     }<br><br>   FillArrays(bids);<br>   FillArrays(asks);<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//|                                                                  |<br>//+------------------------------------------------------------------+<br>void FillArrays(double &amp;array[])<br>  {<br>   int size = (int)book_levels;<br><br>   if(ArraySize(array) &gt;= size)<br>      return;<br><br>   for(int i = ArraySize(array); i &lt; size; i++)<br>     {<br>      array[i] = 0;<br>     }<br>  }<br><br>//+------------------------------------------------------------------+<br>//| File define                                                      |<br>//+------------------------------------------------------------------+<br>string FilenameDefine(string _symbol)<br>  {<br>   MqlDateTime current_date;<br>   TimeToStruct(TimeTradeServer(),current_date);<br>   string month = IntegerToString(current_date.mon);<br>   if(StringLen(month) &lt; 2)<br>      month = &quot;0&quot; + month;<br>   string day = IntegerToString(current_date.day);<br>   if(StringLen(day) &lt; 2)<br>      day = &quot;0&quot; + day;<br>   return _symbol + &quot;_BookData_&quot; + IntegerToString(current_date.year) + month + day + &quot;.csv&quot;;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time to check                                                    |<br>//+------------------------------------------------------------------+<br>bool TimeToCheck()<br>  {<br>   int copied = CopyRates(symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime init = daily_bar[0].time + (init_trade_hour * 60 * 60) + (init_trade_min * 60);<br>      datetime end = daily_bar[0].time + (end_trade_hour * 60 * 60) + (end_trade_min * 60);<br>      datetime now = TimeTradeServer();<br><br>      if(now &gt;= init &amp;&amp; now &lt; end)<br>        {<br>         return (true);<br>        }<br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br>   return false;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Validate parameters                                              |<br>//+------------------------------------------------------------------+<br>bool ValidInitialization()<br>  {<br>   if(!SetTimesOfTrading())<br>      return false;<br><br>   if(!(input_book_levels &gt;= 1 &amp;&amp; input_book_levels &lt;= 10))<br>      return false;<br>      <br>   book_levels = input_book_levels;<br><br>   symbol = input_symbol;<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time of Trading inputs                                           |<br>//+------------------------------------------------------------------+<br>bool SetTimesOfTrading()<br>  {<br>   string init_trade[];<br>   if(StringSplit(input_init_trade_time, &#39;:&#39;, init_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   init_trade_hour = (int)StringToInteger(init_trade[0]);<br>   init_trade_min = (int)StringToInteger(init_trade[1]);<br><br>   string end_trade[];<br>   if(StringSplit(input_end_trade_time, &#39;:&#39;, end_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   end_trade_hour = (int)StringToInteger(end_trade[0]);<br>   end_trade_min = (int)StringToInteger(end_trade[1]);<br><br>   int copied = CopyRates(symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime init = daily_bar[0].time + (init_trade_hour * 60 * 60) + (init_trade_min * 60);<br>      datetime end = daily_bar[0].time + (end_trade_hour * 60 * 60) + (end_trade_min * 60);<br><br>      if(init &gt; end)<br>        {<br>         Print(&quot;[ERROR] Time to end trades must be bigger than time to init trades.&quot;);<br>         return false;<br>        }<br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br><br>   return true;<br>  }<br><br><br>//+------------------------------------------------------------------+<br>//| Initialize arrays                                                |<br>//+------------------------------------------------------------------+<br>bool InitializeArrays()<br>  {<br>   if(!ArraySetAsSeries(daily_bar, true))<br>      return false;<br><br>   if(!ArraySetAsSeries(struct_book, true))<br>      return false;<br><br>   if(!ArraySetAsSeries(bids, true))<br>      return false;<br><br>   if(!ArraySetAsSeries(asks, true))<br>      return false;<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Initialize file to save                                          |<br>//+------------------------------------------------------------------+<br>bool InitializeFile()<br>  {<br>   filename = FilenameDefine(symbol);<br><br>   if(FileIsExist(filename))<br>     {<br>      filehandle = FileOpen(filename, FILE_WRITE|FILE_READ|FILE_CSV, &quot;,&quot;);<br>      if(filehandle!=INVALID_HANDLE)<br>        {<br>         int column = 1;<br>         while(!FileIsEnding(filehandle))<br>           {<br>            int data_size = FileReadInteger(filehandle, INT_VALUE);<br>            string read_data = FileReadString(filehandle, data_size);<br>            if(column==columns)<br>              {<br>               column = 0;<br>              }<br>            if(column==1)<br>              {<br>               datetime new_data = (datetime)read_data;<br>               if(new_data &gt; last_date)<br>                 {<br>                  last_date = new_data;<br>                 }<br>              }<br>            memory =+ FileSize(filehandle);<br>            column++;<br>           }<br>        }<br>     }<br>   else<br>     {<br>      filehandle = FileOpen(filename, FILE_WRITE|FILE_READ|FILE_CSV, &quot;,&quot;);<br>      int book_size = (int)book_levels;<br>      string to_append = &quot;Date,Last,&quot;;<br>      for(int i = 1; i &lt;= book_size; i++)<br>        {<br>         if(i == book_size)<br>           {<br>            to_append += &quot;Bid_&quot; + IntegerToString(i) + &quot;,Ask_&quot; + IntegerToString(i);<br>            break;<br>           }<br>         to_append += &quot;Bid_&quot; + IntegerToString(i) + &quot;,Ask_&quot; + IntegerToString(i) + &quot;,&quot;;<br>        }<br>      FileWrite(filehandle, to_append);<br>      memory =+ FileSize(filehandle);<br>     }<br><br>   if(filehandle==INVALID_HANDLE)<br>     {<br>      Print(&quot;Error in opening file.&quot;);<br>      return false;<br>     }<br><br>   Print(&quot;Getting data from &quot; + symbol);<br><br>   return true;<br>  }<br>//+------------------------------------------------------------------+</pre><p>This code generates a CSV file with header like below when using the PETR4 Brazilian ticker.</p><pre>Date,Last,Bid_1,Ask_1,Bid_2,Ask_2,Bid_3,Ask_3,Bid_4,Ask_4,Bid_5,Ask_5<br>2023.04.03 10:09:49,24.00000000,24.00000000,24.03000000,23.99000000,24.04000000,23.98000000,24.05000000,23.97000000,24.06000000,23.96000000,24.07000000<br>2023.04.03 10:09:54,24.00000000,24.01000000,24.02000000,24.00000000,24.03000000,23.99000000,24.04000000,23.98000000,24.05000000,23.97000000,24.06000000<br>2023.04.03 10:09:59,24.02000000,24.01000000,24.02000000,24.00000000,24.03000000,23.99000000,24.04000000,23.98000000,24.05000000,23.97000000,24.06000000</pre><p>Now, using Python:</p><pre>import MetaTrader5 as mt5<br>import time<br>import datetime<br>import pandas as pd<br><br><br>## Inputs<br>input_book_levels = 5<br>input_data_frequency = 5<br>input_symbol = &#39;VALE3&#39;<br>input_file_name = f&#39;{input_symbol}_BookData_{datetime.datetime.now().strftime(&quot;%Y%m%d&quot;)}.csv&#39;<br>input_init_time = &#39;10:00&#39;<br>input_end_time = &#39;17:00&#39;<br>input_shutdown_when_not_time = True<br><br><br>## Constants<br>BOOK_TYPE_BID = 0<br>BOOK_TYPE_ASK = 1<br>DATETIME_FORMAT = &#39;%Y-%m-%d %H:%M:%S&#39;<br><br><br>## Variables<br>NOW = datetime.datetime.now()<br>TIME_TO_GET = True<br><br><br>## Validate inputs<br>if not 0 &lt; input_book_levels &lt; 20:<br>    print(&#39;Book levels must be between 0 and 20.&#39;)<br>    quit() <br><br>if input_data_frequency &lt; 1:<br>    print(&#39;Warning: the frequency is less than 1 seconds, it may cause memory damage.&#39;)<br><br><br>## Initialize<br>print(&quot;&quot;)<br>print(&quot;MetaTrader5 package author: &quot;,mt5.__author__)<br>print(&quot;MetaTrader5 package version: &quot;,mt5.__version__)<br>print(&quot;&quot;)<br>if not mt5.initialize():<br>    print(&quot;initialize() failed, error code =&quot;,mt5.last_error())<br>    mt5.shutdown()<br>    quit()<br><br>if not mt5.symbol_select(input_symbol,True):<br>    print(f&quot;Failed to select {input_symbol}&quot;)<br>    mt5.shutdown()<br>    quit()<br> <br>if not mt5.market_book_add(input_symbol):<br>    print(f&quot;mt5.market_book_add({input_symbol}) failed, error code =&quot;,mt5.last_error())<br>    mt5.shutdown()<br>    quit()<br><br><br>try:<br>    print(&#39;Existing file found. Appending to it.&#39;)<br>    df_data = pd.read_csv(input_file_name)<br>    df_data = df_data.set_index(&#39;Date&#39;)<br>except:<br>    print(&#39;No existing file found. Starting from scratch.&#39;)<br>    df_data = pd.DataFrame()<br><br><br>def save_data(asks: dict, bids: dict, last: float) -&gt; pd.DataFrame():<br>    global df_data<br>    index = datetime.datetime.now().strftime(DATETIME_FORMAT)<br>    asks.update(bids)<br>    df = pd.DataFrame.from_dict(asks.items())<br>    df = df.set_index(0)<br>    df = df.T<br>    df.columns = asks.keys()<br>    df[&#39;Date&#39;] = index<br>    df = df.set_index(&#39;Date&#39;)<br>    df[&#39;Last&#39;] = last<br>    if df_data.empty:<br>        df_data = df<br>    else:<br>        df_data = df_data.append(df)<br>    df_data.to_csv(input_file_name)<br>    return df_data<br><br>def update_time_to_get():<br>    global TIME_TO_GET<br>    global NOW<br>    NOW = datetime.datetime.now()<br>    TIME_TO_GET = (datetime.datetime(NOW.year,NOW.month,NOW.day,int(input_init_time.split(&#39;:&#39;)[0]),int(input_init_time.split(&#39;:&#39;)[1]),0) &lt;=   <br>               NOW &lt;= <br>               datetime.datetime(NOW.year,NOW.month,NOW.day,int(input_end_time.split(&#39;:&#39;)[0]),int(input_end_time.split(&#39;:&#39;)[1]),0))<br><br>while(True):<br>    try:<br>        bids = {}<br>        asks = {}<br>        update_time_to_get()<br>        if TIME_TO_GET:<br>            last_tick = mt5.symbol_info_tick(input_symbol)._asdict()<br>            items = mt5.market_book_get(input_symbol)<br>            i = 0<br>            if items:<br>                for it in items:<br>                    it_dict = it._asdict()<br>                    if it_dict[&#39;type&#39;] == BOOK_TYPE_ASK:<br>                        key_index = int(len(items)/2-i)<br>                        if key_index in range(1,input_book_levels+1):<br>                            key = f&#39;Ask_{key_index}&#39;<br>                            if key in asks.keys():<br>                                asks.update({key: it_dict[&#39;price&#39;]})<br>                            else:<br>                                asks[key] = it_dict[&#39;price&#39;]<br>                    if it_dict[&#39;type&#39;] == BOOK_TYPE_BID:<br>                        key_index = len(bids)+1<br>                        if key_index in range(1,input_book_levels+1):<br>                            key = f&#39;Bid_{key_index}&#39;<br>                            if key in bids.keys():<br>                                bids.update({key: it_dict[&#39;price&#39;]})<br>                            else:<br>                                bids[key] = it_dict[&#39;price&#39;]<br>                    i += 1<br>            asks = dict(reversed(asks.items()))<br>            df = save_data(asks, bids, last_tick[&#39;last&#39;])<br>        else:<br>            if input_shutdown_when_not_time:<br>                print(&#39;Time to get data expired.&#39;)<br>                break<br>        time.sleep(input_data_frequency)<br>    except NameError as e:<br>        print(e)<br>        mt5.shutdown()<br>        break</pre><p>This one generates a CSV like this when getting VALE3 Brazilian ticker data.</p><pre>Date,Ask_1,Ask_2,Ask_3,Ask_4,Ask_5,Bid_1,Bid_2,Bid_3,Bid_4,Bid_5,Last<br>2023-04-03 10:06:37,79.88,79.9,79.91,79.92,79.93,79.87,79.86,79.85,79.84,79.83,79.88<br>2023-04-03 10:06:42,79.9,79.91,79.92,79.93,79.94,79.87,79.86,79.85,79.84,79.83,79.9<br>2023-04-03 10:06:47,79.9,79.91,79.92,79.93,79.94,79.87,79.86,79.85,79.84,79.83,79.88</pre><p>You have the possibility to choose the asset, number of book levels, frequency to save data and a time range to get data.</p><h3>If I have to maintain the script running, there is a cost of energy involved</h3><p>You’re right, there is. But of course there are ways to avoid you to use your own machine to store data. First you could use any VPS to run this code like a task, but you’d have to configure all its environment, installing MetaTrader5 etc. Now, here I go again being a MetaTrader5 fanboy: this platform has its own cloud servers, where you can use them to run your MQL5/Python scripts. Today, the cost per month is something and 13 dollars for a six-month contract.</p><p>Here is my advice: if you find a tick and book API of six months of data that costs less than 75 dollars — first tell me — buy it and store all possible data! If not, I think the solution I’ve presented here is to you, enjoy!</p><p>This one was small, but I really think this is gold, a very good way of having trustful data to your backtests. Hope you liked it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd7abbfc479a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What you need to know about backtests]]></title>
            <link>https://angelohomen.medium.com/what-you-need-to-know-about-backtests-26383be719b8?source=rss-9bbd7c8c5876------2</link>
            <guid isPermaLink="false">https://medium.com/p/26383be719b8</guid>
            <category><![CDATA[algotrading]]></category>
            <category><![CDATA[electronic-trading]]></category>
            <category><![CDATA[quant-strategy]]></category>
            <category><![CDATA[trade]]></category>
            <category><![CDATA[backtest]]></category>
            <dc:creator><![CDATA[Angelo Homen, CQF]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 16:42:13 GMT</pubDate>
            <atom:updated>2023-04-03T16:48:08.489Z</atom:updated>
            <content:encoded><![CDATA[<p>Backtesting strategies of any investment school was always a challenge to me. I’d say that my experiences with algotrading were not the best ones and that lead me to be rigorous, not just about my backtesting results, but about <em>how</em> do I run my backtests.</p><p>I need to be fair, if your purpose is to backtest a portfolio management every first day of the month you don’t need to be so critical. When talking about intraday or more frequently trades, the game changes. But, why?</p><p>Every trade is a gambling game, and I know you read/hear it in your every single study somewhere, but it has to be told. The number of variables present in a trade is uncountable. Macroeconomy, sentimental analysis, technical analysis, averages, math, and so on… When modelling a trading strategy, you’re just selecting 0.0000001% (or less) number of variables to try predicting if the asset will go up for buying, down for selling, or if the complete market theory will be respected in order to make some “free risk money” in arbitrage technics.</p><p>Backtesting has a lot of ways to be done, in order to build a profitable trading strategy, but this process has a big problem: overfitting. Overfitting is the art of building the perfect trading bot using so many optimizations in your train sample that it is just the <em>state of the art</em> in automated trading — when you learn how to construct a time machine to fly to the past and use this trading bot in real life (and trust me, the chances of losing money with this one still exists, I’ll tell you why later).</p><p>Backtesting is not an art, it is a scientific method, and you <strong>need</strong> to be rigorous. I’ve already seen some people building their own strategies using their own tool to backtest with data from free source API’s and need to say: this is not wrong, when you know <strong>exactly</strong> what you’re doing. Daily data is useful for strategies that do not depend at all on a good execution environment. So, trading systems based on portfolio management equilibrium on Markowitz theorem, for example, can be tested using Yahoo Finance’s API data, and if you’re rigorous enough, you can add slippage to your trade, forcing some “real life” environment to your test.</p><p>On the other hand, if your purpose is something sophisticated, like using a technical indicator to intraday trading, for example, or even catch some market inefficiency (and here the execution time is the key parameter), you have to be careful and critical about your entire backtesting function, specially with your market data source. At first, the data has to be real, i.e., an historical tick had to be a trade or, in some way, that price had to be shown some time at that specific day and time range. I know, this sounds quite obvious, but my purpose here is to show you how easy it is to transform your wonderful train backtest into garbage.</p><p>My background is algotrading, focused on intraday trading automations, and I’ve seen a lot of mistakes when guiding a team to build some automated strategies, and of course, at least 90% of those mistakes were mine. From my experience I got some highlights and want to share with you to, in some way, help you follow less and correct steps to build your trading bot.</p><h4>Overfitting</h4><p>Like I said before, modelling rules for trading is choosing some of the millions or billions of available variables that generates impact on the instrument prices. But when choosing it, there is a trade-off: the more you increase the number of variables chosen to model your strategy, your chances of overfitting are bigger. I like to think about a polynomial equation to fit a complex function. When you increase the number of variables at your equation, it will perfectly adjust to its target, but when talking specifically about a trading backtest, it is not good to have a perfect model at your training sample, because you would build an addicted bot, that just works well at this piece of data, and when it goes to real life, it would be just a money burn bot.</p><h4>Backtesting method</h4><p>My purpose here is not to help you implement your backtest, because I’m a little lazy about it. There are a thousand python libraries that run backtests for you, and I’m pretty sure that their developers did a better job than I would do, that is not my strongest skill. Beyond python libraries, we have trading platforms that run backtests for you, like MetaTrader 4/5 and Nelogica’s ProfitPro.</p><p>MetaTrader has a complete backtesting report and some ways of running it. You can set up your backtesting running as:</p><ul><li>OHLC: that only uses open, high, low and close prices of the chosen instrument. Usually is the fastest method to backtest in MetaTrader.</li><li>Every tick: this method activates a tick simulator, where there is an algorithm that sets randomly negotiations between the range prices given by 1-minute timeframe candles and, of course, respecting its open and close prices.</li><li>Every tick based on real ticks: this one is the <strong>perfect </strong>way to backtest your strategy, but of course, there is a trade off. This method depends on your broker, because MetaTrader downloads data from your account’s related broker. And, because storing every tick of an instrument is very costly, usually there is only a week of every tick data available.</li></ul><p>ProfitPro has been developing a very interesting way to backtest strategies, with a very easy implementation. I’m learning some stuff about it yet, so, in some time, I’m quite sure I will bring something to show you how it works.</p><p>Ok, now, what is my piece of device? Use a backtest development that you trust. If you trust in your own development, develop it, using any language you want. If you’re like me and wants to focus on developing your own strategy and don’t want to develop a complex backtest, use backtest tools like MT5 or ProfitPro.</p><p>One question you may do is: when using any platform to backtest, how am I sure that it is using real data, that actually had been a trade in the past? Well, you need to search about the broker, but this problem can only happen for past data, and not for real time ones. One thing you can do to avoid it is to build a code that captures trades every time step and, after some time, you’d have your own data to test. You can do an even better thing: import your own database to MetaTrader and use its backtest tool! This may be one of my next articles, what do you think about it?</p><h4>How do I build my trading bots</h4><p>First thing, as I mentioned early, is to guarantee that I have trustful data.</p><p>To build a trading bot, I try to be as critical and rigorous as possible. First thing I do is to analyze how many historical data I have available. Talking about MT5, I have usually 5 years. With those 5 years, I estimate my train/test ratio, which to me was always 70/30 — I train my algorithm at 70% of historical data and test on 30%.</p><p>My rule is simple: this 30% of test data just doesn’t exist. This means that I don’t want to know about any piece of it until the time to it comes. I do it to have no bias on my trading bot hypothesis. When you have a hint about your test sample, trust me, you’ll find a certain way to fit it at your strategy. That is the first way to build garbage.</p><p>The next step is to draw a flowchart (using something like PowerPoint or paper and pen) to turn your hypothesis visible. You have to be as more objective as you can, because algorithms doesn’t accept subjective parameters. Always make sure you’re using logical parameters. For example, if you’re going to use some moving average applied to daily data, you could use periods like 5, 22, 132, etc. and not 11, 49, and so on. You may ask why. Well, we’re talking about time series data, so we need logical time series periods. A period of 5 is the same to say that you want a weekly average. A period of 22 is the same to say that you’re working with monthly average (a month have 22 working days in average). So, when optimizing an algorithm, please, do not choose a non-logical parameter, that would be the second way to build a non-successful trading bot.</p><p>To optimize and choose the best optimizations, I follow some good references and methods. <em>The Evaluation and Optimization of Trading Strategies — Robert Pardo</em> has very interesting ways to turn the optimization choosing more objective than subjective. My way of backtesting is using WFM/WFA/WFE (Walking Forward Matrix/Analysis/Efficiency) methods combined to optimize in-sample data. A basic rule is to always discard the top 15% results of the optimization in order to add statistical confidence.</p><p>More important than visualizing your backtest report (with sharpe ratio, drawdown, max profit, min loss, etc.), is to visualize your equity curve. Trust me, it can really tell you about your strategy more than its statistical results. A graphic is simple to analyze: you just want a line that just goes up as softness as possible. That is my first impression of the trading bot. I don’t like volatile returns, I like consistent returns, so, what I’m searching is a soft equity curve that goes up.</p><p>After all these steps, the last one is the key: use the chosen model on test data (the 30% of data that “doesn’t” exist). And the rule is pretty simple. If:</p><ul><li>Returns are negative or next to zero;</li><li>The test drawdown is bigger than train drawdown;</li><li>The maximum consecutive losses in test is bigger than maximum consecutive losses in train;</li></ul><p>The hypothesis failed. It is garbage. Do not optimize it again, just go to another one. The reason for this is simple: now you know exactly where your trading bot fails, and you will try to fix is in train data to have a good test data fit, leading to an overfitting problem.</p><p>This one doesn’t have any code. Here I’ve tried to pass some of my vision about building automated trading strategies in order to help you to build your in the right way. There are a lot of ways to choose the best optimization, here I’ve told you about my way of doing it. How do you do your choosing? Are you rigorous about your backtest? Hope you like it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26383be719b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your first intraday totally automated Quant strategy — Part 3]]></title>
            <link>https://angelohomen.medium.com/your-first-intraday-totally-automated-quant-strategy-part-3-7f44601f96c2?source=rss-9bbd7c8c5876------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f44601f96c2</guid>
            <category><![CDATA[electronic-trading]]></category>
            <category><![CDATA[algotrading]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[metatrader-5]]></category>
            <dc:creator><![CDATA[Angelo Homen, CQF]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 23:17:21 GMT</pubDate>
            <atom:updated>2023-03-30T21:48:24.820Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your first intraday totally automated Quant strategy — Part 3</h3><h3>Notes</h3><p>This is the continuation of <em>“</em><a href="https://angelohomen.medium.com/your-first-intraday-totally-automated-quant-strategy-part-2-ab7c2fdd86f3"><em>Your first intraday totally automated Quant strategy — Part 2</em></a><em>”</em> that, if you didn’t read, I advise you to do it in order to have an easier understanding.</p><p><em>If your purpose here is just seeing the code, just go to the end of the page, my GitHub repository link is there, and you can see everything we’ve done here.</em></p><p>For this final part, we’re going to introduce some execution rules to our trading bot, specifically: Trailing Stop and Breakeven. Furthermore, we’ll implement some debugging logging to tests become easier.</p><p>Breakeven is a logic based on a trigger and a margin. Basically, when the difference between your breakeven trigger and your entry price has a defined value, your Stop Loss will become your margin plus entry point (for buying, minus entry point for selling). For example, suppose that you’re bought at price 30 with Stop Loss of 29 and your breakeven trigger and margin are, respectively, 5 and 3. When the current price becomes equals or bigger than 35, your Stop Loss will “jump” from 29 to 33 (30 from entry and 3 from margin).</p><p>Trailing stop has a little difference when comparing to breakeven. The difference is that the trailing stop has a “continuous” process, and not just one time trigger. We’ll just check at each market trade if the absolute difference between the symbol’s current price and our Stop Loss is equals or bigger than a trigger, and when it is, we’ll add (for buy) a predetermined step. For example, let’s say our trigger is 10 and stop is 1. Our current Stop Loss is 25, and we’re sold. Let’s say the current price became 15. The difference between 25 (Stop Loss) and 15 (Last price) is equals or bigger than 10? Yes! So, let’s move a step (to a better price, never worst) at our Stop Loss. Is the step is 1, now our Stop Loss will become 25–1=24 (remember, we’re sold). Believe me, this is going to be simple.</p><p>So, let’s do it!</p><p>As always, we’re going to start setting our new global variables and the options to the user to activate or not the use of breakeven and trailing stop. So, it is going to turn to:</p><pre>//+------------------------------------------------------------------+<br>//| Global Variables                                                 |<br>//+------------------------------------------------------------------+<br>ulong magic_number;<br>int average_period;<br>ENUM_TIMEFRAMES returns_timeframe;<br>ENUM_RISK_USING risk_indicator;<br>double risk_array[];<br>double risk_ma;<br>double risk_std_dev;<br>double returns_array[];<br>double confidence_level;<br>double VaR = 0;<br>double ES = 0;<br>double array_mean;<br>double array_std_dev;<br>double last_value;<br>int init_trade_hour;<br>int init_trade_min;<br>int end_trade_hour;<br>int end_trade_min;<br>int close_pos_hour;<br>int close_pos_min;<br>bool use_risk_mgmt;<br>double take_profit_pts;<br>double stop_loss_pts;<br>bool use_trades_limit;<br>int number_of_trades;<br>int count_number_of_trades;<br>bool use_breakeven;<br>double break_even;<br>double break_even_pts;<br>bool breakeven_done;<br>bool use_trailing_stop;<br>double trigger_ts;<br>double step_ts;<br>bool close_pos_on_avg;<br><br>//+------------------------------------------------------------------+<br>//| Inputs                                                           |<br>//+------------------------------------------------------------------+<br>input group &quot;Expert advisor&#39;s settings&quot;<br>input ulong                   input_magic_number         = 1;                 //EA Magic number<br><br>input group &quot;Expert advisor&#39;s setup parameters&quot;<br>input ENUM_RISK_USING         input_risk_indicator       = RISK_VAR;          //Risk indicator calculation<br>input ENUM_TIMEFRAMES         input_returns_timeframe    = PERIOD_M1;         //Returns timeframe<br>input uint                    input_average_period       = 20;                //Risk indicator MA period<br>input ENUM_CONFIDENCE_LEVELS  input_confidence_level     = LEVEL_95;          //Risk indicator confidence level<br>input double                  input_risk_std_dev         = 2;                 //Risk indicator Standard Deviation<br>input bool                    input_close_pos_on_avg     = false;             //Close position on risk indicator average?<br>input string                  input_init_trade_time      = &quot;09:05&quot;;           //Time to initialize trades<br>input string                  input_end_trade_time       = &quot;13:00&quot;;           //Time to end trades<br>input string                  input_close_positions      = &quot;17:00&quot;;           //Time to close positions<br><br>input group &quot;Expert advisor&#39;s risk management&quot;<br>input bool                    input_use_risk_mgmt        = false;             //Use Risk Management?<br>input double                  input_take_profit_pts      = 50;                //Take profit threshold (pts - entry)<br>input double                  input_stop_loss_pts        = 10;                //Stop loss threshold (entry - pts)<br>input bool                    input_use_trades_limit     = false;             //Use trades limit?<br>input int                     input_number_of_trades     = 1;                 //Number of trades per day<br><br>input group &quot;Expert advisor&#39;s breakeven and trailing stop&quot;<br>input bool                    input_use_breakeven        = false;             //Use breakeven?<br>input double                  input_break_even           = 10;                //Breakeven trigger<br>input double                  input_break_even_pts       = 5;                 //Breakeven points<br>input bool                    input_use_trailing_stop    = false;             //Use trailing stop?<br>input double                  input_trigger_ts           = 20;                //Trailing stop trigger<br>input double                  input_step_ts              = 1;                 //Trailing stop step</pre><p>And, now with those variables, let’s make sure everything has the right value at the <strong>InitializeParameters() </strong>method.</p><pre>//+------------------------------------------------------------------+<br>//| Initialize parameters                                            |<br>//+------------------------------------------------------------------+<br>bool InitializeParameters()<br>  {<br>   magic_number = input_magic_number;<br><br>   if(input_risk_indicator == RISK_ES)<br>      risk_indicator = RISK_ES;<br>   else<br>      risk_indicator = RISK_VAR;<br><br>   returns_timeframe = input_returns_timeframe;<br><br>   average_period = (int)input_average_period;<br><br>   if(input_confidence_level == LEVEL_95)<br>      confidence_level = .95;<br>   else<br>      confidence_level = .99;<br><br>   if(input_risk_std_dev &gt; 0)<br>      risk_std_dev = input_risk_std_dev;<br>   else<br>      risk_std_dev = -input_risk_std_dev;<br><br>   close_pos_on_avg = input_close_pos_on_avg;<br><br>   if(risk_std_dev == 0)<br>     {<br>      Print(&quot;[ERROR] Standard deviation must be bigger than 0.&quot;);<br>      return false;<br>     }<br><br>   if(!SetTimesOfTrading())<br>     {<br>      return false;<br>     }<br><br>   use_risk_mgmt = input_use_risk_mgmt;<br><br>   take_profit_pts = MathAbs(input_take_profit_pts);<br><br>   stop_loss_pts = MathAbs(input_stop_loss_pts);<br><br>   use_trades_limit = input_use_trades_limit;<br><br>   if(use_trades_limit)<br>     {<br>      if(input_number_of_trades &lt;= 0)<br>        {<br>         Print(&quot;[ERROR] When using number of trades limit you must specify a value bigger than zero.&quot;);<br>         return false;<br>        }<br>      else<br>        {<br>         number_of_trades = input_number_of_trades;<br>        }<br>     }<br><br>   if(use_risk_mgmt)<br>     {<br>      if(stop_loss_pts == 0)<br>        {<br>         Print(&quot;[ERROR] When using risk management Stop Loss must be different from 0.&quot;);<br>         return false;<br>        }<br><br>      if(take_profit_pts == 0)<br>        {<br>         Print(&quot;[ERROR] When using risk management Take Profit must be different from 0.&quot;);<br>         return false;<br>        }<br>     }<br><br>   use_breakeven = input_use_breakeven;<br><br>   if(use_breakeven)<br>     {<br>      if(break_even_pts &gt; break_even)<br>        {<br>         Print(&quot;[ERROR] Breakeven point must be equals or less than breakeven.&quot;);<br>         return false;<br>        }<br><br>      break_even_pts = input_break_even_pts;<br>      break_even = input_break_even;<br>     }<br><br>   use_trailing_stop = input_use_trailing_stop;<br><br>   if(use_trailing_stop)<br>     {<br>      if(step_ts &gt; trigger_ts)<br>        {<br>         Print(&quot;[ERROR] Trailing stop point must be equals or less than trigger.&quot;);<br>         return false;<br>        }<br><br>      step_ts = input_step_ts;<br>      trigger_ts = input_trigger_ts;<br>     }<br><br>   return true;<br>  }</pre><p>Both <strong>Breakeven() </strong>and <strong>TrailingStop()</strong> methods will check if there are open positions to activate it, and our <strong>EACoreExecution()</strong> method will be:</p><pre>//+------------------------------------------------------------------+<br>//| Core logic                                                       |<br>//+------------------------------------------------------------------+<br>void EACoreExecution()<br>  {<br>   if(NewDay())<br>      InitializeDay();<br><br>   long check_positions = OpenPositionTicketByMagic();<br><br>   if(check_positions != 0)<br>     {<br>      CheckCloseTrigger(check_positions);<br><br>      if(!breakeven_done &amp;&amp; use_breakeven)<br>         Breakeven(check_positions);<br><br>      if(use_trailing_stop)<br>         TrailingStop(check_positions);<br>     }<br><br>   if(TimeToTrade())<br>     {<br>      if(NewCandle())<br>        {<br>         if(!CalculateStatistics())<br>            return;<br><br>         switch(TriggerActions())<br>           {<br>            case TRIGGER_BUY:<br>               BuyTriggerLogic(check_positions);<br>               break;<br>            case TRIGGER_SELL:<br>               SellTriggerLogic(check_positions);<br>               break;<br>            default:<br>               break;<br>           }<br>        }<br>     }<br><br>   if(TimeToClosePositions())<br>     {<br>      if(check_positions != 0)<br>        {<br>         ulong ticket = MathAbs(check_positions);<br>         ClosePosition(ticket);<br>        }<br>     }<br>  }</pre><p>The <em>breakeven_done </em>variable is used to control if a breakeven was already triggered in a trade, and that&#39;s why I told you to implement the <strong>ClosePosition() </strong>method! Remember about having a centralized method for it? When you close a trade, you must set this variable to false, for the next trade to have the breakeven possibility. So now, here it is, the <strong>InitializeDay() </strong>and our newest <strong>ClosePosition()</strong> methods:</p><pre>//+------------------------------------------------------------------+<br>//| Initialize day                                                   |<br>//+------------------------------------------------------------------+<br>void InitializeDay()<br>  {<br>   count_number_of_trades = 0;<br>   breakeven_done = false;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Close open position                                              |<br>//+------------------------------------------------------------------+<br>void ClosePosition(long ticket)<br>  {<br>   if(m_trade.PositionClose(ticket, -1))<br>     {<br>      breakeven_done = false;<br>      Print(&quot;Closed position with ticket &quot; + IntegerToString(ticket));<br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error on position close. Result code: &quot;, m_trade.ResultRetcode(), &quot;, Retcode description: &quot;, m_trade.ResultRetcodeDescription());<br>     }<br>  }</pre><p>Now, if there is an open position, and we’re using both breakeven and trailing stop, the rules will be next:</p><pre>//+------------------------------------------------------------------+<br>//| Breakeven                                                        |<br>//+------------------------------------------------------------------+<br>void Breakeven(long pos_ticket)<br>  {<br>   if(pos_ticket == 0 || !use_breakeven)<br>      return;<br><br>   double open_price;<br>   double current_sl;<br>   double current_tp;<br><br>   double last_price = SymbolInfoDouble(_Symbol, SYMBOL_LAST);<br>   long ticket = MathAbs(pos_ticket);<br><br>   m_position.InfoDouble(POSITION_PRICE_OPEN, open_price);<br><br>   m_position.InfoDouble(POSITION_SL, current_sl);<br><br>   m_position.InfoDouble(POSITION_TP, current_tp);<br><br>   if(pos_ticket &gt; 0)<br>     {<br>      if(last_price - open_price &gt;= break_even)<br>        {<br>         double new_sl = NormalizePrice(open_price + break_even_pts);<br><br>         if(new_sl &gt; current_sl)<br>           {<br>            if(m_trade.PositionModify(ticket, new_sl, current_tp))<br>              {<br>               breakeven_done = true;<br>               Print(&quot;Stop loss was modified from &quot; + DoubleToString(current_sl) + &quot; to &quot; + DoubleToString(new_sl));<br>              }<br>            else<br>              {<br>               Print(&quot;[ERROR] Error on position modify. Result code: &quot;, m_trade.ResultRetcode(), &quot;, Retcode description: &quot;, m_trade.ResultRetcodeDescription());<br>              }<br>           }<br>        }<br>     }<br><br>   if(pos_ticket &lt; 0)<br>     {<br>      if(open_price - last_price &gt;= break_even)<br>        {<br>         double new_sl = NormalizePrice(open_price - break_even_pts);<br><br>         if(new_sl &lt; current_sl)<br>           {<br>            if(m_trade.PositionModify(ticket, new_sl, current_tp))<br>              {<br>               breakeven_done = true;<br>               Print(&quot;Stop loss was modified from &quot; + DoubleToString(current_sl) + &quot; to &quot; + DoubleToString(new_sl));<br>              }<br>            else<br>              {<br>               Print(&quot;[ERROR] Error on position modify. Result code: &quot;, m_trade.ResultRetcode(), &quot;, Retcode description: &quot;, m_trade.ResultRetcodeDescription());<br>              }<br>           }<br>        }<br>     }<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Trailing stop                                                    |<br>//+------------------------------------------------------------------+<br>void TrailingStop(long pos_ticket)<br>  {<br>   if(pos_ticket == 0 || !use_trailing_stop)<br>      return;<br><br>   double open_price;<br>   double current_sl;<br>   double current_tp;<br><br>   double last_price = SymbolInfoDouble(_Symbol, SYMBOL_LAST);<br>   long ticket = MathAbs(pos_ticket);<br><br>   m_position.InfoDouble(POSITION_PRICE_OPEN, open_price);<br><br>   m_position.InfoDouble(POSITION_SL, current_sl);<br><br>   m_position.InfoDouble(POSITION_TP, current_tp);<br><br>   if(pos_ticket &gt; 0)<br>     {<br>      if(last_price &gt;= (current_sl + trigger_ts))<br>        {<br>         double new_sl = NormalizeDouble(MathMax((current_sl + step_ts), (last_price - trigger_ts)), _Digits);<br><br>         if(new_sl &gt; current_sl)<br>           {<br>            if(m_trade.PositionModify(ticket, new_sl, current_tp))<br>              {<br>               Print(&quot;Done trailing stop.&quot;);<br>              }<br>            else<br>              {<br>               Print(&quot;[ERROR] Error on position modify. Result code: &quot;, m_trade.ResultRetcode(), &quot;, Retcode description: &quot;, m_trade.ResultRetcodeDescription());<br>              }<br>           }<br>        }<br>     }<br><br>   if(pos_ticket &lt; 0)<br>     {<br>      if(last_price &lt;= (current_sl - trigger_ts))<br>        {<br>         double new_sl = NormalizeDouble(MathMin((current_sl - step_ts), (last_price + trigger_ts)), _Digits);<br><br>         if(new_sl &lt; current_sl)<br>           {<br>            if(m_trade.PositionModify(ticket, new_sl, current_tp))<br>              {<br>               Print(&quot;Done trailing stop.&quot;);<br>              }<br>            else<br>              {<br>               Print(&quot;[ERROR] Error on position modify. Result code: &quot;, m_trade.ResultRetcode(), &quot;, Retcode description: &quot;, m_trade.ResultRetcodeDescription());<br>              }<br>           }<br>        }<br>     }<br>  }</pre><p>And that’s it, my friend, your brand-new trading bot is available for tests (and please, JUST tests and simulations). My purpose with these three articles was to:</p><ul><li>Present you MetaTrader5 and show you the potential this platform has.</li><li>Show you some cool stuff you can do talking about Algotrading. I know that was not a real strategy, but Value at Risk and/or Expected Shortfall are tools that Quants need to know how to implement and to interpret, so, it was not that bad!</li><li>Overcome my shyness.</li></ul><p>I promise you, it was just the first of many things we can do together! In my next articles I’ll show topics like: how to build your own backtest database (where you can use either for MetaTrader5 and even for your Python code), how to interpret a backtest correctly (in Angelo’s side of view), how to work with optimizations and (I confess I’m really excited to write) how to develop this exact trading bot using Python plugged on MetaTrader5.</p><p>You can see at GitHub that there are some new codes about logging to facilitate understanding possible errors that occur during backtest/execution.</p><p>If you want to see if it is exactly how I’ve implemented it, please visit my GitHub repository with this code:</p><p><a href="https://github.com/angelohomen/BasicExpertAdvisor/blob/main/BasicEA3.mq5">BasicExpertAdvisor/BasicEA3.mq5 at main · angelohomen/BasicExpertAdvisor</a></p><p>So, what do you think about this article? Was it useful? Did you think it was too large? Please, if you have any doubt or feedback, let me know! Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f44601f96c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your first intraday totally automated Quant strategy — Part 2]]></title>
            <link>https://angelohomen.medium.com/your-first-intraday-totally-automated-quant-strategy-part-2-ab7c2fdd86f3?source=rss-9bbd7c8c5876------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab7c2fdd86f3</guid>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[quant-strategy]]></category>
            <category><![CDATA[algotrading]]></category>
            <dc:creator><![CDATA[Angelo Homen, CQF]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 12:01:28 GMT</pubDate>
            <atom:updated>2023-03-30T21:47:06.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your first intraday totally automated Quant strategy — Part 2</h3><h3>Notes</h3><p>This is the continuation of <em>“</em><a href="https://angelohomen.medium.com/your-first-intraday-totally-automated-quant-strategy-part-1-8922b534da43"><em>Your first intraday totally automated Quant strategy — Part 1</em></a><em>”</em> that, if you didn’t read, I advise you to do it in order to have an easier understanding.</p><p><em>If your purpose here is just seeing the code, just go to the end of the page, my GitHub repository link is there, and you can see everything we’ve done here.</em></p><p>For this Part 2 I want to introduce some risk management to our strategy. Basically, the main purpose of these implementations will be to use Take Profit and Stop Loss based on price difference and to limit the number of trades per day. These parameters will be optional.</p><p>Stop Loss is a very important parameter to have on your trading bot in order to limit your losses for each trade. On the other hand, if you don’t have control about your number of trades per day, you might have trouble when having 5, 10, 15… trigger to trade in just one day, because your maximum losing amount will be your predefined Stop Loss times the number of trades. That is not really bad, but if you’re a person that likes to have more control on your strategy, this can be interesting for you.</p><h3>Hands on</h3><p>First thing, as always, we need to implement the possibility of the user to choose if it wants to use risk management or not, so, our global variables and inputs will be like this:</p><pre>//+------------------------------------------------------------------+<br>//| Global Variables                                                 |<br>//+------------------------------------------------------------------+<br>ulong magic_number;<br>int average_period;<br>ENUM_TIMEFRAMES returns_timeframe;<br>ENUM_RISK_USING risk_indicator;<br>double risk_array[];<br>double risk_ma;<br>double risk_std_dev;<br>double returns_array[];<br>double confidence_level;<br>double VaR = 0;<br>double ES = 0;<br>double array_mean;<br>double array_std_dev;<br>double last_value;<br>int init_trade_hour;<br>int init_trade_min;<br>int end_trade_hour;<br>int end_trade_min;<br>int close_pos_hour;<br>int close_pos_min;<br>bool use_risk_mgmt;<br>double take_profit_pts;<br>double stop_loss_pts;<br>bool use_trades_limit;<br>int number_of_trades;<br>int count_number_of_trades;<br><br>//+------------------------------------------------------------------+<br>//| Inputs                                                           |<br>//+------------------------------------------------------------------+<br>input group &quot;Expert advisor&#39;s settings&quot;<br>input ulong                   input_magic_number         = 1;                 //EA Magic number<br><br>input group &quot;Expert advisor&#39;s setup parameters&quot;<br>input ENUM_RISK_USING         input_risk_indicator       = RISK_VAR;          //Risk indicator calculation<br>input ENUM_TIMEFRAMES         input_returns_timeframe    = PERIOD_M1;         //Returns timeframe<br>input uint                    input_average_period       = 20;                //Risk indicator MA period<br>input ENUM_CONFIDENCE_LEVELS  input_confidence_level     = LEVEL_95;          //Risk indicator confidence level<br>input double                  input_risk_std_dev         = 2;                 //Risk indicator lower Standard Deviation<br>input string                  input_init_trade_time      = &quot;09:05&quot;;           //Time to initialize trades<br>input string                  input_end_trade_time       = &quot;13:00&quot;;           //Time to end trades<br>input string                  input_close_positions      = &quot;17:00&quot;;           //Time to close positions<br><br>input group &quot;Expert advisor&#39;s risk management&quot;<br>input bool                    input_use_risk_mgmt        = false;             //Use Risk Management?<br>input double                  input_take_profit_pts      = 5;                 //Take profit threshold (pts - entry)<br>input double                  input_stop_loss_pts        = 5;                 //Stop loss threshold (entry - pts)<br>input bool                    input_use_trades_limit     = false;             //Use trades limit?<br>input int                     input_number_of_trades     = 1;                 //Number of trades per day</pre><p>And we need to initialize those new parameters correctly at <strong>OnInit() </strong>method:</p><pre>//+------------------------------------------------------------------+<br>//| Initialize parameters                                            |<br>//+------------------------------------------------------------------+<br>bool InitializeParameters()<br>  {<br>   magic_number = input_magic_number;<br><br>   returns_timeframe = input_returns_timeframe;<br><br>   average_period = (int)input_average_period;<br><br>   if(input_risk_std_dev == 0)<br>      return false;<br><br>   if(input_risk_std_dev &gt; 0)<br>      risk_std_dev = input_risk_std_dev;<br>   else<br>      risk_std_dev = -input_risk_std_dev;<br><br>   if(input_confidence_level == LEVEL_95)<br>      confidence_level = .95;<br>   else<br>      confidence_level = .99;<br><br>   use_trades_limit = input_use_trades_limit;<br><br>   if(use_trades_limit)<br>     {<br>      if(number_of_trades &lt;= 0)<br>        {<br>         Print(&quot;[ERROR] When using number of trades limit you must specify a value bigger than zero.&quot;);<br>         return false;<br>        }<br>      else<br>        {<br>         number_of_trades = input_number_of_trades;<br>        }<br>     }<br><br>   use_risk_mgmt = input_use_risk_mgmt;<br><br>   take_profit_pts = MathAbs(input_take_profit_pts);<br><br>   stop_loss_pts = MathAbs(input_stop_loss_pts);<br><br>   if(input_risk_indicator == RISK_ES)<br>      risk_indicator = RISK_ES;<br>   else<br>      risk_indicator = RISK_VAR;<br><br>   if(use_risk_mgmt)<br>     {<br>      if(stop_loss_pts == 0)<br>        {<br>         Print(&quot;[ERROR] When using risk management Stop Loss must be different from 0.&quot;);<br>         return false;<br>        }<br><br>      if(take_profit_pts == 0)<br>        {<br>         Print(&quot;[ERROR] When using risk management Take Profit must be different from 0.&quot;);<br>         return false;<br>        }<br>     }<br><br>   if(!SetTimesOfTrading())<br>     {<br>      return false;<br>     }<br><br>   return true;<br>  }</pre><p>Alright, so now we have our new inputs and every time the trading bot gets initialized we’ll be sure that it does not have wrong parameters such as negative take profit, for example.</p><p>On <em>Part 1</em> we’ve used “m_trade.PositionClose(ticket, -1)” to close open positions when it was time to do it, or there was an inverse trigger (such as you were bought and now there was a sell trigger) or when the risk indicator had the value of its mean. It is fancier to have a method to close open position and make sure that, when a new logic comes up, you need to edit your code in just one part of it. So, here it is:</p><pre>//+------------------------------------------------------------------+<br>//| Close open position                                              |<br>//+------------------------------------------------------------------+<br>void ClosePosition(long ticket)<br>  {<br>   m_trade.PositionClose(ticket, -1);<br>  }</pre><p>And you can just substitute “m_trade.PositionClose(ticket, -1)” to “ClosePosition(ticket)”!</p><p>Another really important method we need is to <strong>NormalizePrice()</strong>. I like to think that when I’m developing a new Expert Advisor it has to be flexible, in order to be used in most assets/tickers/instruments that exists. So, this method will allow the trading bot to automatically calculate prices in the same precision of the asset prices precision.</p><pre>//+------------------------------------------------------------------+<br>//| Normalize prices by Symbol                                       |<br>//+------------------------------------------------------------------+<br>double NormalizePrice(double price)<br>  {<br>   double tick_size = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE);<br>   double ticks_qty = price / tick_size;<br>   int ticks_qty_int = (int) ticks_qty;<br>   return NormalizeDouble(ticks_qty_int * tick_size, _Digits);<br>  }</pre><p>So now let’s talk about the number of trades input. This parameter will be optional, so the user can use it or not. Basically, our bot has, when it is set true, to count every position it is taking at our <em>count_number_of_trades</em> variable. Another thing is to implement a <strong>NewDay()<em> </em></strong>method, which when it returns true, our counter is set to 0.</p><pre>//+------------------------------------------------------------------+<br>//| New Day                                                          |<br>//+------------------------------------------------------------------+<br>bool NewDay()<br>  {<br>   static datetime last_time_day = 0;<br><br>   datetime lastbar_time = (datetime)SeriesInfoInteger(_Symbol, PERIOD_D1, SERIES_LASTBAR_DATE);<br><br>   if(last_time_day == 0)<br>     {<br>      last_time_day = lastbar_time;<br>      return false;<br>     }<br><br>   if(last_time_day != lastbar_time)<br>     {<br>      last_time_day = lastbar_time;<br>      return true;<br>     }<br>   return false;<br>  }</pre><p>And, the first validation at <strong>EACoreExecution()</strong> is:</p><pre>if(NewDay())<br>  {<br>   count_number_of_trades = 0;<br>  }</pre><p><strong>NumberOfTraderExceeded()</strong> method is going to be used as a filter, to check if our trading bot had exceeded the number of trader per day.</p><pre>//+------------------------------------------------------------------+<br>//| Check number of trades filter                                    |<br>//+------------------------------------------------------------------+<br>bool NumberOfTradesExceeded()<br>  {<br>   if(!use_trades_limit)<br>     {<br>      return false;<br>     }<br>   return count_number_of_trades &gt;= number_of_trades;<br>  }</pre><p>Now, talking about the trigger, <strong>NoTriggerLogic() </strong>will be the same, with no changes. On the other side, <strong>BuyTriggerLogic() </strong>and <strong>SellTriggerLogic() </strong>will have new implementations, calling our brand-new method <strong>ExecutionAndRiskManagementLogic()</strong>.</p><pre>//+------------------------------------------------------------------+<br>//| Buy trigger logic                                                |<br>//+------------------------------------------------------------------+<br>void BuyTriggerLogic(long check_positions)<br>  {<br>   if(check_positions == 0) // No open position<br>     {<br>      if(!NumberOfTradesExceeded())<br>         ExecutionAndRiskManagementLogic(TRIGGER_BUY);<br>     }<br>   else // Open position<br>     {<br>      ulong ticket = MathAbs(check_positions);<br><br>      if(check_positions &gt; 0) //Buy open position<br>        {<br><br>        }<br>      else                    //Sell open position<br>        {<br>         ClosePosition(ticket);<br>        }<br>     }<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Sell trigger logic                                               |<br>//+------------------------------------------------------------------+<br>void SellTriggerLogic(long check_positions)<br>  {<br>   if(check_positions == 0) // No open position<br>     {<br>      if(!NumberOfTradesExceeded())<br>         ExecutionAndRiskManagementLogic(TRIGGER_SELL);<br>     }<br>   else // Open position<br>     {<br>      ulong ticket = MathAbs(check_positions);<br><br>      if(check_positions &gt; 0) //Buy open position<br>        {<br>         ClosePosition(ticket);<br>        }<br>      else                    //Sell open position<br>        {<br><br>        }<br>     }<br>  }</pre><p>This last method is a little big when relating to others. It represents all the risk management logic using Stop Loss/Take Profit or not. When the strategy does not use Risk Management, it will trade just like when using, but what will change is the rule to close a trade: it will only happen when an inverse trigger is called or when it is time to close trades on the day. You’ll see that this method adds to <em>count_number_of_trades</em> every time a trade occurs.</p><pre>//+------------------------------------------------------------------+<br>//| Set SL and TP                                                    |<br>//+------------------------------------------------------------------+<br>void ExecutionAndRiskManagementLogic(ENUM_TRIGGERS trigger)<br>  {<br>   long ticket;<br>   double price_open;<br><br>   if(use_risk_mgmt)<br>     {<br>      if(trigger == TRIGGER_BUY)<br>        {<br>         if(m_trade.Buy(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN), _Symbol, 0, 0, 0, NULL))<br>           {<br>            ticket = (long)MathAbs(OpenPositionTicketByMagic());<br>            m_position.InfoDouble(POSITION_PRICE_OPEN, price_open);<br>            if(use_risk_mgmt)<br>              {<br>               double stop_loss_price = NormalizePrice(price_open - stop_loss_pts);<br>               double take_profit_price = NormalizePrice(price_open + take_profit_pts);<br><br>               m_trade.PositionModify(ticket, stop_loss_price, take_profit_price);<br>               Print(&quot;Buy deal done with price of &quot; + DoubleToString(price_open, 3) + &quot;, sl of &quot; + DoubleToString(stop_loss_price, 3) + &quot; and tp of &quot; + DoubleToString(take_profit_price, 3) + &quot; with ticket &quot; + IntegerToString(ticket));<br>              }<br>            else<br>              {<br>               Print(&quot;Buy deal done with price of &quot; + DoubleToString(price_open, 3) + &quot; with ticket &quot; + IntegerToString(ticket));<br>              }<br>            count_number_of_trades++;<br>           }<br>        }<br><br>      if(trigger == TRIGGER_SELL)<br>        {<br>         if(m_trade.Sell(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN), _Symbol, 0, 0, 0, NULL))<br>           {<br>            ticket = (long)MathAbs(OpenPositionTicketByMagic());<br>            m_position.InfoDouble(POSITION_PRICE_OPEN, price_open);<br>            if(use_risk_mgmt)<br>              {<br>               double stop_loss_price = NormalizePrice(price_open + stop_loss_pts);<br>               double take_profit_price = NormalizePrice(price_open - take_profit_pts);<br><br>               m_trade.PositionModify(ticket, stop_loss_price, take_profit_price);<br>               Print(&quot;Sell deal done with price of &quot; + DoubleToString(price_open, 3) + &quot;, sl of &quot; + DoubleToString(stop_loss_price, 3) + &quot; and tp of &quot; + DoubleToString(take_profit_price, 3) + &quot; with ticket &quot; + IntegerToString(ticket));<br>              }<br>            else<br>              {<br>               Print(&quot;Sell deal done with price of &quot; + DoubleToString(price_open, 3) + &quot; with ticket &quot; + IntegerToString(ticket));<br>              }<br>            count_number_of_trades++;<br>           }<br>        }<br>     }<br>   else<br>     {<br>      if(trigger == TRIGGER_BUY)<br>        {<br>         if(m_trade.Buy(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN), _Symbol, 0, 0, 0, NULL))<br>           {<br>            ticket = (long)MathAbs(OpenPositionTicketByMagic());<br>            m_position.InfoDouble(POSITION_PRICE_OPEN, price_open);<br>            Print(&quot;Buy deal done with price of &quot; + DoubleToString(price_open, 3) + &quot; with ticket &quot; + IntegerToString(ticket));<br>            count_number_of_trades++;<br>           }<br>        }<br><br>      if(trigger == TRIGGER_SELL)<br>        {<br>         if(m_trade.Sell(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN), _Symbol, 0, 0, 0, NULL))<br>           {<br>            ticket = (long)MathAbs(OpenPositionTicketByMagic());<br>            m_position.InfoDouble(POSITION_PRICE_OPEN, price_open);<br>            Print(&quot;Sell deal done with price of &quot; + DoubleToString(price_open, 3) + &quot; with ticket &quot; + IntegerToString(ticket));<br>            count_number_of_trades++;<br>           }<br>        }<br>     }<br>  }</pre><p>As you can see, if you’re not using risk management, you’ll just buy or sell on market and wait till it is time to close all position or the inverse trigger comes true. When using risk management, here I’ve implemented to enter on market and then modify my position to have Stop Loss and Take Profit — remember, for selling the Stop Loss will be above entry price, and Take Profit below it.</p><blockquote>You can literally choose the order to set your Stop Loss/Take Profit. There are basically two ways: When buying, you can first take the Symbol’s Ask, calculate based on this the prices of Stop Loss and Take Profit and then send the order with these values. The other way is to open position and then setting the Stop Loss and Take Profit prices. My experience is that, when (and just when) using market orders, it is better to set up the risk prices after you perform your entry because of the possibility to have slippage on it. It could happen that the ask you got was 30 but when performing the trade you have a average price of 31, so the stop loss that should be 26 becomes 25 (bad, huh? A worst Stop Loss that it should be).</blockquote><p>And that’s it! You now have a “more intelligent” trading bot, that manages its own risk based on Stop Loss and Take Profit triggers and, if you want to have more control of it, a limit to number of trades. Did you find it useful?</p><p>Our next step, on the third and final Part of this article, is to develop two types of execution management to our trading bot: <strong>Trailing Stop </strong>and <strong>Breakeven</strong>.</p><p>If you want to see if it is exactly how I’ve implemented it, please visit my GitHub repository with this code:</p><p><a href="https://github.com/angelohomen/BasicExpertAdvisor/blob/main/BasicEA2.mq5">BasicExpertAdvisor/BasicEA2.mq5 at main · angelohomen/BasicExpertAdvisor</a></p><p>So, what do you think about this article? Was it useful? Here I’ve tried to be more objective, what do you think about it? Please, if you have any doubt or feedback, let me know! Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab7c2fdd86f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your first intraday totally automated Quant strategy — Part 1]]></title>
            <link>https://angelohomen.medium.com/your-first-intraday-totally-automated-quant-strategy-part-1-8922b534da43?source=rss-9bbd7c8c5876------2</link>
            <guid isPermaLink="false">https://medium.com/p/8922b534da43</guid>
            <category><![CDATA[expected-shortfall]]></category>
            <category><![CDATA[algotrading]]></category>
            <category><![CDATA[value-at-risk]]></category>
            <category><![CDATA[realtime]]></category>
            <dc:creator><![CDATA[Angelo Homen, CQF]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 11:47:41 GMT</pubDate>
            <atom:updated>2023-03-30T21:45:55.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your first intraday totally automated Quant strategy — Part 1</h3><h3>Notes</h3><p>Algorithmic trading is a powerful weapon capable of literally doing almost anything — and if you thought “[…] anything, less making money” — I’ll not judge you, because this is the most tuff thing to do. Ok, it is not easy, but everyone has this difficult (even big banks) of modelling some algorithm that really is a money printer (I would say this just doesn’t exist, but people insist on trying to make it).</p><blockquote>If your purpose here is just seeing the code, just go to the end of the page, my GitHub repository link is there and you can see everything we’ve done here.</blockquote><p>However, for those of you who are really interested on starting to discover some really cool stuff about algorithmic trading, I’ll make 3 posts developing from begin to end an easy Quant Strategy totally automated. I have to say that no, this trading bot will not be profitable and, for any reason, you shouldn’t use it on your account as a “investment tip”. Instead of this, use the methods, the ideas and logics to build your own trading bot and, who knows, develop your own money printer!</p><h3>Hands on</h3><p>The stack we will use at first moment is just MQL5 IDE/code and MetaTrader5 platform. If you don’t have an account on MetaTrader5 or don’t know any of those IDEs and/or platform, I recommend you to watch some videos on YouTube about it, there are thousands of tutorials.</p><p>At first, I’ll explain the strategy to be implemented. I admit that the strategy is silly, but trust me, the tools that we’ll implement will be useful for a lot of trading bots and even for your own investment analysis (have you ever imagined having a real time Value at Risk/Expected Shortfall calculator for any asset? Cool, huh?).</p><p>The strategy is simple: we’ll be capable to choose which risk indicator we want to use: Value at Risk or Expected Shortfall. This risk indicator will have a moving average of its values and a standard deviation. The idea is to buy the asset when the last value of the indicator is above its average plus standard deviation, because, in theory, there is less risk on buying this asset. The inverse is true, if the last value of the indicator is less than its average minus standard deviation, there is too much risk involved on buying it, so, we’ll sell it — I know, that just has no sense, but I’ve done this for two purposes: to show you buy and sell logic and to give you an idea: what about using this indicator as a filter to your investments? When there is too much risk involved, just do nothing, what do you think?</p><p>So, let’s do it! Begin creating a new Expert Advisor. You will have a code like this:</p><pre>//+------------------------------------------------------------------+<br>//|                                                     BasicEA1.mq5 |<br>//|                                          Angelo R. L. Homen, CQF |<br>//|                                             https://www.mql5.com |<br>//+------------------------------------------------------------------+<br>#property copyright &quot;Angelo R. L. Homen, CQF&quot;<br>#property link      &quot;https://www.mql5.com&quot;<br>#property version   &quot;1.00&quot;<br>//+------------------------------------------------------------------+<br>//| Expert initialization function                                   |<br>//+------------------------------------------------------------------+<br>int OnInit()<br>  {<br>//---<br>   <br>//---<br>   return(INIT_SUCCEEDED);<br>  }<br>//+------------------------------------------------------------------+<br>//| Expert deinitialization function                                 |<br>//+------------------------------------------------------------------+<br>void OnDeinit(const int reason)<br>  {<br>//---<br>   <br>  }<br>//+------------------------------------------------------------------+<br>//| Expert tick function                                             |<br>//+------------------------------------------------------------------+<br>void OnTick()<br>  {<br>//---<br>   <br>  }<br>//+------------------------------------------------------------------+</pre><p>My purpose here is not to teach about MetaTrader5 (yet), so, the only thing you need to know now is that the method <strong>OnInit()</strong> is called when the Expert Advisor has initialized and <strong>OnTick()</strong> is called wherever a trade happen in the configured asset.</p><p>Before implementing the core logic of the Expert Advisor, let’s think about what we need. Basically, talking about the risk indicator, we need the option to choose about Value at Risk or Expected Shortfall. Furthermore, we need the capability of choosing their confidence levels. Just to have more control on the implementation, I’ll make use of “enum” data from MQL5 for the two variables mentioned above and for my strategy triggers (buy trigger, sell trigger or no trigger — those will be important to open positions later). To be more intuitive, I like using “#define” property. I will include the necessary references to the project and a MqlRates variable that I’ll explain later too.</p><pre>//+------------------------------------------------------------------+<br>//|                                                     BasicEA1.mq5 |<br>//|                                          Angelo R. L. Homen, CQF |<br>//|                                             https://www.mql5.com |<br>//+------------------------------------------------------------------+<br>#property copyright &quot;Angelo R. L. Homen, CQF&quot;<br>#property link      &quot;https://www.mql5.com&quot;<br>#property version   &quot;1.00&quot;<br><br>//+------------------------------------------------------------------+<br>//|DEFINES                                                           |<br>//+------------------------------------------------------------------+<br>#define LEVEL_95       10001<br>#define LEVEL_99       10002<br>#define RISK_VAR       10003<br>#define RISK_ES        10004<br>#define TRIGGER_BUY    10005<br>#define TRIGGER_SELL   10006<br>#define NO_TRIGGER     10007<br><br>//+------------------------------------------------------------------+<br>//| References                                                       |<br>//+------------------------------------------------------------------+<br>#include &lt;Trade/Trade.mqh&gt;<br>#include &lt;Trade/PositionInfo.mqh&gt;<br>#include &lt;Trade/SymbolInfo.mqh&gt;<br>#include &lt;Math/Stat/Normal.mqh&gt;<br>CTrade            m_trade;<br>CPositionInfo     m_position;<br>CSymbolInfo       m_symbol;<br><br>//+------------------------------------------------------------------+<br>//| MQL Variables                                                    |<br>//+------------------------------------------------------------------+<br>MqlRates CandleData[];<br>MqlRates daily_bar[];<br><br>//+------------------------------------------------------------------+<br>//|ENUMS                                                             |<br>//+------------------------------------------------------------------+<br>enum ENUM_CONFIDENCE_LEVELS<br>  {<br>   _LEVEL_95 = LEVEL_95,   //95%<br>   _LEVEL_99 = LEVEL_99,   //99%<br>  };<br><br>enum ENUM_RISK_USING<br>  {<br>   _RISK_VAR = RISK_VAR,   //Value at Risk (VaR)<br>   _RISK_ES = RISK_ES,     //Expected Shortfall (ES)<br>  };<br><br>enum ENUM_TRIGGERS<br>  {<br>   _TRIGGER_BUY = TRIGGER_BUY,<br>   _TRIGGER_SELL = TRIGGER_SELL,<br>   _NO_TRIGGER = NO_TRIGGER,<br>  };<br><br>//+------------------------------------------------------------------+<br>//| Inputs                                                           |<br>//+------------------------------------------------------------------+<br>input group &quot;Expert advisor&#39;s settings&quot;<br>input ulong                   input_magic_number         = 1;                 //EA Magic number<br><br>input group &quot;Expert advisor&#39;s setup parameters&quot;<br>input ENUM_RISK_USING         input_risk_indicator       = RISK_VAR;          //Risk indicator calculation<br>input ENUM_TIMEFRAMES         input_returns_timeframe    = PERIOD_M1;         //Returns timeframe<br>input uint                    input_average_period       = 20;                //Risk indicator MA period<br>input ENUM_CONFIDENCE_LEVELS  input_confidence_level     = LEVEL_95;          //Risk indicator confidence level<br>input double                  input_risk_std_dev         = 2;                 //Risk indicator lower Standard Deviation<br>input string                  input_init_trade_time      = &quot;09:05&quot;;           //Time to initialize trades<br>input string                  input_end_trade_time       = &quot;13:00&quot;;           //Time to end trades<br>input string                  input_close_positions      = &quot;17:00&quot;;           //Time to close positions<br><br>//+------------------------------------------------------------------+<br>//| Expert initialization function                                   |<br>//+------------------------------------------------------------------+<br>int OnInit()<br>  {<br>//---<br>   <br>//---<br>   return(INIT_SUCCEEDED);<br>  }<br>//+------------------------------------------------------------------+<br>//| Expert deinitialization function                                 |<br>//+------------------------------------------------------------------+<br>void OnDeinit(const int reason)<br>  {<br>//---<br>   <br>  }<br>//+------------------------------------------------------------------+<br>//| Expert tick function                                             |<br>//+------------------------------------------------------------------+<br>void OnTick()<br>  {<br>//---<br>   <br>  }<br>//+------------------------------------------------------------------+</pre><p>To avoid users wrong choice of parameters, it is fascinating using <strong>OnInit()</strong> to validate all input parameters. For that, let’s first create global variables — between inputs and enums — to be set as input values and create our first method: <strong>InitializeParameters()</strong>.</p><pre>//+------------------------------------------------------------------+<br>//| Global Variables                                                 |<br>//+------------------------------------------------------------------+<br>ulong magic_number;<br>int average_period;<br>ENUM_TIMEFRAMES returns_timeframe;<br>ENUM_RISK_USING risk_indicator;<br>double risk_array[];<br>double risk_ma;<br>double risk_std_dev;<br>double returns_array[];<br>double confidence_level;<br>double VaR = 0;<br>double ES = 0;<br>double array_mean;<br>double array_std_dev;<br>double last_value;<br>int init_trade_hour;<br>int init_trade_min;<br>int end_trade_hour;<br>int end_trade_min;<br>int close_pos_hour;<br>int close_pos_min;</pre><pre>//+------------------------------------------------------------------+<br>//| Initialize parameters                                            |<br>//+------------------------------------------------------------------+<br>bool InitializeParameters()<br>  {<br>   magic_number = input_magic_number;<br><br>   returns_timeframe = input_returns_timeframe;<br><br>   average_period = (int)input_average_period;<br><br>   if(input_risk_std_dev == 0)<br>      return false;<br><br>   if(input_risk_std_dev &gt; 0)<br>      risk_std_dev = input_risk_std_dev;<br>   else<br>      risk_std_dev = -input_risk_std_dev;<br><br>   if(input_confidence_level == LEVEL_95)<br>      confidence_level = .95;<br>   else<br>      confidence_level = .99;<br><br>   if(input_risk_indicator == RISK_ES)<br>      risk_indicator = RISK_ES;<br>   else<br>      risk_indicator = RISK_VAR;<br><br>   if(!SetTimesOfTrading())<br>     {<br>      return false;<br>     }<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time of Trading inputs                                           |<br>//+------------------------------------------------------------------+<br>bool SetTimesOfTrading()<br>  {<br>   string init_trade[];<br>   if(StringSplit(input_init_trade_time, &#39;:&#39;, init_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   init_trade_hour = (int)StringToInteger(init_trade[0]);<br>   init_trade_min = (int)StringToInteger(init_trade[1]);<br><br>   string end_trade[];<br>   if(StringSplit(input_end_trade_time, &#39;:&#39;, end_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   end_trade_hour = (int)StringToInteger(end_trade[0]);<br>   end_trade_min = (int)StringToInteger(end_trade[1]);<br><br>   string close_trade[];<br>   if(StringSplit(input_close_positions, &#39;:&#39;, close_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   close_pos_hour = (int)StringToInteger(close_trade[0]);<br>   close_pos_min = (int)StringToInteger(close_trade[1]);<br><br>   int copied = CopyRates(_Symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime init = daily_bar[0].time + (init_trade_hour * 60 * 60) + (init_trade_min * 60);<br>      datetime end = daily_bar[0].time + (end_trade_hour * 60 * 60) + (end_trade_min * 60);<br>      datetime close = daily_bar[0].time + (close_pos_hour * 60 * 60) + (close_pos_min * 60);<br><br>      if(init &gt; end)<br>        {<br>         Print(&quot;[ERROR] Time to end trades must be bigger than time to init trades.&quot;);<br>         return false;<br>        }<br><br>      if(close &lt; end)<br>        {<br>         Print(&quot;[ERROR] Time to close position must be bigger than time to end trades.&quot;);<br>         return false;<br>        }<br><br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br><br>   return true;<br>  }</pre><p>Calm down! I know it seems like a lot of stuff, but it is not. Just to have a clear view, our code is like this now:</p><pre>//+------------------------------------------------------------------+<br>//|                                                     BasicEA1.mq5 |<br>//|                                          Angelo R. L. Homen, CQF |<br>//|                                             https://www.mql5.com |<br>//+------------------------------------------------------------------+<br>#property copyright &quot;Angelo R. L. Homen, CQF&quot;<br>#property link      &quot;https://www.mql5.com&quot;<br>#property version   &quot;1.00&quot;<br><br>//+------------------------------------------------------------------+<br>//|DEFINES                                                           |<br>//+------------------------------------------------------------------+<br>#define LEVEL_95       10001<br>#define LEVEL_99       10002<br>#define RISK_VAR       10003<br>#define RISK_ES        10004<br>#define TRIGGER_BUY    10005<br>#define TRIGGER_SELL   10006<br>#define NO_TRIGGER     10007<br><br>//+------------------------------------------------------------------+<br>//| References                                                       |<br>//+------------------------------------------------------------------+<br>#include &lt;Trade/Trade.mqh&gt;<br>#include &lt;Trade/PositionInfo.mqh&gt;<br>#include &lt;Trade/SymbolInfo.mqh&gt;<br>#include &lt;Math/Stat/Normal.mqh&gt;<br>CTrade            m_trade;<br>CPositionInfo     m_position;<br>CSymbolInfo       m_symbol;<br><br>//+------------------------------------------------------------------+<br>//| MQL Variables                                                    |<br>//+------------------------------------------------------------------+<br>MqlRates CandleData[];<br>MqlRates daily_bar[];<br><br>//+------------------------------------------------------------------+<br>//|ENUMS                                                             |<br>//+------------------------------------------------------------------+<br>enum ENUM_CONFIDENCE_LEVELS<br>  {<br>   _LEVEL_95 = LEVEL_95,   //95%<br>   _LEVEL_99 = LEVEL_99,   //99%<br>  };<br><br>enum ENUM_RISK_USING<br>  {<br>   _RISK_VAR = RISK_VAR,   //Value at Risk (VaR)<br>   _RISK_ES = RISK_ES,     //Expected Shortfall (ES)<br>  };<br><br>enum ENUM_TRIGGERS<br>  {<br>   _TRIGGER_BUY = TRIGGER_BUY,<br>   _TRIGGER_SELL = TRIGGER_SELL,<br>   _NO_TRIGGER = NO_TRIGGER,<br>  };<br><br>//+------------------------------------------------------------------+<br>//| Inputs                                                           |<br>//+------------------------------------------------------------------+<br>input group &quot;Expert advisor&#39;s settings&quot;<br>input ulong                   input_magic_number         = 1;                 //EA Magic number<br><br>input group &quot;Expert advisor&#39;s setup parameters&quot;<br>input ENUM_RISK_USING         input_risk_indicator       = RISK_VAR;          //Risk indicator calculation<br>input ENUM_TIMEFRAMES         input_returns_timeframe    = PERIOD_M1;         //Returns timeframe<br>input uint                    input_average_period       = 20;                //Risk indicator MA period<br>input ENUM_CONFIDENCE_LEVELS  input_confidence_level     = LEVEL_95;          //Risk indicator confidence level<br>input double                  input_risk_std_dev         = 2;                 //Risk indicator lower Standard Deviation<br>input string                  input_init_trade_time      = &quot;09:05&quot;;           //Time to initialize trades<br>input string                  input_end_trade_time       = &quot;13:00&quot;;           //Time to end trades<br>input string                  input_close_positions      = &quot;17:00&quot;;           //Time to close positions<br><br>//+------------------------------------------------------------------+<br>//| Expert initialization function                                   |<br>//+------------------------------------------------------------------+<br>int OnInit()<br>  {<br>//---<br>   if(!InitializeParameters())<br>      return(INIT_PARAMETERS_INCORRECT);<br>//---<br>   return(INIT_SUCCEEDED);<br>  }<br>//+------------------------------------------------------------------+<br>//| Expert deinitialization function                                 |<br>//+------------------------------------------------------------------+<br>void OnDeinit(const int reason)<br>  {<br>//---<br><br>  }<br>//+------------------------------------------------------------------+<br>//| Expert tick function                                             |<br>//+------------------------------------------------------------------+<br>void OnTick()<br>  {<br>//---<br><br>  }<br><br>//+------------------------------------------------------------------+<br>//| Initialize parameters                                            |<br>//+------------------------------------------------------------------+<br>bool InitializeParameters()<br>  {<br>   magic_number = input_magic_number;<br><br>   returns_timeframe = input_returns_timeframe;<br><br>   average_period = (int)input_average_period;<br><br>   if(input_risk_std_dev == 0)<br>      return false;<br><br>   if(input_risk_std_dev &gt; 0)<br>      risk_std_dev = input_risk_std_dev;<br>   else<br>      risk_std_dev = -input_risk_std_dev;<br><br>   if(input_confidence_level == LEVEL_95)<br>      confidence_level = .95;<br>   else<br>      confidence_level = .99;<br><br>   if(input_risk_indicator == RISK_ES)<br>      risk_indicator = RISK_ES;<br>   else<br>      risk_indicator = RISK_VAR;<br><br>   if(!SetTimesOfTrading())<br>     {<br>      return false;<br>     }<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time of Trading inputs                                           |<br>//+------------------------------------------------------------------+<br>bool SetTimesOfTrading()<br>  {<br>   string init_trade[];<br>   if(StringSplit(input_init_trade_time, &#39;:&#39;, init_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   init_trade_hour = (int)StringToInteger(init_trade[0]);<br>   init_trade_min = (int)StringToInteger(init_trade[1]);<br><br>   string end_trade[];<br>   if(StringSplit(input_end_trade_time, &#39;:&#39;, end_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   end_trade_hour = (int)StringToInteger(end_trade[0]);<br>   end_trade_min = (int)StringToInteger(end_trade[1]);<br><br>   string close_trade[];<br>   if(StringSplit(input_close_positions, &#39;:&#39;, close_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   close_pos_hour = (int)StringToInteger(close_trade[0]);<br>   close_pos_min = (int)StringToInteger(close_trade[1]);<br><br>   int copied = CopyRates(_Symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime init = daily_bar[0].time + (init_trade_hour * 60 * 60) + (init_trade_min * 60);<br>      datetime end = daily_bar[0].time + (end_trade_hour * 60 * 60) + (end_trade_min * 60);<br>      datetime close = daily_bar[0].time + (close_pos_hour * 60 * 60) + (close_pos_min * 60);<br><br>      if(init &gt; end)<br>        {<br>         Print(&quot;[ERROR] Time to end trades must be bigger than time to init trades.&quot;);<br>         return false;<br>        }<br><br>      if(close &lt; end)<br>        {<br>         Print(&quot;[ERROR] Time to close position must be bigger than time to end trades.&quot;);<br>         return false;<br>        }<br><br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br><br>   return true;<br>  }<br>//+------------------------------------------------------------------+</pre><p>The <strong>InitializeParameters()</strong> method is used to assign global variables as the user inputs and check if there is any inconsistency on it, like a null (or 0) standard deviation (doesn’t make sense to have entries on risk indicator average). Another method we’ve implemented was <strong>SetTimesOfTrading()</strong>, taking the user inputs and verifying if it is trying to close trades before opening it, as an example.</p><p>To finish <strong>OnInit()</strong> method, we just need to initialize all arrays we’re going to use. For that, we’ll create the <strong>InitializeArrays()</strong> method and implement it at <strong>OnInit()</strong>. Other important thing is to set the Expert Advisor magic number, that is like an ID for the trading bot.</p><pre>//+------------------------------------------------------------------+<br>//| Initialize arrays                                                |<br>//+------------------------------------------------------------------+<br>bool InitializeArrays()<br>  {<br>   if(!ArraySetAsSeries(CandleData, true))<br>      return false;<br><br>   if(!ArraySetAsSeries(daily_bar, true))<br>      return false;<br><br>   if(ArrayResize(returns_array, average_period) == -1)<br>     {<br>      Print(&quot;[ERRO] Array &#39;returns_array&#39; ressize error.&quot;);<br>      return (false);<br>     }<br><br>   if(ArrayResize(risk_array, 0) == -1)<br>     {<br>      Print(&quot;[ERRO] Array &#39;risk_array&#39; ressize error.&quot;);<br>      return false;<br>     }<br><br>   return true;<br>  }</pre><pre>//+------------------------------------------------------------------+<br>//| Expert initialization function                                   |<br>//+------------------------------------------------------------------+<br>int OnInit()<br>  {<br>   if(!InitializeParameters())<br>      return(INIT_PARAMETERS_INCORRECT);<br><br>   if(!InitializeArrays())<br>      return(INIT_FAILED);<br><br>   m_trade.SetExpertMagicNumber(magic_number);<br><br>   return(INIT_SUCCEEDED);<br>  }</pre><p>So now we have finished all verifications on Expert Advisor’s initialization, well done! We’re going to need two more methods involving time on our trading bot. The <strong>TimeToTrade() </strong>method will check if the current time is between the allowed time to trade, because this is going to be an intraday strategy. <strong>TimeToClosePositions()</strong> is the specific time to close all open orders from the day.</p><pre>//+------------------------------------------------------------------+<br>//| Time to trade                                                    |<br>//+------------------------------------------------------------------+<br>bool TimeToTrade()<br>  {<br>   int copied = CopyRates(_Symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime init = daily_bar[0].time + (init_trade_hour * 60 * 60) + (init_trade_min * 60);<br>      datetime end = daily_bar[0].time + (end_trade_hour * 60 * 60) + (end_trade_min * 60);<br><br>      datetime now = TimeTradeServer();<br><br>      if(now &gt;= init &amp;&amp; now &lt; end)<br>        {<br>         return (true);<br>        }<br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br>   return false;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time to close positions                                          |<br>//+------------------------------------------------------------------+<br>bool TimeToClosePositions()<br>  {<br>   int copied = CopyRates(_Symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime close_time = daily_bar[0].time + (close_pos_hour * 60 * 60) + (close_pos_min * 60);<br>      datetime now = TimeTradeServer();<br><br>      if(now &gt;= close_time)<br>        {<br>         return (true);<br>        }<br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br>   return false;<br>  }</pre><p>Another useful method to avoid lots of unnecessary calculations is the <strong>NewCandle()</strong>. Instead of handling your trading logic every time the <strong>OnTick()</strong> method is invoked, you can handle it using the <strong>NewCandle()</strong>.</p><pre>//+------------------------------------------------------------------+<br>//| New Candle                                                       |<br>//+------------------------------------------------------------------+<br>bool NewCandle()<br>  {<br>   static datetime last_time_day = 0;<br><br>   datetime lastbar_time = (datetime)SeriesInfoInteger(_Symbol, returns_timeframe, SERIES_LASTBAR_DATE);<br><br>   if(last_time_day == 0)<br>     {<br>      last_time_day = lastbar_time;<br>      return false;<br>     }<br><br>   if(last_time_day != lastbar_time)<br>     {<br>      last_time_day = lastbar_time;<br>      return true;<br>     }<br>   return false;<br>  }</pre><p>So, finally, let’s go to the core execution of our Expert Advisor! The <strong>CalculateStatistics()</strong> method will make all Risk Indicator calculations and generate, every <em>New Candle,</em> a value. Once this value is generated, it will be placed into an array with the dimension that the user choose of the moving average period. The rule is that when it is a positive candle (its closing price is bigger than its open price), then we will calculate the returns as <em>(CandleHigh — CandleLow)/(CandleHigh)</em> and, if it is a negative candle, the returns will be calculated as <em>(CandleLow — CandleHigh)/(CandleLow)</em>. So, let’s build the <strong>CalculateStatistics()</strong> method and the <strong>RiskArrayConstruction()</strong> method:</p><pre>//+------------------------------------------------------------------+<br>//| Calculate statisics                                              |<br>//+------------------------------------------------------------------+<br>bool CalculateStatistics()<br>  {<br>   if(CopyRates(_Symbol, returns_timeframe, 0, average_period, CandleData) &lt; average_period)<br>     {<br>      Print(&quot;[ERROR] Error with copy rates.&quot;);<br>      return false;<br>     }<br><br>   int error_code = 0;<br>   int ES_count = 0;<br>   double ES_sum = 0;<br>   double returns_sum = 0;<br>   double std_dev_sum = 0;<br>   double returns_avg = 0;<br>   double returns_std_dev = 0;<br>   uint positive_count = 0;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>     {<br>      if(CandleData[i].close - CandleData[i].open &gt; 0)<br>        {<br>         returns_array[i] = (CandleData[i].high - CandleData[i].low)/CandleData[i].high;<br>         returns_sum += returns_array[i];<br>         positive_count++;<br>        }<br>      else<br>        {<br>         returns_array[i] = (CandleData[i].low - CandleData[i].high)/CandleData[i].low;<br>         returns_sum += returns_array[i];<br>        }<br>     }<br><br>   returns_avg = returns_sum / average_period;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>      std_dev_sum += MathPow(returns_array[i] - returns_avg, 2);<br><br>   returns_std_dev = MathSqrt(std_dev_sum/(average_period-1));<br><br>   VaR = MathQuantileNormal(1 - confidence_level, returns_avg, returns_std_dev, error_code);<br><br>   for(int i = 0; i &lt; ArraySize(returns_array); i++)<br>     {<br>      if(returns_array[i] &lt;= VaR)<br>        {<br>         ES_sum += returns_array[i];<br>         ES_count++;<br>        }<br>     }<br><br>   if(risk_indicator == RISK_ES)<br>     {<br>      if(ES_count &gt; 0)<br>        {<br>         ES = ES_sum/ES_count;<br>         RiskArrayConstruction(ES);<br>        }<br>      else<br>        {<br>         VaR = NULL;<br>         ES = NULL;<br>         return false;<br>        }<br>     }<br><br>   if(risk_indicator == RISK_VAR)<br>     {<br>      RiskArrayConstruction(VaR);<br>     }<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Risk array construction                                          |<br>//+------------------------------------------------------------------+<br>void RiskArrayConstruction(double value)<br>  {<br>   if(ArraySize(risk_array) &lt; average_period)<br>     {<br>      if(ArrayResize(risk_array, ArraySize(risk_array) + 1) == -1)<br>        {<br>         Print(&quot;[ERRO] Array &#39;risk_array&#39; ressize error.&quot;);<br>        }<br>     }<br><br>   int risk_array_size = ArraySize(risk_array);<br><br>   for(int i = risk_array_size - 1; i &gt;= 0; i--)<br>     {<br>      if(i == 0)<br>        {<br>         risk_array[i] = value;<br>         continue;<br>        }<br><br>      if(i &lt; risk_array_size)<br>        {<br>         risk_array[i] = risk_array[i - 1];<br>        }<br>     }<br>  }</pre><p>The <strong>RecalculateRiskArray()</strong> is going to be called every time a <em>New Candle</em> shows in, and its purpose is to fill our global variables with updated values.</p><pre>//+------------------------------------------------------------------+<br>//| Recalculate risk array                                           |<br>//+------------------------------------------------------------------+<br>void RecalculateRiskArray()<br>  {<br>   array_mean = 0;<br>   array_std_dev = 0;<br>   last_value = risk_array[0];<br><br>   double array_sum = 0;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>     {<br>      array_sum += risk_array[i];<br>     }<br><br>   array_mean = array_sum/average_period;<br><br>   double std_dev_sum = 0;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>      std_dev_sum += MathPow(risk_array[i] - array_mean, 2);<br><br>   array_std_dev = MathSqrt(std_dev_sum/(average_period - 1));<br>  }</pre><p>Now, let’s build our buy and sell triggers: remember, when the last risk indicator value is above its average plus standard deviation, we will buy. If it is less than average minus standard deviation, we’ll sell.</p><pre>//+------------------------------------------------------------------+<br>//| VaR/ES with bigger risk                                          |<br>//+------------------------------------------------------------------+<br>bool RiskIndicatorBelowStdDev()<br>  {<br>   if(last_value &lt; array_mean + array_std_dev * risk_std_dev)<br>     {<br>      return true;<br>     }<br><br>   return false;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| VaR/ES with less risk                                            |<br>//+------------------------------------------------------------------+<br>bool RiskIndicatorAboveStdDev()<br>  {<br>   if(last_value &gt; array_mean + array_std_dev * risk_std_dev)<br>     {<br>      return true;<br>     }<br><br>   return false;<br>  }</pre><p>Just to make sure we’re on the same page, our code seems like this:</p><pre>//+------------------------------------------------------------------+<br>//|                                                     BasicEA1.mq5 |<br>//|                                          Angelo R. L. Homen, CQF |<br>//|                                             https://www.mql5.com |<br>//+------------------------------------------------------------------+<br>#property copyright &quot;Angelo R. L. Homen, CQF&quot;<br>#property link      &quot;https://www.mql5.com&quot;<br>#property version   &quot;1.00&quot;<br><br>//+------------------------------------------------------------------+<br>//|DEFINES                                                           |<br>//+------------------------------------------------------------------+<br>#define LEVEL_95       10001<br>#define LEVEL_99       10002<br>#define RISK_VAR       10003<br>#define RISK_ES        10004<br>#define TRIGGER_BUY    10005<br>#define TRIGGER_SELL   10006<br>#define NO_TRIGGER     10007<br><br>//+------------------------------------------------------------------+<br>//| References                                                       |<br>//+------------------------------------------------------------------+<br>#include &lt;Trade/Trade.mqh&gt;<br>#include &lt;Trade/PositionInfo.mqh&gt;<br>#include &lt;Trade/SymbolInfo.mqh&gt;<br>#include &lt;Math/Stat/Normal.mqh&gt;<br>CTrade            m_trade;<br>CPositionInfo     m_position;<br>CSymbolInfo       m_symbol;<br><br>//+------------------------------------------------------------------+<br>//| MQL Variables                                                    |<br>//+------------------------------------------------------------------+<br>MqlRates CandleData[];<br>MqlRates daily_bar[];<br><br>//+------------------------------------------------------------------+<br>//|ENUMS                                                             |<br>//+------------------------------------------------------------------+<br>enum ENUM_CONFIDENCE_LEVELS<br>  {<br>   _LEVEL_95 = LEVEL_95,   //95%<br>   _LEVEL_99 = LEVEL_99,   //99%<br>  };<br><br>enum ENUM_RISK_USING<br>  {<br>   _RISK_VAR = RISK_VAR,   //Value at Risk (VaR)<br>   _RISK_ES = RISK_ES,     //Expected Shortfall (ES)<br>  };<br><br>enum ENUM_TRIGGERS<br>  {<br>   _TRIGGER_BUY = TRIGGER_BUY,<br>   _TRIGGER_SELL = TRIGGER_SELL,<br>   _NO_TRIGGER = NO_TRIGGER,<br>  };<br>  <br>//+------------------------------------------------------------------+<br>//| Global Variables                                                 |<br>//+------------------------------------------------------------------+<br>ulong magic_number;<br>int average_period;<br>ENUM_TIMEFRAMES returns_timeframe;<br>ENUM_RISK_USING risk_indicator;<br>double risk_array[];<br>double risk_ma;<br>double risk_std_dev;<br>double returns_array[];<br>double confidence_level;<br>double VaR = 0;<br>double ES = 0;<br>double array_mean;<br>double array_std_dev;<br>double last_value;<br>int init_trade_hour;<br>int init_trade_min;<br>int end_trade_hour;<br>int end_trade_min;<br>int close_pos_hour;<br>int close_pos_min;<br><br>//+------------------------------------------------------------------+<br>//| Inputs                                                           |<br>//+------------------------------------------------------------------+<br>input group &quot;Expert advisor&#39;s settings&quot;<br>input ulong                   input_magic_number         = 1;                 //EA Magic number<br><br>input group &quot;Expert advisor&#39;s setup parameters&quot;<br>input ENUM_RISK_USING         input_risk_indicator       = RISK_VAR;          //Risk indicator calculation<br>input ENUM_TIMEFRAMES         input_returns_timeframe    = PERIOD_M1;         //Returns timeframe<br>input uint                    input_average_period       = 20;                //Risk indicator MA period<br>input ENUM_CONFIDENCE_LEVELS  input_confidence_level     = LEVEL_95;          //Risk indicator confidence level<br>input double                  input_risk_std_dev         = 2;                 //Risk indicator lower Standard Deviation<br>input string                  input_init_trade_time      = &quot;09:05&quot;;           //Time to initialize trades<br>input string                  input_end_trade_time       = &quot;13:00&quot;;           //Time to end trades<br>input string                  input_close_positions      = &quot;17:00&quot;;           //Time to close positions<br><br>//+------------------------------------------------------------------+<br>//| Expert initialization function                                   |<br>//+------------------------------------------------------------------+<br>int OnInit()<br>  {<br>   if(!InitializeParameters())<br>      return(INIT_PARAMETERS_INCORRECT);<br><br>   if(!InitializeArrays())<br>      return(INIT_FAILED);<br><br>   m_trade.SetExpertMagicNumber(magic_number);<br><br>   return(INIT_SUCCEEDED);<br>  }<br>//+------------------------------------------------------------------+<br>//| Expert deinitialization function                                 |<br>//+------------------------------------------------------------------+<br>void OnDeinit(const int reason)<br>  {<br>//---<br><br>  }<br>//+------------------------------------------------------------------+<br>//| Expert tick function                                             |<br>//+------------------------------------------------------------------+<br>void OnTick()<br>  {<br>//---<br><br>  }<br>  <br>//+------------------------------------------------------------------+<br>//| Recalculate risk array                                           |<br>//+------------------------------------------------------------------+<br>void RecalculateRiskArray()<br>  {<br>   array_mean = 0;<br>   array_std_dev = 0;<br>   last_value = risk_array[0];<br><br>   double array_sum = 0;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>     {<br>      array_sum += risk_array[i];<br>     }<br><br>   array_mean = array_sum/average_period;<br><br>   double std_dev_sum = 0;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>      std_dev_sum += MathPow(risk_array[i] - array_mean, 2);<br><br>   array_std_dev = MathSqrt(std_dev_sum/(average_period - 1));<br>  }<br><br>//+------------------------------------------------------------------+<br>//| VaR/ES with bigger risk                                          |<br>//+------------------------------------------------------------------+<br>bool RiskIndicatorBelowStdDev()<br>  {<br>   if(last_value &lt; array_mean + array_std_dev * risk_std_dev)<br>     {<br>      return true;<br>     }<br><br>   return false;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| VaR/ES with less risk                                            |<br>//+------------------------------------------------------------------+<br>bool RiskIndicatorAboveStdDev()<br>  {<br>   if(last_value &gt; array_mean + array_std_dev * risk_std_dev)<br>     {<br>      return true;<br>     }<br><br>   return false;<br>  }<br>  <br>//+------------------------------------------------------------------+<br>//| Calculate statisics                                              |<br>//+------------------------------------------------------------------+<br>bool CalculateStatistics()<br>  {<br>   if(CopyRates(_Symbol, returns_timeframe, 0, average_period, CandleData) &lt; average_period)<br>     {<br>      Print(&quot;[ERROR] Error with copy rates.&quot;);<br>      return false;<br>     }<br><br>   int error_code = 0;<br>   int ES_count = 0;<br>   double ES_sum = 0;<br>   double returns_sum = 0;<br>   double std_dev_sum = 0;<br>   double returns_avg = 0;<br>   double returns_std_dev = 0;<br>   uint positive_count = 0;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>     {<br>      if(CandleData[i].close - CandleData[i].open &gt; 0)<br>        {<br>         returns_array[i] = (CandleData[i].high - CandleData[i].low)/CandleData[i].high;<br>         returns_sum += returns_array[i];<br>         positive_count++;<br>        }<br>      else<br>        {<br>         returns_array[i] = (CandleData[i].low - CandleData[i].high)/CandleData[i].low;<br>         returns_sum += returns_array[i];<br>        }<br>     }<br><br>   returns_avg = returns_sum / average_period;<br><br>   for(int i = 0; i &lt; average_period; i++)<br>      std_dev_sum += MathPow(returns_array[i] - returns_avg, 2);<br><br>   returns_std_dev = MathSqrt(std_dev_sum/(average_period-1));<br><br>   VaR = MathQuantileNormal(1 - confidence_level, returns_avg, returns_std_dev, error_code);<br><br>   for(int i = 0; i &lt; ArraySize(returns_array); i++)<br>     {<br>      if(returns_array[i] &lt;= VaR)<br>        {<br>         ES_sum += returns_array[i];<br>         ES_count++;<br>        }<br>     }<br><br>   if(risk_indicator == RISK_ES)<br>     {<br>      if(ES_count &gt; 0)<br>        {<br>         ES = ES_sum/ES_count;<br>         RiskArrayConstruction(ES);<br>        }<br>      else<br>        {<br>         VaR = NULL;<br>         ES = NULL;<br>         return false;<br>        }<br>     }<br><br>   if(risk_indicator == RISK_VAR)<br>     {<br>      RiskArrayConstruction(VaR);<br>     }<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Risk array construction                                          |<br>//+------------------------------------------------------------------+<br>void RiskArrayConstruction(double value)<br>  {<br>   if(ArraySize(risk_array) &lt; average_period)<br>     {<br>      if(ArrayResize(risk_array, ArraySize(risk_array) + 1) == -1)<br>        {<br>         Print(&quot;[ERRO] Array &#39;risk_array&#39; ressize error.&quot;);<br>        }<br>     }<br><br>   int risk_array_size = ArraySize(risk_array);<br><br>   for(int i = risk_array_size - 1; i &gt;= 0; i--)<br>     {<br>      if(i == 0)<br>        {<br>         risk_array[i] = value;<br>         continue;<br>        }<br><br>      if(i &lt; risk_array_size)<br>        {<br>         risk_array[i] = risk_array[i - 1];<br>        }<br>     }<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Initialize parameters                                            |<br>//+------------------------------------------------------------------+<br>bool InitializeParameters()<br>  {<br>   magic_number = input_magic_number;<br><br>   returns_timeframe = input_returns_timeframe;<br><br>   average_period = (int)input_average_period;<br><br>   if(input_risk_std_dev == 0)<br>      return false;<br><br>   if(input_risk_std_dev &gt; 0)<br>      risk_std_dev = input_risk_std_dev;<br>   else<br>      risk_std_dev = -input_risk_std_dev;<br><br>   if(input_confidence_level == LEVEL_95)<br>      confidence_level = .95;<br>   else<br>      confidence_level = .99;<br><br>   if(input_risk_indicator == RISK_ES)<br>      risk_indicator = RISK_ES;<br>   else<br>      risk_indicator = RISK_VAR;<br><br>   if(!SetTimesOfTrading())<br>     {<br>      return false;<br>     }<br><br>   return true;<br>  }<br>  <br>//+------------------------------------------------------------------+<br>//| Initialize arrays                                                |<br>//+------------------------------------------------------------------+<br>bool InitializeArrays()<br>  {<br>   if(!ArraySetAsSeries(CandleData, true))<br>      return false;<br><br>   if(!ArraySetAsSeries(daily_bar, true))<br>      return false;<br><br>   if(ArrayResize(returns_array, average_period) == -1)<br>     {<br>      Print(&quot;[ERRO] Array &#39;returns_array&#39; ressize error.&quot;);<br>      return (false);<br>     }<br><br>   if(ArrayResize(risk_array, 0) == -1)<br>     {<br>      Print(&quot;[ERRO] Array &#39;risk_array&#39; ressize error.&quot;);<br>      return false;<br>     }<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time of Trading inputs                                           |<br>//+------------------------------------------------------------------+<br>bool SetTimesOfTrading()<br>  {<br>   string init_trade[];<br>   if(StringSplit(input_init_trade_time, &#39;:&#39;, init_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   init_trade_hour = (int)StringToInteger(init_trade[0]);<br>   init_trade_min = (int)StringToInteger(init_trade[1]);<br><br>   string end_trade[];<br>   if(StringSplit(input_end_trade_time, &#39;:&#39;, end_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   end_trade_hour = (int)StringToInteger(end_trade[0]);<br>   end_trade_min = (int)StringToInteger(end_trade[1]);<br><br>   string close_trade[];<br>   if(StringSplit(input_close_positions, &#39;:&#39;, close_trade) &lt; 2)<br>     {<br>      return false;<br>     }<br>   close_pos_hour = (int)StringToInteger(close_trade[0]);<br>   close_pos_min = (int)StringToInteger(close_trade[1]);<br><br>   int copied = CopyRates(_Symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime init = daily_bar[0].time + (init_trade_hour * 60 * 60) + (init_trade_min * 60);<br>      datetime end = daily_bar[0].time + (end_trade_hour * 60 * 60) + (end_trade_min * 60);<br>      datetime close = daily_bar[0].time + (close_pos_hour * 60 * 60) + (close_pos_min * 60);<br><br>      if(init &gt; end)<br>        {<br>         Print(&quot;[ERROR] Time to end trades must be bigger than time to init trades.&quot;);<br>         return false;<br>        }<br><br>      if(close &lt; end)<br>        {<br>         Print(&quot;[ERROR] Time to close position must be bigger than time to end trades.&quot;);<br>         return false;<br>        }<br><br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br><br>   return true;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time to trade                                                    |<br>//+------------------------------------------------------------------+<br>bool TimeToTrade()<br>  {<br>   int copied = CopyRates(_Symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime init = daily_bar[0].time + (init_trade_hour * 60 * 60) + (init_trade_min * 60);<br>      datetime end = daily_bar[0].time + (end_trade_hour * 60 * 60) + (end_trade_min * 60);<br><br>      datetime now = TimeTradeServer();<br><br>      if(now &gt;= init &amp;&amp; now &lt; end)<br>        {<br>         return (true);<br>        }<br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br>   return false;<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Time to close positions                                          |<br>//+------------------------------------------------------------------+<br>bool TimeToClosePositions()<br>  {<br>   int copied = CopyRates(_Symbol, PERIOD_D1, 0, 1, daily_bar);<br>   if(copied == 1)<br>     {<br>      datetime close_time = daily_bar[0].time + (close_pos_hour * 60 * 60) + (close_pos_min * 60);<br>      datetime now = TimeTradeServer();<br><br>      if(now &gt;= close_time)<br>        {<br>         return (true);<br>        }<br>     }<br>   else<br>     {<br>      Print(&quot;[ERROR] Error with copy rates &#39;daily_bar&#39;&quot;);<br>      return false;<br>     }<br>   return false;<br>  }</pre><p>Our trading bot don’t want to make more than one trade each time, and it is very important to control it, because it can literally: make you very rich or — with 99.99999999% of chance — make you lose all your money. To check if you have open orders, we’ll develop the <strong>OpenPositionTicketByMagic()</strong> method. Its return is a <em>long</em>. When it is 0, there are no open positions. When it is negative, there is a sell open order, and its absolute value is its ticket (like an order ID). When it is positive, there is a buy open order.</p><pre>//+------------------------------------------------------------------+<br>//| Open positions by magic                                          |<br>//+------------------------------------------------------------------+<br>long OpenPositionTicketByMagic()<br>  {<br>   if(m_position.SelectByMagic(_Symbol, magic_number))<br>     {<br>      long position_type;<br>      m_position.InfoInteger(POSITION_TYPE, position_type);<br>      if(position_type == POSITION_TYPE_BUY)<br>         return (long)m_position.Ticket();<br>      else<br>         return -(long)m_position.Ticket();<br>     }<br><br>   return 0;<br>  }</pre><p>Now, we just need 4 more auxiliary methods (finally). One method is the <strong>TriggerActions()</strong>, used to indicate if there was any trigger to the strategy.</p><pre>//+------------------------------------------------------------------+<br>//| Trigger actions                                                  |<br>//+------------------------------------------------------------------+<br>ENUM_TRIGGERS TriggerActions()<br>  {<br>   if(ArraySize(risk_array) &lt; average_period)<br>     {<br>      return NO_TRIGGER;<br>     }<br><br>   RecalculateRiskArray();<br><br>   if(RiskIndicatorAboveStdDev())<br>     {<br>      return TRIGGER_BUY;<br>     }<br><br>   if(RiskIndicatorBelowStdDev())<br>     {<br>      return TRIGGER_SELL;<br>     }<br><br>   return NO_TRIGGER;<br>  }</pre><p>And, to finish, the other three methods are <strong>BuyTriggerLogic()</strong>, <strong>SellTriggerLogic()</strong> and <strong>NoTriggerLogic()</strong>, with, I would say, very intuitive names.</p><pre>//+------------------------------------------------------------------+<br>//| Buy trigger logic                                                |<br>//+------------------------------------------------------------------+<br>void BuyTriggerLogic(long check_positions)<br>  {<br>   if(check_positions == 0) // No open position<br>     {<br>      if(m_trade.Buy(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN), _Symbol, 0, 0, 0, NULL))<br>        {<br>         Print(&quot;Buy deal done.&quot;);<br>        }<br>     }<br>   else // Open position<br>     {<br>      ulong ticket = MathAbs(check_positions);<br><br>      if(check_positions &gt; 0) //Buy open position<br>        {<br><br>        }<br>      else                    //Sell open position<br>        {<br>         m_trade.PositionClose(ticket, -1);<br>        }<br>     }<br>  }<br><br>//+------------------------------------------------------------------+<br>//| Sell trigger logic                                               |<br>//+------------------------------------------------------------------+<br>void SellTriggerLogic(long check_positions)<br>  {<br>   if(check_positions == 0) // No open position<br>     {<br>      if(m_trade.Sell(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN), _Symbol, 0, 0, 0, NULL))<br>        {<br>         Print(&quot;Sell deal done.&quot;);<br>        }<br>     }<br>   else // Open position<br>     {<br>      ulong ticket = MathAbs(check_positions);<br><br>      if(check_positions &gt; 0) //Buy open position<br>        {<br>         m_trade.PositionClose(ticket, -1);<br>        }<br>      else                    //Sell open position<br>        {<br><br>        }<br>     }<br>  }<br><br>//+------------------------------------------------------------------+<br>//| No trigger logic                                                 |<br>//+------------------------------------------------------------------+<br>void NoTriggerLogic(long check_positions)<br>  {<br>   if(check_positions == 0) // No open position<br>     {<br><br>     }<br>   else // Open position<br>     {<br>      ulong ticket = MathAbs(check_positions);<br><br>      if(check_positions &gt; 0)<br>        {<br>         if(last_value &lt;= array_mean)<br>           {<br>            m_trade.PositionClose(ticket, -1);<br>           }<br>        }<br><br>      if(check_positions &lt; 0)<br>        {<br>         if(last_value &gt;= array_mean)<br>           {<br>            m_trade.PositionClose(ticket, -1);<br>           }<br>        }<br>     }<br>  }</pre><p>To implement our core logic, here it is, the main method of our trading bot:</p><pre>//+------------------------------------------------------------------+<br>//| Core logic                                                       |<br>//+------------------------------------------------------------------+<br>void EACoreExecution()<br>  {<br>   long check_positions = OpenPositionTicketByMagic();<br><br>   if(TimeToTrade())<br>     {<br>      if(NewCandle())<br>        {<br>         if(!CalculateStatistics())<br>            return;<br><br>         switch(TriggerActions())<br>           {<br>            case TRIGGER_BUY:<br>               BuyTriggerLogic(check_positions);<br>               break;<br>            case TRIGGER_SELL:<br>               SellTriggerLogic(check_positions);<br>               break;<br>            default:<br>               NoTriggerLogic(check_positions);<br>               break;<br>           }<br>        }<br>     }<br><br>   if(TimeToClosePositions())<br>     {<br>      if(check_positions != 0)<br>        {<br>         ulong ticket = MathAbs(check_positions);<br>         m_trade.PositionClose(ticket, -1);<br>        }<br>     }<br>  }</pre><p>Call the <strong>EACoreExecution()</strong> at <strong>OnTick()</strong> method and here we go, your first Quant Expert Advisor is done!</p><p>If you want to see if it is exactly how I’ve implemented it, please visit my GitHub repository with this code:</p><p><a href="https://github.com/angelohomen/BasicExpertAdvisor/blob/main/BasicEA1.mq5">BasicExpertAdvisor/BasicEA1.mq5 at main · angelohomen/BasicExpertAdvisor</a></p><p>So, what do you think about this article? Was it useful? Did you think it was too large? Please, if you have any doubt or feedback, let me know! Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8922b534da43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>