<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3581778232347889594</id><updated>2019-02-06T15:10:10.122+01:00</updated><category term="Default"/><category term="mql4"/><category term="MetaTrader4"/><category term="advisory"/><category term="algotrading"/><category term="financials"/><category term="planning"/><category term="Coding"/><category term="Indicators"/><category term="Investing"/><category term="Correlation"/><category term="Darwinex"/><category term="Donchian"/><category term="Expert Advisor"/><category term="Expert advisers"/><category term="FX"/><category term="Hedging"/><category term="Permanent portfolio"/><category term="Trading"/><category term="Video"/><title type='text'>IlanTree</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>29</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-4765790382599200765</id><published>2019-02-05T11:18:00.000+01:00</published><updated>2019-02-06T14:18:47.618+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="algotrading"/><category scheme="http://www.blogger.com/atom/ns#" term="MetaTrader4"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><title type='text'>Mutual Exclusion (Mutex) Implementation in MQL4</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://4.bp.blogspot.com/-6QHjJgWaLo0/XFlj-xvsKnI/AAAAAAAA9v4/RBfG2_QRjLwFqp2v2R-Ra_UpxtLikIJKQCLcBGAs/s1600/27767467616_b686ba5900_k%2B%25281%2529.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;900&quot; data-original-width=&quot;1600&quot; height=&quot;180&quot; src=&quot;https://4.bp.blogspot.com/-6QHjJgWaLo0/XFlj-xvsKnI/AAAAAAAA9v4/RBfG2_QRjLwFqp2v2R-Ra_UpxtLikIJKQCLcBGAs/s320/27767467616_b686ba5900_k%2B%25281%2529.jpg&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;h2&gt;&lt;/h2&gt;&lt;h2&gt;Introduction&lt;/h2&gt;In computer science, &lt;a href=&quot;https://en.wikipedia.org/wiki/Mutual_exclusion&quot; rel=&quot;nofollow&quot; target=&quot;_blank&quot;&gt;mutual exclusion&lt;/a&gt; is a property of concurrency control, which is instituted for the purpose of preventing race conditions; it is the requirement that one thread of execution never enters its critical section at the same time that another concurrent thread of execution enters its own critical section.&lt;br /&gt;&lt;br /&gt;In Algotrading, you may encounter this situation while:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Running several expert advisers using a shared object which may worked on only once and not in parallel.&lt;/li&gt;&lt;li&gt;Trading only in certain conditions, for example allowing only one expert adviser to open a position while the other ones are blocked.&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;In my case, I am running several expert advisers on the same account trading different currencies. But, I wanted to have only one product open at a given moment while the others are blocked. So, if for example both EURUSD &amp;amp; EURJPY have the right conditions to open an order, only one order will be open. I wanted to avoid to be double exposed to products which are correlated between them, but there could be many other reasons to prevent it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h2&gt;Implementation&lt;/h2&gt;&lt;div&gt;MQL4 language supports &lt;a href=&quot;https://docs.mql4.com/globals&quot; rel=&quot;nofollow&quot; target=&quot;_blank&quot;&gt;global variables&lt;/a&gt;&amp;nbsp;which may use as the lock mechanism to prevent parallel execution of the same code and / or accessing a shared object.&amp;nbsp;&lt;/div&gt;&lt;div&gt;We start by declaring the Mutex variable as:&lt;/div&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;#define MUTEX              &quot;Mutex&quot;&lt;/span&gt;&lt;br /&gt;&lt;div&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;Also, we declare two constants which hold the different Mutex status, locked / unlocked:&lt;br /&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;#define LOCKED             1 #define UNLOCKED           0 &lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;We will use this variable&amp;nbsp; and the different status throughout the code to make sure certain code parts are not accessed in parallel, but first, we need to initialize it in the OnInit() function:&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;   if(GlobalVariableSet(MUTEX,UNLOCKED)==0)      {       Log(&quot;OnInit Mutex GlobalVariableSet failed&quot;,true,GetLastError());       return INIT_FAILED;      }&lt;/span&gt;&lt;br /&gt;This code initializes the Mutex to unlocked status.&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Then, throughout the execution, whenever we have a certain code we want to lock, we will add the following condition:&lt;/div&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&amp;amp;&amp;amp; &lt;b&gt;&lt;span style=&quot;color: red;&quot;&gt;GlobalVariableSetOnCondition(MUTEX,LOCKED,UNLOCKED)&lt;/span&gt;&lt;/b&gt; &amp;amp;&amp;amp;&lt;/span&gt;&lt;br /&gt;&lt;div&gt;As per the &lt;a href=&quot;https://docs.mql4.com/globals/globalvariablesetoncondition&quot; rel=&quot;nofollow&quot; target=&quot;_blank&quot;&gt;function&lt;/a&gt; definition, the unction provides &lt;b&gt;atomic access&lt;/b&gt; to the global variable, so it can be used for providing of a Mutex at interaction of several Expert Advisors working simultaneously within one client terminal.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As soon as the critical code is over, add the following piece of code to release the Mutex:&lt;/div&gt;&lt;span style=&quot;color: red; font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&lt;b&gt; GlobalVariableSetOnCondition(MUTEX,UNLOCKED,LOCKED);&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;&lt;div&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;With this simple utility, you can ensure that the critical part is not executed in parallel, as the first thread / expert adviser will get the lock while the others will not be able to enter this block of code until the mutex is locked.&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Concrete Example&lt;/h2&gt;&lt;div&gt;As part of my trading, I am interested to know whenever the balance changed due to a profit / loss. As I run several expert advisers on the same account, so I don&#39;t want to get notified X times about balance change, rather once as this is a shared value.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Mutual exclusion solves exactly that problem as the balance value is a shared value among the different expert advisers. To implement that, I created a global variable to hold the balance value:&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;const string BALANCE=&quot;Balance&quot;; &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;I initialize it with the current value in the OnInit() function:&lt;br /&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;   if(GlobalVariableSetOnCondition(MUTEX,LOCKED,UNLOCKED)==true)      {       if(GlobalVariableSet(BALANCE,AccountBalance())==0)         {          &lt;/span&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;SendNotification&lt;/span&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;(&quot;OnInit BALANCE GlobalVariableSet failed, please update manually&quot;);          return INIT_FAILED;         }       GlobalVariableSetOnCondition(MUTEX,UNLOCKED,LOCKED);      }&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And then, whenever the OrdersTotal() number changes, I send a notification about the new balance value, but I use the Mutex object to make sure that only one Expert adviser sends the notification while the other are locked:&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;         if(&lt;span style=&quot;color: red;&quot;&gt;&lt;b&gt;GlobalVariableSetOnCondition&lt;/b&gt;&lt;/span&gt;&lt;b&gt;&lt;span style=&quot;color: red;&quot;&gt;(MUTEX,LOCKED,UNLOCKED)&lt;/span&gt;&lt;/b&gt;==true)            {             if(GlobalVariableGet(BALANCE)!=AccountBalance())               {                double DailyProfit=AccountBalance()-GlobalVariableGet(BALANCE);                if(DailyProfit!=0)                   &lt;/span&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;SendNotification&lt;/span&gt;&lt;span style=&quot;background-color: white; font-family: , &amp;quot;consolas&amp;quot; , &amp;quot;liberation mono&amp;quot; , &amp;quot;menlo&amp;quot; , &amp;quot;courier&amp;quot; , monospace; font-size: 12px; white-space: pre;&quot;&gt;(StringConcatenate(SYMBOL,&quot; daily Profit = &quot;,DoubleToString(DailyProfit,2)));                 if(GlobalVariableSet(BALANCE,AccountBalance())==0)                   SendNotification(&quot;BALANCE GlobalVariableSet update failed, please update manually&quot;);               }             &lt;span style=&quot;color: red;&quot;&gt;&lt;b&gt;GlobalVariableSetOnCondition&lt;/b&gt;&lt;/span&gt;&lt;b&gt;&lt;span style=&quot;color: red;&quot;&gt;(MUTEX,UNLOCKED,LOCKED)&lt;/span&gt;&lt;/b&gt;;            } &lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This way, the critical path of checking the balance value and sending notification will not happen in parallel. By the time the next expert adviser gets the balance value, it is already updated by the previous expert adviser, so, the notification will be send once.&lt;/div&gt;&lt;div&gt;&lt;hr /&gt;&lt;br /&gt;&lt;div&gt;Join the Telegram channel to stay updated with trading ideas, articles and signals &lt;a href=&quot;http://t.me/ForexAlgotrading&quot; rel=&quot;nofollow&quot; target=&quot;_blank&quot;&gt;t.me/ForexAlgotrading&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/4765790382599200765/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2019/02/mutual-exclusion-implementation-in-mql4.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4765790382599200765'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4765790382599200765'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2019/02/mutual-exclusion-implementation-in-mql4.html' title='Mutual Exclusion (Mutex) Implementation in MQL4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://4.bp.blogspot.com/-6QHjJgWaLo0/XFlj-xvsKnI/AAAAAAAA9v4/RBfG2_QRjLwFqp2v2R-Ra_UpxtLikIJKQCLcBGAs/s72-c/27767467616_b686ba5900_k%2B%25281%2529.jpg" height="72" width="72"/><thr:total>0</thr:total><georss:featurename>Zürich, Switzerland</georss:featurename><georss:point>47.3768866 8.5416940000000068</georss:point><georss:box>47.204846599999996 8.2189705000000064 47.5489266 8.8644175000000072</georss:box></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-2969046945080356248</id><published>2019-01-24T12:00:00.000+01:00</published><updated>2019-01-24T21:14:15.718+01:00</updated><title type='text'>MetaTrader 4 Indicator to show Currency trend in Different Timeframes</title><content type='html'>&lt;div style=&quot;clear: both; text-align: left;&quot;&gt;&lt;h2&gt;Usage&lt;/h2&gt;When trading, you probably have several windows open next to each other, different products, different time frames. Or, you have the same product but in different timeframes to see how it performs.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I wrote this indicator so I can see for a given product, how it behaves in the different timeframes available by MetaTradre 4. It has three different lines to express the following information:&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;The trend for a given timeframe, blue arrow means bullish, red arrow means bearish.&lt;/li&gt;&lt;li&gt;The pips change for a given timeframe, blue text means bullish, red text means bearish.&lt;/li&gt;&lt;li&gt;The standard deviation for a given timeframe, red text means that the timeframe movement is higher thatn the volatility, otherwise black.&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;Once attached, a panel will be drawn in the lower left corner as in the following screenshot for EURUSD:&lt;/div&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://4.bp.blogspot.com/-x3uOBPjqpzo/XEh-tRZA8rI/AAAAAAAA9vY/dj2OLUbvVV0PACtiqM35buoTNGsgufu3ACLcBGAs/s1600/EURUSDH1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Timeframes trend indicator&quot; border=&quot;0&quot; data-original-height=&quot;674&quot; data-original-width=&quot;1276&quot; height=&quot;338&quot; src=&quot;https://4.bp.blogspot.com/-x3uOBPjqpzo/XEh-tRZA8rI/AAAAAAAA9vY/dj2OLUbvVV0PACtiqM35buoTNGsgufu3ACLcBGAs/s640/EURUSDH1.png&quot; title=&quot;Timeframes trend indicator&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;You may see, that the daily trend for example is bullish. And that the hourly movement in pips is higher than the volatility, thus the STD value for hourly timeframe is painted in red.&lt;br /&gt;&lt;br /&gt;To download, use the following links:&lt;br /&gt;1. The indicator, to be placed and compiled in the indicators folder - &lt;a href=&quot;https://drive.google.com/open?id=1iX569sDcM75U9--7_MfX_ZcwG5LY3mL3&quot; rel=&quot;nofollow&quot;&gt;Indicator&lt;/a&gt;.&lt;br /&gt;2. The common library, to placed and compilied in the common folder - &lt;a href=&quot;https://drive.google.com/open?id=1rgBXZUHvxN0hImCaS_c9fTfs6i1EmrYG&quot; rel=&quot;nofollow&quot;&gt;Library&lt;/a&gt;&lt;br /&gt;Compile and attached to your product.&lt;br /&gt;&lt;br /&gt;For any queries, don&#39;t hesitate to &lt;a href=&quot;http://p/contact.html&quot;&gt;contact&lt;/a&gt; me.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/2969046945080356248/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2019/01/metatrader-4-indicator-to-show-currency.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/2969046945080356248'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/2969046945080356248'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2019/01/metatrader-4-indicator-to-show-currency.html' title='MetaTrader 4 Indicator to show Currency trend in Different Timeframes'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://4.bp.blogspot.com/-x3uOBPjqpzo/XEh-tRZA8rI/AAAAAAAA9vY/dj2OLUbvVV0PACtiqM35buoTNGsgufu3ACLcBGAs/s72-c/EURUSDH1.png" height="72" width="72"/><thr:total>0</thr:total><georss:featurename>Zürich, Switzerland</georss:featurename><georss:point>47.3768866 8.5416940000000068</georss:point><georss:box>47.204846599999996 8.2189705000000064 47.5489266 8.8644175000000072</georss:box></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-534015405665605937</id><published>2019-01-01T13:04:00.001+01:00</published><updated>2019-01-18T21:41:06.149+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>Looking back at 2018 and forward to 2019</title><content type='html'>&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Every year brings with it 365 opportunities to make a difference, so did 2018 and so will 2019. The last was very exciting and challenging. Since going live with my algorithmic strategies to the public, it a was a roller coaster. As soon as you expose your ideas and start getting an inflow of investors it&#39;s a whole new and different experience.&lt;br/&gt;&lt;br/&gt;The challenge we face as FX traders, specifically as retail ones is that we don&#39;t have enough equity to make a living out of the trading, which drives us to take more risky positions with insane leverage hoping this will make us overnight rich. Of course, in reality the market has its own rules and most of the traders gets punished for acting foolish, seeing their account gets blown. This is one of the reasons that 80% of retails traders lose money on average, a figure which can be seen on many FX brokers sites:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignright size-medium wp-image-1345&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2019/01/6240846050_fc4c31e8c2_o-300x200.jpg&quot; alt=&quot;Ship wreck&quot; width=&quot;300&quot; height=&quot;200&quot; /&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;2018&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Lessons Learned&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;In 2018 I learned the hard way how risk management is critical. I got burnt with GBPUSD crash in Q1. So, if you don&#39;t want to end underwater, make sure you manage your risk properly, that&#39;s the number 1 killer to accounts. A simple calculation to check if your risk makes sense is to multiply your margin with your account leverage and divide with your equity, if the result is above 10, you better think carefully, if its over 50, one wrong move and your account will be wiped out...&lt;br/&gt;&lt;br/&gt;For example, say my broker offers me a leverage of 1:200 and I currently have margin equals to 57.25$ with equity of 1,753.07$. Making the above calculation of 52.25*200/1,753.07 = 6.53 teaches me I am in the right risk area. Unless I am on the right side of the trend, I make sure this value stays within the 10 boundaries. Otherwise, the higher the leverage, the higher the change per pip which is happening. It could work for me, but most likely it will work against me due to volatility.&lt;br/&gt;&lt;br/&gt;My lessons from the previous year are:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;To focus on a single currency, get to know it inside out, understand clearly what is the impact of news events on it, what are the different dependencies and so on. Forget about trading multiple currencies in a single account, the orders gets mixed and the management becomes challenging.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Have a clear open and close strategy and stick to it. The main problem with the market is the volatility, that noise that surrounds the trend and prevents us from seeing clearly where the currency goes. There are so many moments the market goes against what I think and I get tempted to close my position and move on with my life, but that&#39;s exactly the problem, that&#39;s where the amateurs are separated from the pros. As Nassim Taleb says in his brilliant book &quot;&lt;a href=&quot;https://www.amazon.com/Fooled-Randomness-Hidden-Markets-Incerto/dp/0812975219&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Fooled by Randomness&lt;/a&gt;&quot;, the less you look at the market, the better. The more often you check the positions, you will get turned off by volatility and what it does to your positions and P&amp;amp;L.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Don&#39;t over trade! If you reach your daily, weekly, monthly goal stop trading and do something else with your time. The more you trade, the higher the risk the strategy will miss and you&#39;ll incur losses. Sometimes, I have a take profit taken already at 10:00, which leaves me free the whole day not to worry and look at the market, it&#39;s amazing feeling.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Strategies&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;In 2018, I was operating two strategies with EURUSD as the underline:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;&lt;li&gt;&lt;a href=&quot;https://www.ilantree.com/zeb/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Day trading strategy&lt;/a&gt; - Focusing on short term opportunities with using scale in approach, this strategy achieved 52.26% return. It outperformed every index out there and provided myself and my investors brilliant return. December especially was remarkable, while the equities were hammered, my strategy managed to grow 16.05%.&lt;/p&gt;&lt;/li&gt;&lt;br/&gt;&lt;li&gt;&lt;p&gt;&lt;a href=&quot;https://www.ilantree.com/gfa/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Volatility trading strategy&lt;/a&gt; - focusing on volatility and momentum opportunities, this strategy had a 22.31% return. As these opportunities don&#39;t come so frequently, there were months where almost nothing happened and months (like August) where the strategy enjoyed the high volatility of the Turkish lira crises and made 8.04%.&lt;/p&gt;&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;As part of new investors, Relton Captial which&lt;span class=&quot;js-text-content content-block&quot;&gt; is a Zurich-based private investment company operating an array of tailor-made investment strategies added my strategies to their offerings and had them published on their homepage - &lt;a href=&quot;http://www.reltoncap.com/investments/index&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;http://www.reltoncap.com/investments/index&lt;/a&gt;. These investments will help me to refinance the DARWINs I sell, so the equity grows larger and the VAR goes lower, thus ensuring better return to the investors.&lt;/span&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;2019&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;This year, I am planning to introduce a grid trading based product. A strategy which is independent of market direction and driven by fixed spaced grid. Thus, making profit no matter where the market heads whether its trending or ranging. It is in a final stage of testing and about to be turned into a real account soon.&lt;br/&gt;&lt;br/&gt;With that, I will have three different products which have no correlation between them to make up a portfolio. I normally divide my funds equally along my products, even I am tempted to put it all on the day trading one. But as they say, don&#39;t put all of your eggs in a single basket...&lt;br/&gt;&lt;br/&gt;Besides that, I want to increase my investors streams, either by having visibility on the social media, or by letting Darwinex do their magic and show case my success on their front page. For me, ending 2019 with three DARWINs with a return of above 10% and total investment of 5 million will be considered a success.&lt;br/&gt;&lt;br/&gt;I opened up a telegram channel to show case my day trading strategy, it is limited to 100 actions per month, where open or close order is considered a single action, so in total around 50 trades you get for free if you join &lt;a href=&quot;http://t.me/ForexAlgotrading&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;t.me/ForexAlgotrading&lt;/a&gt;. Otherwise, for the full strategy you can either register to the signal available here - &lt;a href=&quot;https://www.mql5.com/en/signals/450569&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.mql5.com/en/signals/450569&lt;/a&gt; or invest in the original DARWIN where you can get a leverage of 1:4 as an investor.&lt;br/&gt;&lt;br/&gt;For example, assuming you had an investor account with 25k $ in Darwinex with a leverage of 1:4, it would have translated to 100k $ investment in the strategy which will have a return of 16.05% which is 16k $. That is more that 50% on your original investment!&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignleft size-medium wp-image-1346&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2019/01/9245616611_2045e4ec2f_z-300x169.jpg&quot; alt=&quot;Champagne&quot; width=&quot;300&quot; height=&quot;169&quot; /&gt;&lt;br/&gt;&lt;br/&gt;So, happy new year everyone and I hope you&#39;ll make it big time in 2019!</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/534015405665605937/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2019/01/looking-back-at-2018-and-forward-to-2019_1.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/534015405665605937'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/534015405665605937'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2019/01/looking-back-at-2018-and-forward-to-2019_1.html' title='Looking back at 2018 and forward to 2019'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-3470891162671706779</id><published>2018-12-10T08:00:00.001+01:00</published><updated>2019-01-18T21:44:08.970+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>Implementing Trailing Stop Loss in MQL4</title><content type='html'>&lt;blockquote class=&quot;wp-block-quote&quot;&gt;Cut your losses early, and let your winners runs.&lt;br /&gt;&lt;cite&gt;Trading circles&lt;/cite&gt;&lt;/blockquote&gt;&lt;h2&gt;Introduction&lt;/h2&gt;This is the most common quote you&#39;ll probably hear in trading circles. Which basically means, that as soon as you open a position, you need to monitor it and make a decision against it or for it. When you move into the algotrading regime, I would modify this quote into the following one:&lt;br /&gt;&lt;blockquote class=&quot;wp-block-quote&quot;&gt;Cut your losses early, and let your winners run... to your trailing stop loss.&lt;br /&gt;&lt;cite&gt;Roy Meshulam&lt;/cite&gt;&lt;/blockquote&gt;That&#39;s because you don&#39;t want to spend your time in front your PC monitoring the order. The contrary, you want to have a fully automated expert adviser that does it for you, opening and closing order according to the logic you built.&lt;br /&gt;&lt;br /&gt;Trailing stop loss a strong utility to have. It is basically the logic to update the stop loss value and move it together with the price. So, if the price is in your favour, you move the stop loss, thus, capturing more profit. If it is against, you keep the stop loss with the same value. Hence, it is called trailing stop loss.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Stop Loss / Take Profit Function&lt;/h2&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;The first thing we must have is a safe function to update an order with a stop loss / take profit value. We can&#39;t rely on the OrderModify one, as there is no proper error handling, value checking etc.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading {&quot;level&quot;:3} --&gt;&lt;br /&gt;&lt;h3&gt;Function Signature&lt;/h3&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;So, we will use our own function, which takes the following parameters:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:preformatted --&gt;&lt;br /&gt;&lt;pre class=&quot;wp-block-preformatted&quot;&gt;bool AddStopProfit(int argOrder,double argStopLoss,double argTakeProfit,bool argForceCorrectValue=false) export&lt;/pre&gt;&lt;br /&gt;&lt;!-- /wp:preformatted --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:list --&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;The order we want to modify&lt;/li&gt;&lt;li&gt;The stop loss value&lt;/li&gt;&lt;li&gt;The take profit value&lt;/li&gt;&lt;li&gt;A boolean flag to force a new value or not&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;!-- /wp:list --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;The return value will be a boolean which indicates whether the value modifications succeeded or not.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading {&quot;level&quot;:3} --&gt;&lt;br /&gt;&lt;h3&gt;Verification Step&lt;/h3&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;Next, we need to check if the order is still open. If yes, whether the new stop loss / take profit values are different than the existing ones. If the order is closed already, or the values are the same, then, there is nothing to change so we will return true:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:code --&gt;&lt;br /&gt;&lt;pre class=&quot;wp-block-code&quot;&gt;&lt;code&gt;if(OrderCloseTime()!=0 || &lt;br /&gt;     (NormalizeDouble(argStopLoss,(int)MarketInfo(OrderSymbol(),MODE_DIGITS))==OrderStopLoss() &amp;amp;&amp;amp; &lt;br /&gt;     NormalizeDouble(argTakeProfit,(int)MarketInfo(OrderSymbol(),MODE_DIGITS))==OrderTakeProfit()))&lt;br /&gt;     return true;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;!-- /wp:code --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading {&quot;level&quot;:3} --&gt;&lt;br /&gt;&lt;h3&gt;Modification Step&lt;/h3&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;Next, we will check what are the legal values for stop loss / take profit for the order. We will use as an example a long order. But the same logic will be applicable to a short one.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading {&quot;level&quot;:3} --&gt;&lt;br /&gt;&lt;h3&gt;Long Order Stop Loss Value Verification&lt;/h3&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;Normally, the broker has a maximum value for the stop loss. Which means, that if you try setting up one above this point, the OrderModify function will fail. To check what is this value we use the following code:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:code --&gt;&lt;br /&gt;&lt;pre class=&quot;wp-block-code&quot;&gt;&lt;code&gt;StopLoss=MarketInfo(OrderSymbol(),MODE_BID)-MarketInfo(OrderSymbol(),MODE_STOPLEVEL)*MarketInfo(OrderSymbol(),MODE_POINT);&lt;br /&gt;        if(argStopLoss!=0 &amp;amp;&amp;amp; argStopLoss&amp;gt;StopLoss)&lt;br /&gt;          {&lt;br /&gt;           if(argForceCorrectValue==false)&lt;br /&gt;             {&lt;br /&gt;              SendNotification(StringConcatenate(&quot;OP_BUY illegal SL for #&quot;,argOrder,&quot;, New / Allowed = &quot;,argStopLoss,&quot;/&quot;,StopLoss));&lt;br /&gt;              return false;&lt;br /&gt;             }&lt;br /&gt;           else&lt;br /&gt;              argStopLoss=StopLoss;&lt;br /&gt;          }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;!-- /wp:code --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;The first line check what is the maximum stop loss value we can set by subtracting the stop level value from the current bid price. The MODE_STOPLEVEL according to&amp;nbsp;&lt;a aria-label=&quot;The first line check what is the maximum stop loss value we can set by subtracting the stop level value from the current bid price. The MODE_STOPLEVEL value is the stop level in points. Which, according to https://docs.mql4.com/constants/environment_state/marketinfoconstants: A zero value of MODE_STOPLEVEL means either absence of any restrictions on the minimal distance for Stop Loss/Take Profit or the fact that a trade server utilizes some external mechanisms for dynamic level control, which cannot be translated in the client terminal. In the second case, GetLastError() can return error 130, because MODE_STOPLEVEL is actually &amp;quot;floating&amp;quot; here. (opens in a new tab)&quot; href=&quot;https://docs.mql4.com/constants/environment_state/marketinfoconstants&quot; rel=&quot;noreferrer noopener&quot; target=&quot;_blank&quot;&gt;https://docs.mql4.com/constants/environment_state/marketinfoconstants&lt;/a&gt;: Is the stop level in points. A zero value of MODE_STOPLEVEL means either absence of any restrictions on the minimal distance for Stop Loss/Take Profit or the fact that a trade server utilizes some external mechanisms for dynamic level control, which cannot be translated in the client terminal. In the second case, GetLastError() can return error 130, because MODE_STOPLEVEL is actually &quot;floating&quot; here.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;If the&amp;nbsp;argForceCorrectValue is set to false and the stop level value is illegal. The function will terminate and return false value, otherwise, we will use the maximum calculated stop level value instead of the function argument.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;The same logic applies for the take profit, there we need to check the that take profit value is not smaller than the minimum one allowed by the broker.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading {&quot;level&quot;:3} --&gt;&lt;br /&gt;&lt;h3&gt;Calling OrderModify&lt;/h3&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;Finally, we will call MQL4 OrderModify function to set the stop loss / take profit value, either the calculated one or the one we got as an argument:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:code --&gt;&lt;br /&gt;&lt;pre class=&quot;wp-block-code&quot;&gt;&lt;code&gt;if(OrderModify(argOrder,OrderOpenPrice(),NormalizeDouble(argStopLoss,(int)MarketInfo(OrderSymbol(),MODE_DIGITS)),NormalizeDouble(argTakeProfit,(int)MarketInfo(OrderSymbol(),MODE_DIGITS)),0)==false)&lt;br /&gt;       {&lt;br /&gt;        SendNotification(StringConcatenate(&quot;Add Stop/Profit failed updating order #&quot;,argOrder,&quot;, SL (N/E) = &quot;,argStopLoss,&quot;/&quot;,OrderStopLoss(),&quot;, TP (N/E) = &quot;,argTakeProfit,&quot;/&quot;,OrderTakeProfit()),true,GetLastError());&lt;br /&gt;        return false;&lt;br /&gt;       }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;!-- /wp:code --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;With this step completed, we updated the order values successfully. A typical call to this function will be something like:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:code --&gt;&lt;br /&gt;&lt;pre class=&quot;wp-block-code&quot;&gt;&lt;code&gt;AddStopProfit(OrderTicket(), 1.23456,1.43589,true);&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;!-- /wp:code --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;Meaning, modify the current ticket with a stop loss equal to 1.23456, take profit equals to 1.43589 and force valid values for them by setting the force flag to true.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading {&quot;level&quot;:3} --&gt;&lt;br /&gt;&lt;h3&gt;Full Function Code&lt;/h3&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;Putting it all together we have the following code:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:code --&gt;&lt;br /&gt;&lt;pre class=&quot;wp-block-code&quot;&gt;&lt;code&gt;    bool AddStopProfit(int argOrder,double argStopLoss,double argTakeProfit,bool argForceCorrectValue=false) export&lt;br /&gt;  {&lt;br /&gt;   if(OrderSelect(argOrder,SELECT_BY_TICKET))&lt;br /&gt;     {&lt;br /&gt;      if(OrderCloseTime()!=0 || &lt;br /&gt;         (NormalizeDouble(argStopLoss,(int)MarketInfo(OrderSymbol(),MODE_DIGITS))==OrderStopLoss() &amp;amp;&amp;amp; &lt;br /&gt;         NormalizeDouble(argTakeProfit,(int)MarketInfo(OrderSymbol(),MODE_DIGITS))==OrderTakeProfit()))&lt;br /&gt;         return true;&lt;br /&gt;      else if(OrderCloseTime()==0)&lt;br /&gt;        {&lt;br /&gt;         double StopLoss,TakeProfit;&lt;br /&gt;         if(OrderType()==OP_BUY)&lt;br /&gt;           {&lt;br /&gt;            StopLoss=MarketInfo(OrderSymbol(),MODE_BID)-MarketInfo(OrderSymbol(),MODE_STOPLEVEL)*MarketInfo(OrderSymbol(),MODE_POINT);&lt;br /&gt;            if(argStopLoss!=0 &amp;amp;&amp;amp; argStopLoss&amp;gt;StopLoss)&lt;br /&gt;              {&lt;br /&gt;               if(argForceCorrectValue==false)&lt;br /&gt;                 {&lt;br /&gt;                  Log(StringConcatenate(&quot;OP_BUY illegal SL for #&quot;,argOrder,&quot;, New / Allowed = &quot;,argStopLoss,&quot;/&quot;,StopLoss));&lt;br /&gt;                  return false;&lt;br /&gt;                 }&lt;br /&gt;               else&lt;br /&gt;                  argStopLoss=StopLoss;&lt;br /&gt;              }&lt;br /&gt;&lt;br /&gt;            TakeProfit=MarketInfo(OrderSymbol(),MODE_ASK)+MarketInfo(OrderSymbol(),MODE_STOPLEVEL)*MarketInfo(OrderSymbol(),MODE_POINT);&lt;br /&gt;            if(argTakeProfit!=0 &amp;amp;&amp;amp; argTakeProfit&amp;lt;TakeProfit)&lt;br /&gt;              {&lt;br /&gt;               if(argForceCorrectValue==false)&lt;br /&gt;                 {&lt;br /&gt;                  Log(StringConcatenate(&quot;OP_BUY illegal TP for order #&quot;,argOrder,&quot;, New / Allowed = &quot;,argTakeProfit,&quot;/&quot;,TakeProfit));&lt;br /&gt;                  return false;&lt;br /&gt;                 }&lt;br /&gt;               else&lt;br /&gt;                  argTakeProfit=TakeProfit;&lt;br /&gt;              }&lt;br /&gt;           }&lt;br /&gt;         else if(OrderType()==OP_SELL)&lt;br /&gt;           {&lt;br /&gt;            StopLoss=MarketInfo(OrderSymbol(),MODE_ASK)+MarketInfo(OrderSymbol(),MODE_STOPLEVEL)*MarketInfo(OrderSymbol(),MODE_POINT);&lt;br /&gt;            if(argStopLoss!=0 &amp;amp;&amp;amp; argStopLoss&amp;lt;StopLoss)&lt;br /&gt;              {&lt;br /&gt;               if(argForceCorrectValue==false)&lt;br /&gt;                 {&lt;br /&gt;                  Log(StringConcatenate(&quot;OP_SELL illegal SL value for #&quot;,argOrder,&quot;, New / Allowed = &quot;,argStopLoss,&quot;/&quot;,StopLoss));&lt;br /&gt;                  return false;&lt;br /&gt;                 }&lt;br /&gt;               else&lt;br /&gt;                  argStopLoss=StopLoss;&lt;br /&gt;              }&lt;br /&gt;&lt;br /&gt;            TakeProfit=MarketInfo(OrderSymbol(),MODE_BID)-MarketInfo(OrderSymbol(),MODE_STOPLEVEL)*MarketInfo(OrderSymbol(),MODE_POINT);&lt;br /&gt;            if(argTakeProfit!=0 &amp;amp;&amp;amp; argTakeProfit&amp;gt;TakeProfit)&lt;br /&gt;              {&lt;br /&gt;               if(argForceCorrectValue==false)&lt;br /&gt;                 {&lt;br /&gt;                  Log(StringConcatenate(&quot;OP_SELL illegal TP for order #&quot;,argOrder,&quot;, New / Allowed = &quot;,argTakeProfit,&quot;/&quot;,TakeProfit));&lt;br /&gt;                  return false;&lt;br /&gt;                 }&lt;br /&gt;               else&lt;br /&gt;                  argTakeProfit=TakeProfit;&lt;br /&gt;              }&lt;br /&gt;           }&lt;br /&gt;         if(OrderModify(argOrder,OrderOpenPrice(),NormalizeDouble(argStopLoss,(int)MarketInfo(OrderSymbol(),MODE_DIGITS)),NormalizeDouble(argTakeProfit,(int)MarketInfo(OrderSymbol(),MODE_DIGITS)),0)==false)&lt;br /&gt;           {&lt;br /&gt;            Log(StringConcatenate(&quot;Add Stop/Profit failed updating order #&quot;,argOrder,&quot;, SL (N/E) = &quot;,argStopLoss,&quot;/&quot;,OrderStopLoss(),&quot;, TP (N/E) = &quot;,argTakeProfit,&quot;/&quot;,OrderTakeProfit()),true,GetLastError());&lt;br /&gt;            return false;&lt;br /&gt;           }&lt;br /&gt;         else&lt;br /&gt;            return true;&lt;br /&gt;        }&lt;br /&gt;     }&lt;br /&gt;   else&lt;br /&gt;     {&lt;br /&gt;      Log(StringConcatenate(&quot;Add Stop/Profit failed selecting order #&quot;,argOrder),true,GetLastError());&lt;br /&gt;      return false;&lt;br /&gt;     }&lt;br /&gt;   return true;&lt;br /&gt;  }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;!-- /wp:code --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading --&gt;&lt;br /&gt;&lt;h2&gt;Trailing Stop Loss Implementation&lt;/h2&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;Now that the we have a correct function to update an order with stop loss / take profit values. Implementing a trailing stop loss will use it whenever the ticket progress in the right direction:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:preformatted --&gt;&lt;br /&gt;&lt;pre class=&quot;wp-block-preformatted&quot;&gt;double GAP=0.00100;&lt;br /&gt;&lt;br /&gt;int Ticket=OrderTicket();&lt;br /&gt;if((MarketInfo(Symbol(),MODE_BID)-OrderStopLoss())&amp;gt;GAP)&lt;br /&gt;    AddStopProfit(Ticket,MarketInfo(Symbol(),MODE_BID)-GAP,0,true);&lt;/pre&gt;&lt;br /&gt;&lt;!-- /wp:preformatted --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;In this example, I chose a long order and checked whether the current price minus the order stop loss price is &lt;strong&gt;bigger&lt;/strong&gt; than the predefined GAP value of 100 pips. If it is the case, I subtract the &lt;strong&gt;GAP&lt;/strong&gt; from the current price. Thus, I ensure the gap is kept constant between the current price to the stop loss of 100 pips.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;It is straightforward to use and I tried to keep it as simple as possible. Another possibility is to set the stop loss based on an indicator value, for example using the &lt;a aria-label=&quot;It is straightforward to use and I tried to keep it as simple as possible. Another possibility is to set the stop loss based on an indicator value, for example using the Trailing ATR indicator:  (opens in a new tab)&quot; href=&quot;https://www.ilantree.com/product/trailing-atr-indicator/&quot; rel=&quot;noreferrer noopener&quot; target=&quot;_blank&quot;&gt;Trailing ATR indicator&lt;/a&gt;:&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:image {&quot;id&quot;:585} --&gt;&lt;br /&gt;&lt;br /&gt;&lt;figure class=&quot;wp-block-image&quot;&gt;&lt;img alt=&quot;&quot; class=&quot;wp-image-585&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/edd/2018/04/TrailingATR.png&quot; /&gt;&lt;/figure&gt;&lt;br /&gt;&lt;!-- /wp:image --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;In this example, you may adjust the code to have the trailing stop equal the value of the Trailing ATR value. There&#39;s a really nice value capturing in this image if you calculate properly...&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:heading --&gt;&lt;br /&gt;&lt;h2&gt;Summary&lt;/h2&gt;&lt;br /&gt;&lt;!-- /wp:heading --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;In this post, I introduce the code I use for algorithmic trailing stop value. You may use this code as is in your programs and update the stop loss every X minutes / every predefined event etc.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;&lt;br /&gt;&lt;br /&gt;&lt;!-- wp:paragraph --&gt;&lt;br /&gt;As usual, feel free to contact me for any query / topic. Join the telegram chat for free signals and trading ideas &lt;a aria-label=&quot;As usual, feel free to contact me for any query / topic. Join the telegram chat for free signals and trading ideas t.me/ForexAlgotrading. (opens in a new tab)&quot; href=&quot;http://t.me/ForexAlgotrading&quot; rel=&quot;noreferrer noopener&quot; target=&quot;_blank&quot;&gt;t.me/ForexAlgotrading&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;!-- /wp:paragraph --&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/3470891162671706779/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/12/implementing-trailing-stop-loss-in-mql4_10.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3470891162671706779'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3470891162671706779'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/12/implementing-trailing-stop-loss-in-mql4_10.html' title='Implementing Trailing Stop Loss in MQL4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-4023701306799342907</id><published>2018-11-18T10:50:00.001+01:00</published><updated>2019-01-18T21:41:05.934+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>How to Communicate Between MetaTrader Terminals using Files</title><content type='html'>&lt;h1&gt;Introduction&lt;/h1&gt;&lt;br/&gt;&lt;br/&gt;Do you need different MetaTrader terminals to be able to communicate between themselves?&lt;br/&gt;&lt;br/&gt;Some reasons to implement this logic could be:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Trading with different accounts which need to know on each other status.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Trading with different brokers which needs to have the same orders open.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Using one terminal to notify another terminal upon a certain trading condition.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;The use case which enforced me to communicate between different terminals, was a strategy running on one account that had to notify another terminal to open orders once certain conditions were met. The second strategy was a derivative of the first one, so it had a dependency on its behavior. But I didn’t want to run both strategies in the same terminal as I wanted the order book to be clean and not a mixture of these two strategies.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;&lt;em&gt;Important: this solution will only work if the terminals are running on the same PC, otherwise, you need to consider using other methods like reading remote URL or using FTP.&lt;/em&gt;&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;&lt;h1&gt;Solution&lt;/h1&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Using Common Files&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;MetaTrader has a feature to handle files located in the common data folder. A location accessible by using the option FILE_COMMON upon file functions call. This is where we will place our shared files which will be used to hold the information different terminals need to use.&lt;br/&gt;&lt;br/&gt;Normally, there is a single producer who writes the file and N consumers who reads it. Otherwise, a solution needs to take file synchronization in consideration, not to get to a state where two processes are writing at the same time and corrupting the file.&lt;br/&gt;&lt;br/&gt;There must be a shared name between all the participants, so all the terminals refer to the same file on the common folder.&lt;br/&gt;&lt;br/&gt;So, high level the solution will be to open up a file in the common folder, update it with whatever information we want to share, close it. In parallel, the consumers check for changes every X minute, as soon as a change detected. They read it and act accordingly. Meaning that our code will have two sides, the producer and the consumer of the information.&lt;br/&gt;&lt;br/&gt;To locate the common data folder location, click in MetaEditor File -&amp;gt; “Open Common Data Folder”.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Producer&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;This instance is responsible to open up the file as a write only file and update it with the relevant information for the consumers. It will do so in the common folders so other terminals will be able to access it.&lt;img class=&quot;wp-image-1281 size-medium alignright&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/11/4221092606_a0f1fe955a_z-300x194.jpg&quot; alt=&quot;Farm&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;&lt;br/&gt;&lt;br/&gt;The first thing we need is a shared file name, one which will be used within all the MetaTrader terminals. I will declare it as follows:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;const string FILENAME=&quot;Pipe.txt&quot;;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;It may be any given name, I chose Pipe as it is behaving like an information pipe between the different terminals.&lt;br/&gt;&lt;br/&gt;Next, once a new information is ready to be shared, we will do the following:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;int FileHandle=FileOpen(FILENAME,FILE_TXT|FILE_WRITE|FILE_COMMON);&lt;br/&gt; if(FileHandle==INVALID_HANDLE) &lt;br/&gt;    SendNotification(StringConcatenate(&quot;Operation FileOpen failed: &quot;,IntegerToString(GetLastError()))); &lt;br/&gt;else {&lt;br/&gt;    if(FileWriteString(FileHandle,StringConcatenate(&quot;OP_SELL&quot;,&quot;;&quot;,DoubleToString(0.29,2)))==0) &lt;br/&gt;        SendNotification(StringConcatenate(&quot;Operation FileWrite failed: &quot;,IntegerToString(GetLastError())));&lt;br/&gt; FileClose(FileHandle);&lt;br/&gt; }&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;We start by opening a file for writing in the common data folder, by using the flag FILE_COMMON flag. Then, if the file open was successful, we write into the file the information we want. In this case, I wrote an instruction to open a short order with a certain order lots value. If the write was successful, the return value will not be 0, rather, the number of the bytes written. We finish by closing the shared file.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Consumer&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;size-medium wp-image-1282 alignright&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/11/3253926617_29c3f5a7ef_z-300x225.jpg&quot; alt=&quot;Horse&quot; width=&quot;300&quot; height=&quot;225&quot; /&gt;On the consumer side, we will use the same file name to refer to the same information pipe with the producer from the previous part:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;const string FILENAME=&quot;Pipe.txt&quot;;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Then, we will check every X minute whether a pipe exists with new information. Once there, we will open for reading and get the new information to be used:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if(TheMinute!=Minute()) &lt;br/&gt;{&lt;br/&gt; TheMinute=Minute();&lt;br/&gt;  if(FileIsExist(FILENAME,FILE_COMMON)==true)&lt;br/&gt; {&lt;br/&gt;     int FileHandle=FileOpen(FILENAME,FILE_TXT|FILE_READ| FILE_COMMON);&lt;br/&gt;    if(FileHandle==INVALID_HANDLE) &lt;br/&gt;    {&lt;br/&gt;         SendNotification(StringConcatenate(&quot;Operation FileOpen failed: &quot;,IntegerToString(GetLastError())));&lt;br/&gt;         ExpertRemove();&lt;br/&gt;         return; &lt;br/&gt;    }&lt;br/&gt;      string Line,Values[]; &lt;br/&gt;    while(FileIsEnding(FileHandle)==false)&lt;br/&gt;     {&lt;br/&gt;         Line=FileReadString(FileHandle);&lt;br/&gt;         StringSplit(Line,StringGetCharacter(&quot;;&quot;,0),Values);  &lt;br/&gt;        //do something with the values… &lt;br/&gt;    } &lt;br/&gt;    FileClose(FileHandle);&lt;br/&gt;     if(FileDelete(FILENAME,FILE_COMMON)==false) &lt;br/&gt;    { &lt;br/&gt;       SendNotification(StringConcatenate(&quot;Operation FileClose failed: &quot;,IntegerToString(GetLastError())));&lt;br/&gt;        ExpertRemove();&lt;br/&gt;        return; &lt;br/&gt;     }&lt;br/&gt;   } &lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;As soon as we see the file exists, we will open it for reading, again in the common data folder by using the FILE_COMMON flag. Then we read line by line and split the line into the Values array using the “;” as the separator. Then the consumer has all the information he needs to use in the internal logic. Finally, we close and delete the file to make sure we will not use old information.&lt;br/&gt;&lt;br/&gt;Using this piece of code, we ensured we are checking regularly for new input and once we have it, we are able to use it across multiple MetaTrader instances. In my case, I only need it in one instance of MetaTrader. But If I had to use it in more than one instance, I would use the file timestamp as the indicator if something changed instead of deleting the file as multiple instances would be using it. It is a simple check:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;FileGetInteger(FileHandle,FILE_MODIFY_DATE);&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;I have introduced a method I am using with my expert advisers to communicate between different MetaTrader instances using files in the common data folder. It is based on a communication between a single producer to multiple consumers. With that in hand, you can create a multi strategy across several different accounts.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;As always, for any information on my trading activity or any other information, don’t hesitate to &lt;a href=&quot;https://www.ilantree.com/contact/&quot;&gt;contact&lt;/a&gt; me.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;I launched the &lt;a href=&quot;https://www.ilantree.com/community/&quot;&gt;community&lt;/a&gt; page with different forums, please register and discuss with the community about FX trading and / or Expert Advisors programming.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/4023701306799342907/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/11/how-to-communicate-between-metatrader_18.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4023701306799342907'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4023701306799342907'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/11/how-to-communicate-between-metatrader_18.html' title='How to Communicate Between MetaTrader Terminals using Files'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-437470053345924817</id><published>2018-10-31T11:00:00.001+01:00</published><updated>2019-01-18T21:41:05.822+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Darwinex"/><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="Investing"/><category scheme="http://www.blogger.com/atom/ns#" term="Trading"/><title type='text'>How I make Money trading Forex</title><content type='html'>&lt;a href=&quot;https://www.tradeciety.com/24-statistics-why-most-traders-lose-money/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;&lt;em&gt;Did you know that on average 80% of retail traders lose money when trading Forex?&lt;/em&gt;&lt;/a&gt;&lt;br/&gt;&lt;br/&gt;But, if you&#39;ve been following my blog, you realized by now that I make my income from trading Forex, and to be specific from trading EURUSD &lt;strong&gt;only&lt;/strong&gt;. This is the only product I trade and live from, which is quite counter intuitive, how is it possible to trade only one product with all it&#39;s ups and downs and live from it? In this post, I will explain exactly how I make a living from trading Forex and which traps to avoid.&lt;br/&gt;&lt;br/&gt;Still, even that it worked for me and the setup is quite simple, there&#39;s no guarantee it will work for you the reader. We are all in a different situations in life, with more or less to risk, knowledge and so on. But still, I suggest to read this post to understand which traps are out there and which path you can follow to avoid losing your money.&lt;br/&gt;&lt;br/&gt;&lt;h1&gt;The Traps&lt;/h1&gt;&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignright size-medium wp-image-1225&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/10/12361255373_5ca0346653_z-300x200.jpg&quot; alt=&quot;Trap&quot; width=&quot;300&quot; height=&quot;200&quot; /&gt;&lt;br/&gt;&lt;br/&gt;But first, let&#39;s start with the typical pitfalls out there, unfortunately, in some of them I fell myself and lost money:&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Buying Expert Advisers / Trading Robots&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;There are so many robots out there for sale. With insane back testing results and promises to for guaranteed returns of 100%+ per year. This is absolutely nonsense!!! No one with successful strategy which makes money will sell it to the public with retarded prices as done on the market. It is not realistic and you can forget about their ability to forecast what will come next and earn for you.&lt;br/&gt;&lt;br/&gt;When I started trading 10 years ago, I fell into this trap and bought some robots from a merchant. I had no clue why the robot behaves as it behaves, how the risk management works and what are the trading triggers. The customer service was horrible, no matter how I tried reaching the team who sold the robot, I got no response and complete ignorance. As soon as they got the money, it wasn&#39;t possible to get a reply within a reasonable time, horrible support!&lt;br/&gt;&lt;br/&gt;Eventually, I lost quite a sum on this expert adviser, at least 10 times more than it cost to be specific. From that point onward, I never bought expert advisers and did it all myself from the following reasons:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;I wanted to have full control on the risk management&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;I wanted to know exactly what triggers an order&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;I wanted to know exactly how the expert adviser behaves when an exception happens&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;I wanted to understand exactly the expert adviser behavior&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;I didn&#39;t want to rely on anyone else&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Empty Promises&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Did you ever see this sort of promises online?&lt;img class=&quot;alignright size-medium wp-image-1226&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/10/6846586881_f2ea38a1a4_z-214x300.jpg&quot; alt=&quot;Salesman&quot; width=&quot;214&quot; height=&quot;300&quot; /&gt;&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;&quot;GET XXX PIPS EVERY MONTH WITH FREE!!! FOREX SIGNALS IT 100% ASK ME HOW?&quot;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&quot;Who&#39;s new in trading and looking for a MENTOR? I&#39;ll teach you for FREE. NO SIGNALS, JUST YOU and THE CHART&quot;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Looking for reliable FREE FOREX SIGNAL to recover your all loses! Reply &#39;YES&#39; you will get the telegram link&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&quot;Stop paying for Forex signal .. join our VIP channel and get free Forex signals on a daily base ...COMMENT &quot;yes&quot; to be added.&quot;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&quot;XXX pips sure shot strategy 100% guaranteed only in YYY$ anyone need can send me msg&quot;&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;Following on the previous paragraph, this is nonsense! No one will provide you signals for free, no one will educate you for free and no one will make you money without return. If you want to make money, you need to invest time and money to make it happen, there is no free lunch. These are mostly fraudsters with no clue on trading, I followed some of their accounts and saw how they gets blown away from over leverage, with &lt;a href=&quot;https://www.ilantree.com/leverage-explained/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;effective leverage&lt;/a&gt; of more than 1:20...&lt;br/&gt;&lt;br/&gt;Some of them wants to get your mobile, to harass you with commercials or just adding you to some database, some of them will sell you dreams for nothing. It is normally a post which promises for free insane returns, spelling mistakes, request for your private number and so on. Don&#39;t let greed to influence your decision and just ignore these type of messages.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;NON-DMA Broker&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Working with non Direct Market Access broker is one of the most critical mistakes you can do. It&#39;s basically trading with a broker who has interest in you&#39;re losing your money!!! DMA broker means a broker which simply forward your orders to the markets using liquidity providers and taking a commission for that.&lt;br/&gt;&lt;br/&gt;There are hundreds of brokers out there, choosing the right one based on conditions, regulations and geography is almost impossible, but having a broker which doesn&#39;t trades against you is the right starting point. Normally it is stated clearly in the website which type of broker is it, read the fine printing, the terms and conditions, it will cost you if you won&#39;t...&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Bonus Upon Signing Up&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;If a broker gives you a bonus for depositing with him, be sure that you will lose this money to him. Again, there is no free lunch. If you get money for free, it means the spreads are massive, the execution is retarded or the trading house is opening positions against you. Don&#39;t be tempted to get his 50$ or whatever amount you&#39;re offered only to discover it is gone together with your initial deposit...&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Non Regulated Broker&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;The regulation is here to protect us, the traders. A thumb rule is NEVER trading with a non regulated broker!&lt;img class=&quot;alignright size-full wp-image-1229&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/10/6260723020_d9076a0068_q.jpg&quot; alt=&quot;Hammer&quot; width=&quot;150&quot; height=&quot;150&quot; /&gt;&lt;br/&gt;&lt;br/&gt;Together with that, as part of the regulation, brokers must state how much % of their traders losing money with them. You may see it normally at the bottom of the screen, a statement which looks like:&lt;br/&gt;&lt;br/&gt;&quot;Risk Warning: CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage. &lt;span style=&quot;color: #ff0000;&quot;&gt;&lt;strong&gt;XX.XX% of retail investor accounts lose money when trading CFDs with this provider&lt;/strong&gt;.&lt;/span&gt; You should consider whether you understand how CFDs work and whether you can afford to take the high risk of losing your money.&quot;&lt;br/&gt;&lt;br/&gt;Normally, this number should be 70-80%, if it is higher than, run away as fast as you can. If the numbers are high, something is dodgy and you don&#39;t want to be there with your hard earned money.&lt;br/&gt;&lt;br/&gt;&lt;h1&gt;My Way&lt;/h1&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Finding the right Strategies&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Now that we understand what are the pitfalls / traps out there, it&#39;s time to find a solution to all of that issues. Having so many risks and challenges was the main reason it took me so much time to find the right setup for me.&lt;br/&gt;&lt;br/&gt;Starting  with the main thing, finding a winning strategy. I realized that the main problem new traders have is greed. They come up with 1000, take insane leverage and hope to make millions out of it, which will never ever works, only in a rare cases and after years of successful trades, it might be possible. Instead, I focused on finding a conservative strategy which makes 0-2% a month, mostly close to 1%. That&#39;s how I come up with the &lt;a href=&quot;https://www.ilantree.com/zeb/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Day Trading Strategy&lt;/a&gt;. An algorithm which opens one order maximum per day, 0.1% lot size of the equity and trading today&#39;s movement. If it makes money, it closes the same day, if not, it continues until a fine closure is achieved.&lt;br/&gt;&lt;br/&gt;Together with this strategy, I wrote the more aggressive strategy, so called &lt;a href=&quot;https://www.ilantree.com/gfa/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Volatility Trading Strategy&lt;/a&gt;. Strategy which is driven, as the name suggests, from the product&#39;s volatility. It is much more aggressive with returns up to 8% a month.&lt;br/&gt;&lt;br/&gt;I ran them both on EURUSD, thus ensuring liquidity with narrow spreads. I didn&#39;t want to use any exotics or bizarre products with weird behavior. Rather the most familiar with the most information and tick data out there.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Finding the right Broker&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;With the right strategies in hand, it was time to find the right broker. This was super challenging task with all the brokers out there. But I started narrowing down all of them by the following criteria:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Regulation - I filtered out all the non-regulated brokers, specifically, those which are not regulated by some European known one such as ESMA, FINMA etc.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;DMA - As mentioned above, I filtered out all the non-DMA brokers, meaning, I looked for those with strong liquidity providers and direct market access.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Social trading - As I am confident with my strategies, I wanted to have the possibility to open them up for investors and receive fee from those copying it.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Customer service - I reached out to the different brokers left and checked who is the most approachable team, who is nice and has 24/5 opening hours.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;After this tedious process was over, I had a winner, a broker called &lt;a href=&quot;http://www.darwinex.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Darwinex&lt;/a&gt;. A regulated, DMA broker with an amazing support team and cutting edge technology. They introduced the concept of DARWIN, an instrument which encapsulates trading strategies and open it up for investors. So not only I make money with my own equity, I also get performance fees from the interested investors.&lt;br/&gt;&lt;br/&gt;On top of that, Darwinex offers for investors an &lt;a href=&quot;https://www.darwinex.com/are-you-investor&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;investor account&lt;/a&gt; with up to 4 times leverage on their equity, so not only you get to invest in successful strategies if you choose right, you also get to quadruple your profits. For example, assuming you invest 10k in a certain DARWIN which makes 20% a year, you&#39;ll actually make 4&lt;em&gt;10k&lt;/em&gt;20%=8k, not bad, right?!&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Putting it all together&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Connecting all the dots together, I basically run my own algorithms, hosting them on Darwinex and getting performance fees from the investors:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Day trading strategy - &lt;a href=&quot;https://www.darwinex.com/darwin/ZEB.4.8/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.darwinex.com/darwin/ZEB.4.8/&lt;/a&gt;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Volatility trading strategy - &lt;a href=&quot;https://www.darwinex.com/darwin/GFA.4.21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.darwinex.com/darwin/GFA.4.21&lt;/a&gt;&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;I aim to make 2% per month combined from both strategies, so after 3 years with 125k initial investment times 4 leverage, I will reach my first million:&lt;br/&gt;&lt;br/&gt;500k * (1+2%)^36 = 1M+ $.&lt;br/&gt;&lt;br/&gt;The broker is completely transparent, there is an insurance up to 500k $ so the funds are safe, these are my strategies running so I have 100% confidence about their behavior so I can sleep good at night. And that&#39;s exactly I make money from trading Forex.&lt;br/&gt;&lt;br/&gt;&lt;h1&gt;Conclusions&lt;/h1&gt;&lt;br/&gt;&lt;br/&gt;We all have financial goals we want to achieve, but seems that 80% of us have unrealistic ones. &lt;img class=&quot;alignright size-medium wp-image-1231&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/10/5751595802_03fa020437_z-300x199.jpg&quot; alt=&quot;Goals&quot; width=&quot;300&quot; height=&quot;199&quot; /&gt;It doesn&#39;t have to be like that. In this post, I wrote transparently how Forex trading works for me. The main take away is that there is no free lunch. It is your money and you must make smart decisions with it. Don&#39;t get tempted by empty promises and look for the most reliable way to invest it.&lt;br/&gt;&lt;br/&gt;&lt;em&gt;If you continue falling in the traps mentioned above, then next year, you will be exactly in the same state, reading this article and thinking what went wrong.&lt;/em&gt;&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;As usual, if you have any questions please don’t hesitate to contact me over &lt;a href=&quot;mailto:sales@ilantree.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;sales@ilantree.com&lt;/a&gt; or &lt;a href=&quot;tel:+41 76 236 59 58&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;+41 76 236 59 58&lt;/a&gt;.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Please note, that starting October I launched my free signal providing available via Twitter at &lt;a href=&quot;https://twitter.com/IlanTree&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://twitter.com/IlanTree&lt;/a&gt; or Telegram at &lt;a href=&quot;https://t.me/IlanTreeGroup&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://t.me/IlanTreeGroup&lt;/a&gt;. With these possibilities, you get the signals but with a certain delay, if you want to get the signals at real time, you’d have to register and pay here – &lt;a href=&quot;https://www.mql5.com/en/signals/450569&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.mql5.com/en/signals/450569&lt;/a&gt;.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/437470053345924817/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/10/how-i-make-money-trading-forex_31.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/437470053345924817'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/437470053345924817'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/10/how-i-make-money-trading-forex_31.html' title='How I make Money trading Forex'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-6778460775986199292</id><published>2018-10-25T14:00:00.001+02:00</published><updated>2019-01-18T21:41:05.709+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>How I use Properties Files in Expert Advisers</title><content type='html'>&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;The classic way of defining input parameters for an expert adviser is using a variable, for example:&lt;br/&gt;&lt;code&gt;input double Lots=0.01; //Default lots to use&lt;/code&gt;&lt;br/&gt;In this case the input variable will hold the default value to use in the expert adviser throughout the execution. If you want to change the value, you’d have to restart the expert adviser to enter the new value.&lt;br/&gt;But, what if you could have avoided restarting the expert adviser, in some cases, the expert adviser is doing something or holding some valuable piece of information which might get lost if you restart it again.&lt;br/&gt;&lt;br/&gt;My way of using parameters solves exactly that challenge, in my solution which I will explain later on, I am using properties files and updating the expert adviser on the fly, thus, avoiding the unnecessary restart of the expert adviser.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;File Structure&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;As I am using the plain text files as properties files, the structure is mostly as key=value structure. For example, the Lots input parameter mentioned above will be written as:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;Lots=0.01&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;In its own line.&lt;br/&gt;&lt;br/&gt;As for the file name convention, I normally use the expert adviser name concatenate with “Properties.txt”. So, if the expert adviser is called Trader, there will be a file called TraderProperties.txt under the files folder with the relevant properties. You may form this file name programmatically by calling the following function:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;string PropertiesFilename=StringConcatenate(MQLInfoString(MQL_PROGRAM_NAME) ,&quot;Properties.txt&quot;);&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Reading Properties Files on the Fly&lt;br/&gt;Assuming your expert adviser is running with a certain setup and you want to fine tune it by changing one of the parameters you use. Like mentioned above, one option will be to restart the expert adviser and enter the new values, or, using the following code to check for updated properties. You may put this code with the OnTimer function to check on periods or to call it upon a certain condition.&lt;br/&gt;&lt;br/&gt;Create a global variable to store the last time the properties file was modified, we will see how to use it within the code. For the moment, have this initialization in your code:&lt;br/&gt;&lt;code&gt;long PropertiesFileModifyDate;&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Start by opening the file by calling the next set of functions:&lt;br/&gt;&lt;code&gt;string PropertiesFileName;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(IsDemo()==true)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;PropertiesFileName=StringConcatenate(MQLInfoString(MQL_PROGRAM_NAME) ,&quot;DemoProperties.txt&quot;);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;PropertiesFileName=StringConcatenate(MQLInfoString(MQL_PROGRAM_NAME) ,&quot;Properties.txt&quot;);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(FileIsExist(PropertiesFileName)==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Properties file &quot;,PropertiesFileName,&quot; doesn&#39;t exist, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;With these lines, we create the properties file name, we may distinguish between demo environment to production one as the code suggests, but it is not mandatory. I use as I have different properties for testing and for live accounts. If the file doesn’t exist, the function finishes here and return false to the calling environment.&lt;br/&gt;&lt;br/&gt;Otherwise, we open the file for reading as a text file and check the return handler. If it’s invalid, we print an error and return false:&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;int PropertiesFileHandle=FileOpen(PropertiesFileName,FILE_TXT|FILE_READ);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(PropertiesFileHandle==INVALID_HANDLE)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Operation FileOpen failed, error &quot;,ErrorDescription(GetLastError()),&quot;, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Now that we opened the file successfully, we check whether its modify date is different than the one we store in the global variable. If it equals -1 we return an error, if it equals the global variable PropertiesFileModifyDate we do nothing and return:&lt;br/&gt;&lt;code&gt;long ModifyDate=FileGetInteger(PropertiesFileHandle,FILE_MODIFY_DATE);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(ModifyDate==-1)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Operation FileGetInteger failed, error &quot;,ErrorDescription(GetLastError()),&quot;, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;FileClose(PropertiesFileHandle);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else if(ModifyDate==PropertiesFileModifyDate)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;FileClose(PropertiesFileHandle);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;Finally, if the file got changed, we update the global PropertiesFileModifyDate and read the file’s contents. In this simple example, I suppose there is a single value to read which is Lots, so I get the value and update the internal variable:&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;PropertiesFileModifyDate=ModifyDate;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;string Line,Values[];&lt;/code&gt;&lt;br/&gt;&lt;code&gt;while(FileIsEnding(PropertiesFileHandle)==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Line=FileReadString(PropertiesFileHandle);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(StringSplit(Line,StringGetCharacter(&quot;=&quot;,0),Values)!=2)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Operation StringSplit return more than two values, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;br/&gt;&lt;/code&gt;&lt;code&gt;&lt;code&gt;if(StringCompare(Values[0],&quot;Lots&quot;)==0)&lt;/code&gt;&lt;br/&gt;&lt;/code&gt;&lt;code&gt;Lots=StringToDouble(Values[1])==0;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;FileClose(PropertiesFileHandle);&lt;br/&gt;&lt;/code&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;In the end of the reading process, I close the file and return true to the calling function. In the next calls, we will again compare the modify date and only read the file if necessary.&lt;br/&gt;&lt;br/&gt;Putting it all together in a function we have:&lt;br/&gt;&lt;code&gt;bool SetInputVariables()&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;string PropertiesFileName;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(IsDemo()==true)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;PropertiesFileName=StringConcatenate(MQLInfoString(MQL_PROGRAM_NAME) ,&quot;DemoProperties.txt&quot;);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;PropertiesFileName=StringConcatenate(MQLInfoString(MQL_PROGRAM_NAME) ,&quot;Properties.txt&quot;);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(FileIsExist(PropertiesFileName)==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Properties file &quot;,PropertiesFileName,&quot; doesn&#39;t exist, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;int PropertiesFileHandle=FileOpen(PropertiesFileName,FILE_TXT|FILE_READ);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(PropertiesFileHandle==INVALID_HANDLE)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Operation FileOpen failed, error &quot;,ErrorDescription(GetLastError()),&quot;, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;long ModifyDate=FileGetInteger(PropertiesFileHandle,FILE_MODIFY_DATE);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(ModifyDate==-1)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Operation FileGetInteger failed, error &quot;,ErrorDescription(GetLastError()),&quot;, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;FileClose(PropertiesFileHandle);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else if(ModifyDate==PropertiesFileModifyDate)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;FileClose(PropertiesFileHandle);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;PropertiesFileModifyDate=ModifyDate;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;string Line,Values[];&lt;/code&gt;&lt;br/&gt;&lt;code&gt;while(FileIsEnding(PropertiesFileHandle)==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Line=FileReadString(PropertiesFileHandle);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(StringSplit(Line,StringGetCharacter(&quot;=&quot;,0),Values)!=2)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Operation StringSplit return more than two values, line &quot;,__LINE__));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(StringCompare(Values[0],&quot;Lots&quot;)==0)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Lots=StringToDouble(Values[1])==0;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;With Log utility function as follows (my own implementation):&lt;br/&gt;&lt;code&gt;void Log(string argMessage,bool argSendNotificationFlag=true,int argErrorCode=0) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(argErrorCode!=0)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;argMessage=StringConcatenate(argMessage,&quot;, Error: &quot;,argErrorCode,&quot; - &quot;,ErrorDescription(argErrorCode));&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;&lt;code&gt;Print(StringConcatenate(AccountServer(),&quot;, &quot;,IntegerToString(AccountNumber()),&quot;, &quot;,MQLInfoString(MQL_PROGRAM_NAME),&quot;, &quot;,Symbol(),&quot; &quot;,argMessage,&quot;, Balance = &quot;,DoubleToString(AccountBalance(),2),&quot; &quot;,AccountCurrency(),&quot;, P&amp;amp;L = &quot;,DoubleToString(AccountProfit(),2),&quot; &quot;,AccountCurrency(),&quot;, Equity = &quot;,DoubleToString(AccountEquity(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin = &quot;,DoubleToString(AccountMargin(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin (%) = &quot;,DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_LEVEL),2),&quot;%&quot;));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(argSendNotificationFlag==true)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;SendNotification(StringConcatenate(AccountServer(),&quot;, &quot;,IntegerToString(AccountNumber()),&quot;, &quot;,MQLInfoString(MQL_PROGRAM_NAME),&quot;, &quot;,Symbol(),&quot; &quot;,argMessage,&quot;, Balance = &quot;,DoubleToString(AccountBalance(),2),&quot; &quot;,AccountCurrency(),&quot;, P&amp;amp;L = &quot;,DoubleToString(AccountProfit(),2),&quot; &quot;,AccountCurrency(),&quot;, Equity = &quot;,DoubleToString(AccountEquity(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin = &quot;,DoubleToString(AccountMargin(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin (%) = &quot;,DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_LEVEL),2),&quot;%&quot;));&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Usage&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Equipped with this code, you may update the properties files with new parameter values and put on the relevant environment. Then, upon specific timing or condition you set in your expert adviser, you can call this function and update the parameters on the fly:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;From within OnInit function&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;From within OnTimer function&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Upon a certain code condition&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;The only occasions you need to compile the original expert adviser and restart it is if you introduce new properties to take into consideration or changed its logic.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;&lt;li&gt;&lt;p&gt;As usual, if you have any questions please don’t hesitate to contact me over &lt;a href=&quot;mailto:sales@ilantree.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;sales@ilantree.com&lt;/a&gt; or &lt;a href=&quot;tel:+41 76 236 59 58&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;+41 76 236 59 58&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;&lt;br/&gt;&lt;li&gt;&lt;p&gt;Please note, that starting October I launched my free signal providing available via Twitter at &lt;a href=&quot;https://twitter.com/IlanTree&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://twitter.com/IlanTree&lt;/a&gt; or Telegram at &lt;a href=&quot;https://t.me/IlanTreeGroup&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://t.me/IlanTreeGroup&lt;/a&gt;. With these possibilities, you get the signals but with a certain delay, if you want to get the signals at real time, you’d have to register and pay here - &lt;a href=&quot;https://www.mql5.com/en/signals/450569&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.mql5.com/en/signals/450569&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;&lt;iframe src=&quot;https://www.mql5.com/en/signals/widget/signal/3ir1&quot; width=&quot;220&quot; height=&quot;140&quot; frameborder=&quot;0&quot;&gt;&lt;/iframe&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/6778460775986199292/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/10/how-i-use-properties-files-in-expert_25.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/6778460775986199292'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/6778460775986199292'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/10/how-i-use-properties-files-in-expert_25.html' title='How I use Properties Files in Expert Advisers'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-1935116177422459442</id><published>2018-10-14T13:00:00.001+02:00</published><updated>2019-01-18T21:41:05.595+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Coding"/><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="MetaTrader4"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><title type='text'>MQL Functions to Close All Orders</title><content type='html'>This code and much utility functions are available for purchase as part of the &lt;a href=&quot;https://www.ilantree.com/product/common-library/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Common library&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;It is a common practice in my code to close all the orders once a certain condition is fulfilled. Normally, a profit target is reached, but there could be other reasons. In this post I will introduce some of the functions I am using to perform that. The main  common feature to all of these functions is the counting starts from OrdersTotal()-1 and goes down to 0. This to prevent closing already closed orders as noted in this article - &lt;a href=&quot;https://book.mql4.com/trading/orderclose&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://book.mql4.com/trading/orderclose&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Functions&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Standard&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;The standard function to close all the orders is simply going through the open ones and close them one by one, starting from the last towards the first:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllOrders(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; (OrderProfit()+OrderCommission()+OrderSwap())&amp;gt;=0 &amp;amp;&amp;amp; CloseOrder(OrderTicket(),OrderLots())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; (OrderProfit()+OrderCommission()+OrderSwap())&amp;lt;0 &amp;amp;&amp;amp; CloseOrder(OrderTicket(),OrderLots())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Where CloseOrder is:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseOrder(int argOrder,double argLotSize) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(argOrder,SELECT_BY_TICKET) &amp;amp;&amp;amp; OrderCloseTime()==0)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderType()!=OP_BUY &amp;amp;&amp;amp; OrderType()!=OP_SELL)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return ClosePendingOrder(argOrder);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else if(OrderCloseTime()==0 &amp;amp;&amp;amp; OrderClose(argOrder,VerifyLotSize(OrderSymbol(),argLotSize),OrderType()==OP_BUY?MarketInfo(OrderSymbol(),MODE_BID):MarketInfo(OrderSymbol(),MODE_ASK),Slippage,OrderType()==OP_BUY?clrGreen:clrRed)==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Closing order #&quot;,argOrder,&quot; failed, verified lot size = &quot;,VerifyLotSize(OrderSymbol(),argLotSize)),false,GetLastError());&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Closing order failed selecting order #&quot;,argOrder,&quot;, verified lot size = &quot;,VerifyLotSize(OrderSymbol(),argLotSize)),false,GetLastError());&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;And ClosePendingOrder() is&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool ClosePendingOrder(int argOrder) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(argOrder,SELECT_BY_TICKET) &amp;amp;&amp;amp; OrderCloseTime()==0)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderDelete(argOrder)==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Delete pending order #&quot;,argOrder,&quot; failed&quot;),false,GetLastError());&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Delete pending order failed selecting order #&quot;,argOrder),false,GetLastError());&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;With a small utility function:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;void Log(string argMessage,bool argSendNotificationFlag=true,int argErrorCode=0) export&lt;br/&gt;{&lt;br/&gt;if(argErrorCode!=0)&lt;br/&gt;argMessage=StringConcatenate(argMessage,&quot;, Error: &quot;,argErrorCode,&quot; - &quot;,ErrorDescription(argErrorCode));&lt;br/&gt;Print(StringConcatenate(AccountServer(),&quot;, &quot;,IntegerToString(AccountNumber()),&quot;, &quot;,MQLInfoString(MQL_PROGRAM_NAME),&quot;, &quot;,Symbol(),&quot; &quot;,argMessage,&quot;, Balance = &quot;,DoubleToString(AccountBalance(),2),&quot; &quot;,AccountCurrency(),&quot;, P&amp;amp;L = &quot;,DoubleToString(AccountProfit(),2),&quot; &quot;,AccountCurrency(),&quot;, Equity = &quot;,DoubleToString(AccountEquity(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin = &quot;,DoubleToString(AccountMargin(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin (%) = &quot;,DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_LEVEL),2),&quot;%&quot;));&lt;br/&gt;if(argSendNotificationFlag==true)&lt;br/&gt;SendNotification(StringConcatenate(AccountServer(),&quot;, &quot;,IntegerToString(AccountNumber()),&quot;, &quot;,MQLInfoString(MQL_PROGRAM_NAME),&quot;, &quot;,Symbol(),&quot; &quot;,argMessage,&quot;, Balance = &quot;,DoubleToString(AccountBalance(),2),&quot; &quot;,AccountCurrency(),&quot;, P&amp;amp;L = &quot;,DoubleToString(AccountProfit(),2),&quot; &quot;,AccountCurrency(),&quot;, Equity = &quot;,DoubleToString(AccountEquity(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin = &quot;,DoubleToString(AccountMargin(),2),&quot; &quot;,AccountCurrency(),&quot;, Margin (%) = &quot;,DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_LEVEL),2),&quot;%&quot;));&lt;br/&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;And&lt;br/&gt;&lt;br/&gt;&lt;code&gt;double VerifyLotSize(string argSymbol,double argLotSize) export&lt;br/&gt;{&lt;br/&gt;argLotSize=MarketInfo(argSymbol,MODE_LOTSTEP)==0.1?NormalizeDouble(argLotSize,1):NormalizeDouble(argLotSize,2);&lt;br/&gt;return MathMax(MarketInfo(argSymbol,MODE_MINLOT),MathMin(MarketInfo(argSymbol,MODE_MAXLOT),argLotSize));&lt;br/&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;In this standard implementation, I choose to close first all the profiting orders and then to close the losing ones. Reason for that is keeping the balance / equity high thus the margin % high so we will not run into unwanted situations. Once all the profiting ones are close, the losing ones are closed too. If there is a pending order, such a Stop or Limit one, it is taken care of separately in the ClosePendingOrder function.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Closing by Lot Size&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;With this implementation, I am closing all the profiting orders first and then I close the different orders according to their size until the profit == loss. I am using this function whenever there are large positions which are covered by other large positions and I want them to net each other. It is comfortable to call this function, leaving behind the small lots size orders which are still open:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllOrdersByLotSize(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;double MaxLotSize=0;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;double ClosedProfit=0;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0))&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if((OrderProfit()+OrderCommission()+OrderSwap())&amp;gt;=0)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(CloseOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Failed closing position #&quot;,IntegerToString(OrderTicket())),true,GetLastError());&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;ClosedProfit+=OrderProfit()+OrderCommission()+OrderSwap();&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;else if(OrderLots()&amp;gt;MaxLotSize)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;MaxLotSize=OrderLots();&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(double LotSize=MaxLotSize;LotSize&amp;gt;0;LotSize-=MarketInfo(argSymbol,MODE_MINLOT))&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int j=OrdersTotal()-1;j&amp;gt;=0;j--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(j,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; OrderLots()&amp;gt;=LotSize &amp;amp;&amp;amp; (ClosedProfit+OrderProfit()+OrderCommission()+OrderSwap())&amp;gt;=0)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(CloseOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Log(StringConcatenate(&quot;Failed closing position #&quot;,IntegerToString(OrderTicket())),true,GetLastError());&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;ClosedProfit+=OrderProfit()+OrderCommission()+OrderSwap();&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;The first loop finds the highest order lots size, the second double loop goes through the different orders and closes them if their lot size is higher than the current one. Once a loop is completed, the current lot size reference decreases with the minimum lot avaialble - &lt;code&gt;LotSize-=MarketInfo(argSymbol,MODE_MINLOT)&lt;/code&gt;.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Closing by Type&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;These functions close all orders according to their type, whether they are long or short:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllLongOrders(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; CloseOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;and&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllShortOrders(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; CloseOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;It is closing the open orders as well as the pending ones.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Closing by Profit&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;These functions close all the profiting orders or the losing ones:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllProfitingOrders(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; (OrderProfit()+OrderCommission()+OrderSwap())&amp;gt;0 &amp;amp;&amp;amp; CloseOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;and&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllLosingOrders(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; (OrderProfit()+OrderCommission()+OrderSwap())&amp;lt;0 &amp;amp;&amp;amp; CloseOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Closing Live vs. Pending Orders&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Finally, these functions close all live orders or pending ones:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllLiveOrders(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; (OrderType()==OP_BUY || OrderType()==OP_SELL) &amp;amp;&amp;amp; CloseOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;and&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool CloseAllPendingOrders(string argSymbol=&quot;&quot;) export&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;{&lt;/code&gt;&lt;br/&gt;&lt;code&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; (StringLen(argSymbol)==0 || StringCompare(argSymbol,OrderSymbol())==0) &amp;amp;&amp;amp; OrderType()!=OP_BUY &amp;amp;&amp;amp; OrderType()!=OP_SELL &amp;amp;&amp;amp; ClosePendingOrder(OrderTicket())==false)&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return false;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;Sleep(250);&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;code&gt;return true;&lt;/code&gt;&lt;br/&gt;&lt;code&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;In Common.&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;All the functions are boolean and return the failure / success upon completion, you may use it and act accordingly if something went wrong.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;All the functions starts closing from the last function and works backwards to the first one.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;All the functions have a sleeping time between each closure, to prevent overflooding the running thread and miss an order closure.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;As always, I am happy for any inquiries or suggestions for post per &lt;a href=&quot;mailto:sales@ilantree.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;email&lt;/a&gt; and / or &lt;a href=&quot;tel:+41762365958&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;mobile&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/1935116177422459442/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/10/mql-functions-to-close-all-orders_14.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1935116177422459442'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1935116177422459442'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/10/mql-functions-to-close-all-orders_14.html' title='MQL Functions to Close All Orders'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-4338377645085942198</id><published>2018-08-28T17:40:00.001+02:00</published><updated>2019-01-21T13:04:39.937+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="algotrading"/><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="FX"/><category scheme="http://www.blogger.com/atom/ns#" term="MetaTrader4"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><category scheme="http://www.blogger.com/atom/ns#" term="Video"/><title type='text'>FX Algotrading Q&amp;A Session 16/08/2018</title><content type='html'>On the 16th August I delivered a webinar on the topic of &quot;introduction to FX Algotrading&quot;. In this 40 minutes I introduced myself, the strategies I am running and the platform I am using.&lt;br /&gt;&lt;br /&gt;Here is the replay:&lt;br /&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;iframe width=&quot;320&quot; height=&quot;266&quot; class=&quot;YOUTUBE-iframe-video&quot; data-thumbnail-src=&quot;https://i.ytimg.com/vi/eNARvgKiJ7s/0.jpg&quot; src=&quot;https://www.youtube.com/embed/eNARvgKiJ7s?feature=player_embedded&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/4338377645085942198/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/08/fx-algotrading-q-session-16082018_28.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4338377645085942198'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4338377645085942198'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/08/fx-algotrading-q-session-16082018_28.html' title='FX Algotrading Q&amp;amp;A Session 16/08/2018'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/eNARvgKiJ7s/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-1658129165960151968</id><published>2018-08-20T14:00:00.001+02:00</published><updated>2019-01-18T21:41:05.388+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Coding"/><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><title type='text'>Toggling the Auto Trading Button in MQL4</title><content type='html'>&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;In this post, I will introduce an MQL4 code I use to control remotely the auto trading button on/off status, this code is part of the RemoteControl library product available for purchase &lt;a href=&quot;https://www.ilantree.com/downloads/remote-control/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;There are some scenarios where we would like to stop trading completely such as:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;Extreme market conditions or&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Below a certain equity threshold.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Negative P&amp;amp;L below a certain threshold.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;But when we are not near the PC, this could be a challenging task to do. We can either close all of our positions and take some loss, or, let the positions run and hope for the best…&lt;br/&gt;&lt;br/&gt;In this post, I will introduce a code snippet which you can plant in your code, which upon certain conditions can mimic halt trading by toggling the auto trading button on / off:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;aligncenter wp-image-847 size-full&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/08/Autotrade-Button.png&quot; alt=&quot;Auto Trading Button Toggled to On State&quot; width=&quot;1096&quot; height=&quot;82&quot; /&gt;&lt;br/&gt;&lt;br/&gt;So, upon executing this code, the button will be toggled between on and off, and you will get notified about the new state.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Implementation&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;First of all, we need to modify the WinUser32.mqh which is shipped as part of the MetaEditor installation, by adding the following two lines:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;int GetAncestor(int hWnd,int uCmd); - A function to get the parent of the current window, will be used later on to get the handler of the chart parent, the MetaTrader workstation.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;#define WM_AUTOTRADING 0x80FC – A constant holding the toggle auto trading&lt;br/&gt;button action. Will be used later on as part of the call for an action message.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;The code is as follows:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;ResetLastError();&lt;br/&gt;int hWnd=GetAncestor(WindowHandle(Symbol(),Period()),GA_ROOT);&lt;br/&gt;if(hWnd!=-1)&lt;br/&gt;{&lt;br/&gt;if(PostMessageA(hWnd,WM_COMMAND,WM_AUTOTRADING,0)!=0)&lt;br/&gt;SendNotification(StringConcatenate(&quot;Toggling automated trading button succeeded, &quot;,OriginalTradeAllowedFlag==false?&quot;trading enabled&quot;:&quot;trading disabled&quot;));&lt;br/&gt;else&lt;br/&gt;SendNotification (&quot;Toggling automated trading button failed messaging the button&quot;);&lt;br/&gt;}&lt;br/&gt;else&lt;br/&gt;SendNotification (&quot;Toggling automated trading button failed getting the ancestor window&quot;);&lt;br/&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;First, I reset the last error to make sure, that if something goes wrong, we have the latest error code.&lt;br/&gt;&lt;br/&gt;Then, using the call to GetAncestor, I getting a window handler to the parent window of the current chart. In our case, this is the MetaTrader application itself.&lt;br/&gt;&lt;br/&gt;If the call was successful, and hWnd isn’t -1, rather a handler to the root window. We post a message to that window using the function PostMessageA, which mimic the behavior of clicking the automated trading button. The WM_ AUTOTRADING constant holds the value of the button clicking event.&lt;br/&gt;&lt;br/&gt;If successful, the function will return a non-zero value and the button will be clicked to look as:&lt;br/&gt;&lt;img class=&quot;aligncenter wp-image-846 size-full&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/08/Autotrade-Button-Pressed.jpg&quot; alt=&quot;Auto Trading Button Toggled to Off State&quot; width=&quot;1072&quot; height=&quot;54&quot; /&gt;&lt;br/&gt;&lt;br/&gt;At this point, no trading is possible and the following functions will fail - OrderSend(), OrderClose(), OrderCloseBy(), OrderModify(), OrderDelete(). We can always call this function again once the risk condition was finished and we are interested to start trading again.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Usage&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;I am using this logic across my expert advisers in the following manners:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if((IsTradeAllowed()==true &amp;amp;&amp;amp; AccountInfoDouble(ACCOUNT_MARGIN_LEVEL)&amp;gt;0 &amp;amp;&amp;amp; AccountInfoDouble(ACCOUNT_MARGIN_LEVEL)&amp;lt;200) || (IsTradeAllowed()==false &amp;amp;&amp;amp; AccountInfoDouble(ACCOUNT_MARGIN_LEVEL)&amp;gt;400))&lt;br/&gt;{&lt;br/&gt;“TOGGLE AUTOMATED TRADING BUTTON”&lt;br/&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Meaning, I set certain threshold levels, in this case 200 and 400. If the account margin level in % goes below 200%, I will disable the trading by firing this event. Then, if the account margin level goes above 400%, I will switch trading back again. I am using the IsTradeAllowed function to verify the current state before firing this event. Normally, I put this logic in the OnTimer() function which I call on an hourly basis, but you may plant anywhere you’d like.&lt;br/&gt;&lt;br/&gt;Or:&lt;br/&gt;&lt;br/&gt;Using my remote-control framework to fire a message based on a OP_BUYSTOP message with the value of 1011 as explained in this &lt;a href=&quot;https://www.ilantree.com/remote-controlling-an-expert-adviser-pattern/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;post&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;As always, I am happy for any inquiries or suggestions for post per &lt;a href=&quot;mailto:sales@ilantree.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;email&lt;/a&gt; and / or &lt;a href=&quot;tel:+41762365958&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;mobile&lt;/a&gt;.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/1658129165960151968/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/08/toggling-auto-trading-button-in-mql4_20.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1658129165960151968'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1658129165960151968'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/08/toggling-auto-trading-button-in-mql4_20.html' title='Toggling the Auto Trading Button in MQL4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-3325974611127214663</id><published>2018-08-12T11:25:00.001+02:00</published><updated>2019-01-18T21:41:05.282+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="Hedging"/><category scheme="http://www.blogger.com/atom/ns#" term="MetaTrader4"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><title type='text'>Linear Hedging Framework for MQL4</title><content type='html'>&lt;h2&gt;Introduction&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;When opening an order, we are all hoping that our analysis was correct and our position will make a profit. But, when this is not the case, there are in general three possibilities to continue:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Close the order upon a predefined stop-loss, if we were able to close the order on the opening price, then it&#39;s even better and no harm was done - The challenge with this approach is to know where to set the stop loss point, not to make too tight so it doesn&#39;t get hit quick, or too wide and then the loss is massive.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Let the order run and hope that at some case the trend will reverse and our analysis was correct - Challenging as well, since we will never know with 100% accuracy that this level will be reached again, so in the meantime our P&amp;amp;L gets more and more negative and we make loss on the swap if it is against us.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;strong&gt;Hedge the order&lt;/strong&gt; - meaning opening an opposite order upon a predefined gap and close it once the orders cancel each other profit wise.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;I will dedicate this post to the third option and introduce a linear hedging framework I use myself.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Linear Hedging Framework Explained&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;High level logic&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Before diving into the code itself, I will explain the behavior high level:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;We open an order and let it run, if it reaches our take profit target, fine, happy days we close it and move on to the next order. If not...&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;We open a second order with the same direction and size after a predefined pips gap, for example 500 pips. Then, if the 2nd order, which is the hedge in this case, goes up 250 pips, both orders cancel each other and we close both of them. If not...&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;We open a third order with the same direction, but this time we use twice the lots. Following the logic above, if it climbs up 375 pips, we will close all the three positions.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;We continue opening orders according to this series 1x 1x 2x 2x 3x 3x 4x 4x... where x is the original lot size.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;The gap between the orders can be a fixed value or according to some indicator such as volatility/standard deviation.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;This method is not dangerous as the infamous martingale in that the margin is reasonable and doesn&#39;t cause the account to explode. I am running a live account using this system with the gap set to 500 pips and so far, I didn&#39;t have any issues whatsoever. You are welcome to use this code as you wish, stick it in your expert adviser and share the results with me.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;MQL4 Full Code&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;The full code is as follows:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;const string SYMBOL=Symbol();&lt;br/&gt;const double CLEANUP_TRIGGER=500*MarketInfo(SYMBOL,MODE_POINT);&lt;br/&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if(CleanupFlag==true)&lt;br/&gt;{&lt;br/&gt;CleanupFlag=false;&lt;br/&gt;&lt;br/&gt;for(int i=OrdersTotal()-1;i&amp;gt;=0;i--)&lt;br/&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; StringCompare(SYMBOL,OrderSymbol())==0 &amp;amp;&amp;amp; StringLen(OrderComment())!=0)&lt;br/&gt;{&lt;br/&gt;CleanupFlag=true;&lt;br/&gt;&lt;br/&gt;string Tickets=IntegerToString(OrderTicket());&lt;br/&gt;double Profit=OrderProfit()+OrderCommission()+OrderSwap();&lt;br/&gt;&lt;br/&gt;while(StringFind(OrderComment(),&quot;;&quot;)!=-1)&lt;br/&gt;{&lt;br/&gt;string TheCommentDetails[];&lt;br/&gt;StringSplit(OrderComment(),StringGetCharacter(&quot;;&quot;,0),TheCommentDetails);&lt;br/&gt;if(OrderSelect((int)StringToInteger(TheCommentDetails[1]),SELECT_BY_TICKET) &amp;amp;&amp;amp; OrderCloseTime()==0)&lt;br/&gt;{&lt;br/&gt;Tickets=StringConcatenate(IntegerToString(OrderTicket()),&quot;;&quot;,Tickets);&lt;br/&gt;Profit+=OrderProfit()+OrderCommission()+OrderSwap();&lt;br/&gt;}&lt;br/&gt;else&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed selecing ticket #&quot;,IntegerToString(OrderTicket()),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;if(Profit&amp;gt;0)&lt;br/&gt;{&lt;br/&gt;string TheTickets[];&lt;br/&gt;if(StringSplit(Tickets,StringGetCharacter(&quot;;&quot;,0),TheTickets)&amp;gt;1)&lt;br/&gt;for(int j=ArraySize(TheTickets)-1;j&amp;gt;=0;j--)&lt;br/&gt;if(OrderSelect((int)StringToInteger(TheTickets[j]),SELECT_BY_TICKET) &amp;amp;&amp;amp; OrderCloseTime()==0 &amp;amp;&amp;amp; CloseOrder((int)StringToInteger(TheTickets[j]))==false)&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed closing ticket #&quot;,IntegerToString(OrderTicket()),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;for(int i=OrdersTotal()-1;i&amp;gt;=0;&lt;br/&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; StringCompare(SYMBOL,OrderSymbol())==0 &amp;amp;&amp;amp; (OrderProfit()+OrderSwap()+OrderCommission())&amp;lt;0 &amp;amp;&amp;amp; MathAbs(OrderOpenPrice()-iClose(SYMBOL,PERIOD_M1,0))&amp;gt;CLEANUP_TRIGGER)&lt;br/&gt;{&lt;br/&gt;CleanupFlag=true;&lt;br/&gt;&lt;br/&gt;bool HedgeExists=false;&lt;br/&gt;int TheTicket=OrderTicket();&lt;br/&gt;int TheTicketType=OrderType();&lt;br/&gt;string TheTicketComment=OrderComment();&lt;br/&gt;&lt;br/&gt;for(int j=OrdersTotal()-1;j&amp;gt;=0;j--)&lt;br/&gt;if(OrderSelect(j,SELECT_BY_POS) &amp;amp;&amp;amp; StringCompare(SYMBOL,OrderSymbol())==0)&lt;br/&gt;{&lt;br/&gt;string TheCommentDetails[];&lt;br/&gt;if(StringSplit(OrderComment(),StringGetCharacter(&quot;;&quot;,0),TheCommentDetails)==2)&lt;br/&gt;{&lt;br/&gt;if(StringToInteger(TheCommentDetails[1])==TheTicket)&lt;br/&gt;{&lt;br/&gt;HedgeExists=true;&lt;br/&gt;break;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;if(HedgeExists==true)&lt;br/&gt;continue;&lt;br/&gt;else if(StringFind(TheTicketComment,&quot;;&quot;)==-1)&lt;br/&gt;{&lt;br/&gt;if(OpenOrder(SYMBOL,TheTicketType,LOTS,0,0,StringConcatenate(IntegerToString(2),&quot;;&quot;,IntegerToString(TheTicket)))==-1)&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed opening a cleanup position on ticket #&quot;,IntegerToString(TheTicket),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;else&lt;br/&gt;{&lt;br/&gt;string TheCommentDetails[];&lt;br/&gt;StringSplit(TheTicketComment,StringGetCharacter(&quot;;&quot;,0),TheCommentDetails);&lt;br/&gt;if(OpenOrder(SYMBOL,TheTicketType,(int)MathCeil((double)(StringToInteger(TheCommentDetails[0])+1)/2)*LOTS,0,0,StringConcatenate(IntegerToString(StringToInteger(TheCommentDetails[0])+1),&quot;;&quot;,IntegerToString(TheTicket)))==-1)&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed opening a cleanup position on ticket #&quot;,IntegerToString(TheTicket),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Breaking It Down&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Setting the Gap&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;As mentioned, the first step is deciding what will be the gap we let an order run until we hedge it. This is the same like having a stop loss at the point, but instead, we open another trade with the same direction. In my case, following some exhaustive testing, I realized that a fixed gap works the best for me:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;const string SYMBOL=Symbol();&lt;br/&gt;const double CLEANUP_TRIGGER=500*MarketInfo(SYMBOL,MODE_POINT);&lt;br/&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;In this case, I set the cleanup trigger to 500 pips, so every 500 pips against the order type original direction a new hedge will open.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Hedging&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;The acutal code to open a new hedge is straightforward. Simply go through the open orders and check if any of their open price is remote from the current price with more than the predefined gap:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;for(int i=OrdersTotal()-1;i&amp;gt;=0;i--) &lt;br/&gt;    if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; StringCompare(SYMBOL,OrderSymbol())==0 &amp;amp;&amp;amp; (OrderProfit()+OrderSwap()+OrderCommission())&amp;lt;0 &amp;amp;&amp;amp; MathAbs(OrderOpenPrice()-iClose(SYMBOL,PERIOD_M1,0))&amp;gt;CLEANUP_TRIGGER)&lt;br/&gt;        {&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Then, go through all the open orders and check if there is already a hedge open for this order.&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;CleanupFlag=true; &lt;br/&gt;bool HedgeExists=false; &lt;br/&gt;int TheTicket=OrderTicket(); &lt;br/&gt;int TheTicketType=OrderType(); &lt;br/&gt;string TheTicketComment=OrderComment(); &lt;br/&gt;for(int j=OrdersTotal()-1;j&amp;gt;=0;j--) &lt;br/&gt;if(OrderSelect(j,SELECT_BY_POS) &amp;amp;&amp;amp; StringCompare(SYMBOL,OrderSymbol())==0) &lt;br/&gt;{ &lt;br/&gt;string TheCommentDetails[]; if(StringSplit(OrderComment(),StringGetCharacter(&quot;;&quot;,0),TheCommentDetails)==2) &lt;br/&gt;{&lt;br/&gt;if(StringToInteger(TheCommentDetails[1])==TheTicket)&lt;br/&gt;{ &lt;br/&gt;HedgeExists=true; break; &lt;br/&gt;} &lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Notice that I am using the order comment to tag the order being hedged by a two size array:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;TheCommentDetails[0] will hold the hedge level we have at the moment, the higher the level, the bigger the lot size we will open.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;TheCommentDetails[1] will hold the order number being hedged, so when the loop is running, we compare if the current prolematic order was hedged already or not.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;If there is no hedge for this order, we will open one:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if(HedgeExists==true)&lt;br/&gt;continue;&lt;br/&gt;else if(StringFind(TheTicketComment,&quot;;&quot;)==-1)&lt;br/&gt;{&lt;br/&gt;if(OpenOrder(SYMBOL,TheTicketType,LOTS,0,0,StringConcatenate(IntegerToString(2),&quot;;&quot;,IntegerToString(TheTicket)))==-1)&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed opening a cleanup position on ticket #&quot;,IntegerToString(TheTicket),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;else&lt;br/&gt;{&lt;br/&gt;string TheCommentDetails[];&lt;br/&gt;StringSplit(TheTicketComment,StringGetCharacter(&quot;;&quot;,0),TheCommentDetails);&lt;br/&gt;if(OpenOrder(SYMBOL,TheTicketType,(int)MathCeil((double)(StringToInteger(TheCommentDetails[0])+1)/2)*LOTS,0,0,StringConcatenate(IntegerToString(StringToInteger(TheCommentDetails[0])+1),&quot;;&quot;,IntegerToString(TheTicket)))==-1)&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed opening a cleanup position on ticket #&quot;,IntegerToString(TheTicket),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Closing Hedges&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;Finally, we go over a loop and check for all the orders, if the hedges sum &amp;gt; 0. If yes, we close them all:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if(CleanupFlag==true)&lt;br/&gt;{&lt;br/&gt;CleanupFlag=false;&lt;br/&gt;&lt;br/&gt;for(int i=OrdersTotal()-1;i&amp;gt;=0;i--)&lt;br/&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; StringCompare(SYMBOL,OrderSymbol())==0 &amp;amp;&amp;amp; StringLen(OrderComment())!=0)&lt;br/&gt;{&lt;br/&gt;CleanupFlag=true;&lt;br/&gt;&lt;br/&gt;string Tickets=IntegerToString(OrderTicket());&lt;br/&gt;double Profit=OrderProfit()+OrderCommission()+OrderSwap();&lt;br/&gt;&lt;br/&gt;while(StringFind(OrderComment(),&quot;;&quot;)!=-1)&lt;br/&gt;{&lt;br/&gt;string TheCommentDetails[];&lt;br/&gt;StringSplit(OrderComment(),StringGetCharacter(&quot;;&quot;,0),TheCommentDetails);&lt;br/&gt;if(OrderSelect((int)StringToInteger(TheCommentDetails[1]),SELECT_BY_TICKET) &amp;amp;&amp;amp; OrderCloseTime()==0)&lt;br/&gt;{&lt;br/&gt;Tickets=StringConcatenate(IntegerToString(OrderTicket()),&quot;;&quot;,Tickets);&lt;br/&gt;Profit+=OrderProfit()+OrderCommission()+OrderSwap();&lt;br/&gt;}&lt;br/&gt;else&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed selecing ticket #&quot;,IntegerToString(OrderTicket()),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;if(Profit&amp;gt;0)&lt;br/&gt;{&lt;br/&gt;string TheTickets[];&lt;br/&gt;if(StringSplit(Tickets,StringGetCharacter(&quot;;&quot;,0),TheTickets)&amp;gt;1)&lt;br/&gt;for(int j=ArraySize(TheTickets)-1;j&amp;gt;=0;j--)&lt;br/&gt;if(OrderSelect((int)StringToInteger(TheTickets[j]),SELECT_BY_TICKET) &amp;amp;&amp;amp; OrderCloseTime()==0 &amp;amp;&amp;amp; CloseOrder((int)StringToInteger(TheTickets[j]))==false)&lt;br/&gt;{&lt;br/&gt;Log(StringConcatenate(&quot;Failed closing ticket #&quot;,IntegerToString(OrderTicket()),&quot; line &quot;,__LINE__));&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;Stay tuned for my next webinar &quot;&lt;a href=&quot;https://www.facebook.com/events/2058217767772857/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;FX Algotraind Q&amp;amp;A&lt;/a&gt;&quot; scheduled for Thursday 16th August, 19:00-20:00 GMT+2.&lt;br/&gt;&lt;br/&gt;For any inquiries, please don’t hesitate to contact me per &lt;a href=&quot;mailto:sales@ilantree.com&quot;&gt;email&lt;/a&gt; or &lt;a href=&quot;tel:+41762365958&quot;&gt;mobile&lt;/a&gt;.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/3325974611127214663/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/08/linear-hedging-framework-for-mql4_12.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3325974611127214663'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3325974611127214663'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/08/linear-hedging-framework-for-mql4_12.html' title='Linear Hedging Framework for MQL4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-3859492562425994419</id><published>2018-07-29T21:50:00.001+02:00</published><updated>2019-01-18T21:41:05.171+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>FX Trading Q&amp;A</title><content type='html'>&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Since I joined Quora platform, my &lt;a href=&quot;https://www.quora.com/profile/IlanTree&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;profile&lt;/a&gt; is overflooded with questions to do with FX Trading, investig and algotrading. The goal of this post is to summarize the different quetsions I answered already so there is single point to search.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Questions &amp;amp; Answers&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;How long did it take you to become a profitable trader?&lt;/strong&gt;&lt;br/&gt;I started in 2008, but only in the last three years my hard work started to pay off. Until then, it was mostly losses, mistakes, wrong strategies and decisions.&lt;br/&gt;&lt;br/&gt;The main things I wish I knew back then:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;Choose the right broker, one that has the best execution, minimal spreads and excellent customer service. Those who offer gifts and bonuses were mainly causing me more damage than benefit. I did find Darwinex but it took me ages.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Don&#39;t buy robots, develop your own strategy. All the robots I bought was a complete disaster and cause me more losses, I learned the hard way that no one sells a successful strategy.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Keep the leverage as low as possible, never use the full leverage offered by the broker.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Earn less but many times, meaning to open small positions and make small profits that accumulate than big positions with high moving p&amp;amp;l.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;Later on, when I got confident enough, I started writing a blog myself on Algotrading to share my exprience.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What trading rules do you use or are generally considered best practices in financial speculation?&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;Personally, the most important one is risk management which mainly rolls around keeping the effective margin below 1:10 ratio. Calculating the effective ratio is straightforward:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Sum all the lots you have opened.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Multiply with 100,000&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Divide with your equity&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;for example, assuming we have 1.5 lots open, it means we control 150,000 units. If we have an equity of 1,000, the effective leverage is 1:15… getting risky.&lt;br/&gt;&lt;br/&gt;In my blog, I dedicated a full entry on &lt;a href=&quot;https://www.ilantree.com/leverage-explained/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;risk&lt;/a&gt; management tools I use, if you’re into algorithmic trading, it might interest you as well.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;How can I be a forex trader?&lt;/strong&gt;&lt;br/&gt;Start by learning what is trade all about and start trading a demo account to get a feeling about it. From educational point of view The School of Pipsology is our free online course that helps beginners learn how to trade forex. If you&#39;ve always wanted to learn to trade but have no idea where to begin, then this course is for you - &lt;a href=&quot;https://www.babypips.com/learn/forex&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;School of Pipsology&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What is the best free trading course?&lt;/strong&gt;&lt;br/&gt;&lt;a href=&quot;https://www.babypips.com/learn/forex&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;School of Pipsology&lt;/a&gt; is a really good start, I used it myself when I started trading. It is build as different levels starting from the basics of pip definition all the way up to advanced indicators and risk management topics.&lt;br/&gt;&lt;br/&gt;“The School of Pipsology is our free online course that helps beginners learn how to trade forex. If you&#39;ve always wanted to learn to trade but have no idea where to begin, then this course is for you.”&lt;br/&gt;&lt;br/&gt;If you want to learn about FX Algotrading, I have several articles in my site Ilan Tree - FX Trading 2.0 about this topic as well adics a dedicated &lt;a href=&quot;https://www.ilantree.com/course/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;course&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What should I learn before starting trading as begginer?&lt;/strong&gt;&lt;br/&gt;You may have a look at &lt;a href=&quot;https://www.babypips.com/learn/forex&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;School of Pipsology&lt;/a&gt; as a starting point, to understand the basics of trading Forex, right from the pip value.&lt;br/&gt;&lt;br/&gt;Once you grasp the knowledge of manual trading, perhaps you will have the interest to move to automated, then you may check Ilan Tree - FX Trading 2.0 &lt;a href=&quot;https://www.ilantree.com/course/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;course&lt;/a&gt; for understanding how to do with MetaTrader and MQL4.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What is your favorite trading (forex, stocks, crypto, etc) platform and why?&lt;/strong&gt;&lt;br/&gt;I only trade FX actively, the other products like stocks and crypto are done passively. I do so from several reasons:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;Liquidity - FX is a very liquid product which is always available for purchasing and selling.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Spread - is minimal and can be close to zero.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Volatility - active and moving quite a lot compare to stocks.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Hard to manipulate the price compare to other products.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;I do my trading solely with expert advisers trading on my behalf 24/5. I interfere only when needed, otherwise, I let them run. While with the other products, the market times are changing and available around certain hours.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What percent per year do you make with automated trading strategies? Is it possible to create a profitable strategy based on something as simple as RSI or moving averages crossover?&lt;/strong&gt;&lt;br/&gt;I am running several strategies in parallel on EURUSD, all have a different reutrn per month but more importantly, they are not correlated.&lt;br/&gt;&lt;br/&gt;In general, I am aiming to have between 1–5% return per month. I keep the strategies as simple as possible, but the risk management is the complicated thing. So, for example one of my strategies is using internal bar strength indicator as a signal, but the strategy risk management makes it a profitable one.&lt;br/&gt;&lt;br/&gt;This strategy for example - &lt;a href=&quot;https://www.ilantree.com/investment/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Investment&lt;/a&gt; - Ilan Tree is based on bollinger bands. So, you may as simple as you want, but the risk management will be the edge to make your trading a successful one.&lt;br/&gt;&lt;br/&gt;I currently use a fix loss value as a border, if the P&amp;amp;L goes below it, the algorithm starts to close positions smartly and go bac into the reasonable levels.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;How can I develop a trading robot or Forex signal prediction software using JavaScript?&lt;/strong&gt;&lt;br/&gt;I am using MQL4 solely for my trading purposes, I didn&#39;t have the chance to use JavaScript and honestly I don&#39;t see the added value in doing so.&lt;br/&gt;&lt;br/&gt;If you&#39;re looking to learn about algorithmic trading, have a look at my website Ilan Tree - FX Trading 2.0 and discover how the MetaTrader language works, you might find it simpler than JavaScript and faster time to market.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Must every forex trader have a Myfxbook account?&lt;/strong&gt;&lt;br/&gt;No, it’s absolutely optional for you to have an account in Myfxbook, it is mainly used to track your performance and show case to potential investors but it’s not a must.&lt;br/&gt;&lt;br/&gt;I personally don’t have an account there as I show case my performance in my personal &lt;a href=&quot;https://www.ilantree.com/investment/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;website&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What is your experience of Darwinex, in particular the slippage on connecting your account to a trader?&lt;/strong&gt;&lt;br/&gt;I use Darwinex brokerage services since two years and so far I can warmly recommend it. The slippage is perfect, their execution is flawless and there are many financial benefits.&lt;br/&gt;&lt;br/&gt;I have my own strategy running over their platform, you may see it in my &lt;a href=&quot;https://www.ilantree.com/investment/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;website&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What are the various sources of capital for a sole trader?&lt;/strong&gt;&lt;br/&gt;There are couple of sources:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;Own capital, using savings and/or money you don’t mind putting in risk.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Family/friends&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Loans - least recommended if you’re not having a winning strategy which can cover the loan.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Rebates and awards from your broker - personally I am trading with Darwinex who offers rebates on the trading commissions and a competition for the best 48 traders.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;If you have a strategy you want to automate, consider writing a code which does what you do manually, then you can minimize the emotional risks involved with trading, see here for some coding examples.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What strategy do you prefer for Intraday Trading, trend following or setting a target and exiting it when the target is achieved?&lt;/strong&gt;&lt;br/&gt;I always follow the trend and let the winners run, the losers closed. This can be achieved by having a stop loss which progress with the trend or an algorithm which checks every X minutes the current status and makes a decision on what to do next.&lt;br/&gt;&lt;br/&gt;See my blog for some ideas how to automate your trading in case that something you thought on doing.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;How generic should algorithmic trading be? Should it fit in many pair forex or only one it is okay?&lt;/strong&gt;&lt;br/&gt;It&#39;s a matter of taste, some make it unique to a specific pair but have the risk of over fitting their algorithm. So, when a new information comes, their algorithm fails miserably.&lt;br/&gt;&lt;br/&gt;I do as generic as possible so I am able to run it on multiple currencies. Having it simple makes it easier to track the algorithm and understand what went right or wrong.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Are there any trading platforms that run on Linux?&lt;/strong&gt;&lt;br/&gt;You can even have MetaTrader running on Linux if you follow this article- &lt;a href=&quot;https://www.metatrader4.com/en/trading-platform/help/userguide/install_linux&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Install on Linux&lt;/a&gt; - Getting Started - MetaTrader 4 Help. I did so myself on my Mac and it works flawlessly.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Does a college degree matter to be a trader? I find all the stuff in my high school class as irrelevant to Forex, stocks and crypto trading.&lt;/strong&gt;&lt;br/&gt;No, there’s nothing you can’t study online nowadays including trading. There’s so much material available online which can focus on forex, stocks, trading etc.&lt;br/&gt;&lt;br/&gt;Personally, I taught myself programming expert advises which are algorithms running in MetaTrader and trade the market on my behalf. I share what I learn in my website and you are welcome to visit and educate yourself.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Is Forex trading easy or difficult?&lt;/strong&gt;&lt;br/&gt;It’s all a matter of practice and knowledge. Nowadays you can learn a lot online and get equipped with the right tools to succeed. I am in it for years, started manually and now it’s fully automated.&lt;br/&gt;&lt;br/&gt;First, you need to decide what are your goals with trading, if it’s to become a millionaire or financially free, I chose the latter as it is more realistic.&lt;br/&gt;&lt;br/&gt;As the first step, visit a good website to learn it, something like Learn Forex Trading With BabyPips.com, and then, once you did some trading in demo and real account, think about automating your trading.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What broker provides an international trading account in euro?&lt;/strong&gt;&lt;br/&gt;The broker I work with and prefer over all the others I used offers it - &lt;a href=&quot;https://www.darwinex.com/darwin/GFA.4.21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Darwinex&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;You may see examples for algorithmic trading in my website if that’s your goal in trading - www.ilantree.com.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;What do you think about online forex trading platforms, and what platform is best and most safe to trade with?&lt;/strong&gt;&lt;br/&gt;It depends on your needs and legal situation, I personally use &lt;a href=&quot;https://www.darwinex.com/darwin/GFA.4.21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Darwinex&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;How should I start creating my own trading bot with no foundation in coding?&lt;/strong&gt;&lt;br/&gt;You can learn MQL programming online, or register to an online &lt;a href=&quot;https://www.ilantree.com/course/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;course&lt;/a&gt; like I am leading.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Is quantitative trading as simple as coding TA rules/strategies into MQL and creating an EA? Is there more to it?&lt;/strong&gt;&lt;br/&gt;There are many things to consider like:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;Finding the right broker&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Finding a winning strategy&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Managing the risk&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;etc.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;On the programming side, I am leading a course to educate beginners on writing their own expert advisers, check it &lt;a href=&quot;https://www.ilantree.com/course/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;Does Algotech trading work and how?&lt;/strong&gt;&lt;br/&gt;Yes, if you have the right strategy in hand and you are able to monitor and intervene when things go out of control you can make a living out of it.&lt;br/&gt;&lt;br/&gt;It’s a combination of having a good strategy and the right broker, for me it took several years to find the broker and the strategy. I trade mainly with &lt;a href=&quot;https://www.ilantree.com/investment/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Darwinex&lt;/a&gt; and I publish my strategy performance for interested investors.&lt;br/&gt;&lt;br/&gt;If you’re interested to learn about Algotrading, I have my own course with the following &lt;a href=&quot;https://www.ilantree.com/course/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;syllabus&lt;/a&gt;. It all depends on you in this field, it’s not easy, but super interesting.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/3859492562425994419/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/07/fx-trading-q_29.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3859492562425994419'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3859492562425994419'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/07/fx-trading-q_29.html' title='FX Trading Q&amp;amp;A'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-7069702982498034149</id><published>2018-07-12T17:08:00.001+02:00</published><updated>2019-02-06T14:22:23.003+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="algotrading"/><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="Expert advisers"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><title type='text'>Moving Averages Trader Implementation for MetaTrader 4</title><content type='html'>&lt;h3&gt;Introduction&lt;/h3&gt;Moving averages trading is the most basic and common trading strategy. It is quoted in most of the trading books and articles and is very easy to follow and implement. The basic strategy is two moving averages, a fast one which is adjusting quicker to the current trend than a slow one.&lt;br /&gt;&lt;br /&gt;A classic setup is looking at the 50 days moving average of a certain product and check whether it is above or below the 200 days moving average. If it is above, it is an indicator for going long with this product, if it is below, it is an indicator to short the product.&lt;br /&gt;&lt;br /&gt;In this post, I will introduce a basic implementation of an expert adviser, which based on the inputs will trade the product using the price moving averages. You may use it as a basis for something else, modify it as you wish etc.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Input Parameters&lt;/h3&gt;These input parameters are controlling the moving average calculation:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;input int FastMovingAveragePeriod=50;//Fast Moving Average Period &lt;br /&gt;input int SlowMovingAveragePeriod=100;//slow Moving Average Period &lt;br /&gt;input ENUM_TIMEFRAMES Timeframe=PERIOD_D1;//Moving Average Timeframe &lt;br /&gt;input ENUM_MA_METHOD AveragingMethod=MODE_SMA;//Moving Average Averaging Method &lt;br /&gt;input ENUM_APPLIED_PRICE AppliedPrice=PRICE_CLOSE;//Moving Average Applied Price &lt;br /&gt;input int Shift=0;//Moving Average Shift&lt;br /&gt;input double Lots=0.01;//Order Lots&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The periods are defined as 50 for the fast moving average and 100 for the slow moving average, which control how many periods will look back when calculating the average.&lt;br /&gt;&lt;br /&gt;The Timeframe is the reference for the moving average calculation and data.&lt;br /&gt;&lt;br /&gt;The applied price influences which values we use for calculating the moving average.&lt;br /&gt;&lt;br /&gt;Shift is the moving average shift in value, the default value is 0, meaning calculating the present value. If you set it for 1 for example the moving average will be calculated on the previous period.&lt;br /&gt;&lt;br /&gt;Lots captures the volume to open an order, you may change it to a larger value based on your risk appetite.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Initialization&lt;/h3&gt;The OnInit() function is short and verify the periods input parameters. If the fast period is longer than the slow period, the function will return an error and the expert adviser will fail to start. So, when entering values for the periods, make sure that the FastMovingAveragePeriod is smaller than the SlowMovingAveragePeriod:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;int OnInit() { &lt;br /&gt;if(FastMovingAveragePeriod&amp;gt;=SlowMovingAveragePeriod) { &lt;br /&gt;SendNotification(&quot;Fast moving average period value must be smaller than the slow moving average period value&quot;); &lt;br /&gt;return INIT_PARAMETERS_INCORRECT; &lt;br /&gt;} &lt;br /&gt;return INIT_SUCCEEDED; &lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h2&gt;Trading Logic&lt;/h2&gt;&lt;h3&gt;Going Long&lt;/h3&gt;The first part of the algorithm checks whether the conditions match to go long on the product. It does so by comparing the current fast-moving average value to the slow one. If the fast-moving average value is &lt;strong&gt;larger&lt;/strong&gt; than the short moving average, it will close the short position (if any) and open a long one.&lt;br /&gt;&lt;br /&gt;Since we always have one order open, we can call the order select function, choose the only open order and close it safely, having in mind that if the fast is above the slow, there is a chance that the market trend is moving upwards:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;if(iMA(Symbol(),Timeframe,FastMovingAveragePeriod,0,AveragingMethod,AppliedPrice,0)&amp;gt;iMA(Symbol(),Timeframe,SlowMovingAveragePeriod,0,AveragingMethod,AppliedPrice,0)) &lt;br /&gt;{&lt;br /&gt;    if(OrdersTotal()&amp;gt;0 &amp;amp;&amp;amp; OrderSelect(0,SELECT_BY_POS) &amp;amp;&amp;amp; OrderType()==OP_SELL) &lt;br /&gt;    {&lt;br /&gt;        if(OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_ASK),SLIPPAGE)==false) &lt;br /&gt;        { &lt;br /&gt;            SendNotification(&quot;Something went wrong when closing an order, existing&quot;); ExpertRemove(); &lt;br /&gt;            return; &lt;br /&gt;         } &lt;br /&gt;    }&lt;br /&gt;    if(OrdersTotal()==0)&lt;br /&gt;    {&lt;br /&gt;        if(OrderSend(Symbol(),OP_BUY,Lots,MarketInfo(Symbol(),MODE_ASK),SLIPPAGE,0,0)==-1) &lt;br /&gt;        { &lt;br /&gt;            SendNotification(&quot;Something went wrong when opening an order, existing&quot;); &lt;br /&gt;            ExpertRemove(); &lt;br /&gt;            return;&lt;br /&gt;        }   &lt;br /&gt;    } &lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Going Short&lt;/h3&gt;The same logic goes for the short direction. Here, we are checking that the fast-moving average value is&amp;nbsp;&lt;strong&gt;smaller&lt;/strong&gt; than the long moving average value. If this is the case, we close the long position (if any) and open a short one:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;else &lt;br /&gt;{ &lt;br /&gt;    if(OrdersTotal()&amp;gt;0 &amp;amp;&amp;amp; OrderSelect(0,SELECT_BY_POS) &amp;amp;&amp;amp; OrderType()==OP_BUY) &lt;br /&gt;    { &lt;br /&gt;        if(OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_BID),SLIPPAGE)==false) &lt;br /&gt;        { &lt;br /&gt;            SendNotification(&quot;Something went wrong when closing an order, existing&quot;); &lt;br /&gt;            ExpertRemove(); &lt;br /&gt;            return; &lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    if(OrdersTotal()==0) &lt;br /&gt;    {&lt;br /&gt;        if(OrderSend(Symbol(),OP_SELL,Lots,MarketInfo(Symbol(),MODE_BID),SLIPPAGE,0,0)==-1)&lt;br /&gt;        { &lt;br /&gt;            SendNotification(&quot;Something went wrong when opening an order, existing&quot;); &lt;br /&gt;            ExpertRemove(); &lt;br /&gt;            return; &lt;br /&gt;         }&lt;br /&gt;     }&lt;br /&gt; }&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Testing&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;To see how this basic implementation performs, I ran it using the default values with my favorite currency - EURUSD - for the year 2017:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;As you see, most of the year, the fast-moving average was above the slow one, so the long position was dominant and captured more than 10,000 pips, or 103.56 dollars in profit. Towards the end of the year, the trend reversed and the a new sell position was opened.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Summary&lt;/h3&gt;I introduced a simple working MQL moving averages code for MetaTrader 4 which is available for download &lt;a href=&quot;http://ilantree.com/files/Experts/MovingAverageTrader.mq4&quot; rel=&quot;noopener&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. This strategy closes and opens a position as the trend changes using the moving averages crossover as an indicator. It is only a template and I would not recommend using it with real money, rather as an educational or a starting point for improved strategy such as the Martingale implementation &lt;a href=&quot;https://www.ilantree.com/mql-implementation-of-martingale-for-metatrader-4/&quot; rel=&quot;noopener&quot; target=&quot;_blank&quot;&gt;article&lt;/a&gt; was.&lt;br /&gt;&lt;br /&gt;As always, feel free to leave comments or join our discussion in&amp;nbsp;&lt;a href=&quot;https://www.facebook.com/groups/fxtrading2.0/&quot; rel=&quot;noopener&quot; target=&quot;_blank&quot;&gt;Facebook&lt;/a&gt;.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/7069702982498034149/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/07/moving-averages-trader-implementation_12.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7069702982498034149'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7069702982498034149'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/07/moving-averages-trader-implementation_12.html' title='Moving Averages Trader Implementation for MetaTrader 4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-541385027494042628</id><published>2018-06-26T18:25:00.001+02:00</published><updated>2019-01-18T21:41:04.879+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>5 Checks to Enhance your MQL4 Code</title><content type='html'>&lt;h3&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Throughout my years as an algotrader, I gained a lot experience with writing optimized MQL4 code. In this post, I am going to share some patterns I am using in my on robots. Some check for connectivity, some for spread, some for volatility etc. Embedding these code snippets in your own, will make your robot more resilient and you will more relax, as you will add self monitoring capabilities to it as well as better trade entry rules.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;&lt;strong&gt;Server Connectivity Check&lt;/strong&gt;&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;From time to time, MetaTrader station losses connectivity with the broker&#39;s server. And when that happens, normally, the only thing which works is to restart the platform (or hopefully wait the problem will fix itself). But how can you monitor the platform and get a notification once it is happening?&lt;br/&gt;&lt;br/&gt;That&#39;s exactly the solution I built for myself. Since the function OnTick() is not called anymore as there is no connectivity. The only solution was to place the monitoring in the OnTimer() function and check every X minutes, normally I do it once per hour.&lt;br/&gt;&lt;br/&gt;First, in the OnInit() function, I initialize the timer by calling:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;EventSetTimer(PERIOD_H1*60);&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;This is to call it once per hour, but you may also call it more frequently if you want.&lt;br/&gt;&lt;br/&gt;Then, in the OnTimer() function I use the following code:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;void OnTimer()&lt;br/&gt;  {&lt;br/&gt;   static bool IsDisconnectedFlag=false;&lt;br/&gt;   if(IsDisconnectedFlag==false &amp;amp;&amp;amp; IsConnected()==false)&lt;br/&gt;     {&lt;br/&gt;      SendNotification(StringConcatenate(IntegerToString(AccountNumber()),&quot;: Broker connection lost...&quot;));&lt;br/&gt;      IsDisconnectedFlag=true;&lt;br/&gt;     }&lt;br/&gt;   else if(IsDisconnectedFlag==true &amp;amp;&amp;amp; IsConnected()==true)&lt;br/&gt;     {&lt;br/&gt;      SendNotification(StringConcatenate(IntegerToString(AccountNumber()),&quot;: Broker connection retrieved...&quot;));&lt;br/&gt;      IsDisconnectedFlag=false;&lt;br/&gt;     }&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;First, I set a static variable called IsDisconnectedFlag to false. Then, I check, if the flag is false and the system is disconnected, I send a notification and set the flag to true (so I won&#39;t send the notification more than once). Then, in the next calls, if the system is still disconnected, I do nothing as the flag is already set to false. But, if the system got connected from its own, then I will send a notification to inform myself about it and set the IsDisconnectedFlag back to false.&lt;br/&gt;&lt;br/&gt;Finally, in the DeInit() function, I call EventKillTimer() to delete the timer.&lt;br/&gt;&lt;br/&gt;With this simple code pattern, I don&#39;t have the hassle anymore of checking server connectivity. My expert adviser runs and checks itself if the terminal connected to the broker or not, and notify me so I only need to act when needed.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;&lt;strong&gt;Platform Running Check&lt;/strong&gt;&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;What happens if the platform itself shut down unexpectedly? How would you know? It happened to me from time to time that the terminal itself crashed from whatever reason and I missed some good trades. If I wasn&#39;t checking the platform or paying attention that something is wrong, I would probably have missed it. So how can you get a notification as soon as the platform crashes?&lt;br/&gt;&lt;br/&gt;For that, I am using the following function which is placed within the OnDeinit() function:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;void OnDeinit(const int reason)&lt;br/&gt;{&lt;br/&gt;SendNotification(GetUninitReasonText(reason));&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;where&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;string GetUninitReasonText(int reasonCode) export&lt;br/&gt;{&lt;br/&gt;switch(reasonCode)&lt;br/&gt;{&lt;br/&gt;case REASON_PROGRAM:&lt;br/&gt;return &quot;Expert Advisor terminated its operation by calling the ExpertRemove() function&quot;;&lt;br/&gt;case REASON_REMOVE:&lt;br/&gt;return MQLInfoString(MQL_PROGRAM_NAME)+&quot; has been deleted from the chart&quot;;&lt;br/&gt;case REASON_RECOMPILE:&lt;br/&gt;return MQLInfoString(MQL_PROGRAM_NAME)+&quot; has been recompiled&quot;;&lt;br/&gt;case REASON_CHARTCHANGE:&lt;br/&gt;return &quot;Symbol or chart period has been changed&quot;;&lt;br/&gt;case REASON_CHARTCLOSE:&lt;br/&gt;return &quot;Chart was closed&quot;;&lt;br/&gt;case REASON_PARAMETERS:&lt;br/&gt;return MQLInfoString(MQL_PROGRAM_NAME)+&quot; input parameters have been changed by a user&quot;;&lt;br/&gt;case REASON_ACCOUNT:&lt;br/&gt;return &quot;Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings&quot;;&lt;br/&gt;case REASON_TEMPLATE:&lt;br/&gt;return &quot;A new template has been applied&quot;;&lt;br/&gt;case REASON_INITFAILED:&lt;br/&gt;return MQLInfoString(MQL_PROGRAM_NAME)+&quot; OnInit() handler has returned a nonzero value&quot;;&lt;br/&gt;case REASON_CLOSE:&lt;br/&gt;return &quot;Terminal has been closed&quot;;&lt;br/&gt;default:&lt;br/&gt;return &quot;Another reason&quot;;&lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;As you can see in the function body, there are many reasons for the DeInit function to be called and one of them is the REASON_CLOSE which is closing the terminal. With this function, I am notified immediately once the terminal shut down from any reason. Normally, the other reasons are within your control, such as program compiling or closing the chart, but I included them as well for the sake of completion.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;&lt;strong&gt;Spread Check&lt;/strong&gt;&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;I always use this check before opening an order, making sure that the BId-Ask spread is not too big so I don&#39;t finance the broker. For that, I am using a fixed value saved as a constant at the global scope of the robot:&lt;br/&gt;&lt;br/&gt;const int SPREAD=25;&lt;br/&gt;&lt;br/&gt;Then, whenever I want to open an order, I do the following check:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if(MarketInfo(TheSymbol,MODE_SPREAD)&amp;lt;=SPREAD)&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Basically, if the symbol spread is below the value I set up, then I will perform the action. In my case is opening an order, but you may do whatever you want, depending on the spread. If the spread is big, it will take longer until you will start profiting from this trade.&lt;br/&gt;&lt;br/&gt;For example, let&#39;s assume you opened a buy order with a spread of 30 pips. The bid has to move 30 pips and only then you will start seeing some profits. If the volatility for this pair is low, 30 pips will be a long time to wait or it might reach it but turn around after it. As I am mainly trading EURUSD, the spread is not a concern, but there are always events where the broker increases the spread due to some news event or liquidity and I want to be protected for it.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;&lt;strong&gt;Volatility Check&lt;/strong&gt;&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Volatility can impact your trading significantly. If a currency has a high volatility, it basically means that this currency is vibrating strongly around its price, which means that there are higher chances for your take profit as well as your stop-loss to get hit. As a trader, you have a view on the market, and the last thing you want is to lose it because of the volatility noise (unless you are trading volatility, then you may use this pattern to enter the market when the volatility is high).&lt;br/&gt;&lt;br/&gt;To solve this problem, I am only entering the market when the volatility is low in the last hour compare to the last 24 hours. I do it by checking the standard deviation of the price, which is a really good indicator of the volatility:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;double STD=iStdDev(Symbol(),PERIOD_H1,24,0,MODE_SMA,PRICE_CLOSE,0);&lt;br/&gt;for(int i=1;i&amp;lt;=24;i++)&lt;br/&gt;if(STD==0 || STD&amp;gt;iStdDev(Symbol(),PERIOD_H1,24,0,MODE_SMA,PRICE_CLOSE,i))&lt;br/&gt;return;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;In the first line, I store the current volatility in a variable called STD. Then, I check if in compare to the last 24 hours, the volatility is lower than the current one. If the answer is yes, then I return and do nothing, But, if the volatility is lower than the previous 24 hours. Then, I may continue and trade during this time period.&lt;br/&gt;&lt;br/&gt;With a small modification, you may check if the volatility is the highest in the last 24 hours. If you are trading the news, or want to enter only the volatility is high, just use the following code:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;double STD=iStdDev(Symbol(),PERIOD_H1,24,0,MODE_SMA,PRICE_CLOSE,0);&lt;br/&gt;for(int i=1;i&amp;lt;=24;i++)&lt;br/&gt;if(STD==0 || STD&amp;lt;iStdDev(Symbol(),PERIOD_H1,24,0,MODE_SMA,PRICE_CLOSE,i))&lt;br/&gt;return;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;With that, if in the last 24 hours the product was more volatile than now, the function will return and do nothing.&lt;br/&gt;&lt;br/&gt;Worth mentioning. I chose 24 hours as I believe it&#39;s enough time to look back and see how the product behave, but you may use different periods and checks.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;&lt;strong&gt;Chart Period Check&lt;/strong&gt;&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;In case your expert adviser must run on a specific chart period (as mine only runs on the 1M). Use the following code and place it at the beginning of the OnInit() function to verify that:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if(ChartPeriod()!=PERIOD_M1)&lt;br/&gt;   ChartSetSymbolPeriod(ChartID(),TheSymbol,PERIOD_M1);&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;It will check whether the chart period is the one you expect to use. If not, it will change the chart period immediately. In this example, I checked if it&#39;s the 1M chart, otherwise, I restart the chart into this period.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;In this post, I introduced 5 code snippets which you can add to your existing MQL4 programs to improve its stability and resilience. I use these patterns in most of the expert advisers I run and have them included in an external library available for purchase &lt;a href=&quot;https://www.ilantree.com/downloads/common/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;. I hope you will find it useful for your trading.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/541385027494042628/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/06/5-checks-to-enhance-your-mql4-code_26.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/541385027494042628'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/541385027494042628'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/06/5-checks-to-enhance-your-mql4-code_26.html' title='5 Checks to Enhance your MQL4 Code'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-7129514463745413890</id><published>2018-05-26T16:49:00.001+02:00</published><updated>2019-01-18T21:41:04.774+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>Martingale MQL Implementation for MetaTrader 4</title><content type='html'>&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Martingale per definition is a gambling system of continually doubling the stakes in the hope of an eventual win that must yield a net profit. It is based on the mathematical statement that:&lt;br/&gt;&lt;br/&gt;Sum 2^[0... (k-1)]&amp;lt;2&lt;span style=&quot;display: inline !important; float: none; background-color: transparent; color: #333333; cursor: text; font-family: -apple-system,BlinkMacSystemFont,&#39;Segoe UI&#39;,Roboto,Oxygen-Sans,Ubuntu,Cantarell,&#39;Helvetica Neue&#39;,sans-serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;&quot;&gt;^&lt;/span&gt;k, meaning the previous sum is always small than the next 2 exponent.&lt;br/&gt;&lt;br/&gt;Originally, the method was used in casinos to overcome loses by taking a double position each time. In trading, the method was adopted by setting a target imaginary stop loss, once crossed, a double size position with the same direction would open. If the position will go back enough, the whole structure would close, otherwise, another double position will open after the target point.&lt;br/&gt;&lt;br/&gt;What I would like to present in this post is a raw implementation of the martingale strategy in less than 50 lines of code. &lt;strong&gt;It is only for educational purposes,&lt;/strong&gt; so use it on your own risk. Personally, I am using a modified version of the martingale which has a better risk management feature. Nevertheless, it can give you a good starting point to implement your own version.&lt;br/&gt;&lt;br/&gt;From performance point of view, you can see in the following picture a typical graph of the martingale strategy:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;size-full wp-image-715&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/05/Martingale.gif&quot; alt=&quot;Martingale&quot; width=&quot;1198&quot; height=&quot;330&quot; /&gt;&lt;br/&gt;&lt;br/&gt;Which is a smooth graph going up with little hills from time to time. These &quot;hills&quot; are the martingale strategy opening and doubling the positions until the overall account P&amp;amp;L is positive. The higher the hill, the bigger the position which was used to close the martingale.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Implementation&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;The full code is available &lt;a href=&quot;http://ilantree.com/files/Experts/Martingale.mq4&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;Let&#39;s look at the main parts of the code:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;extern double MartingalePips=100;//Pips gap between Martingale levels&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;That&#39;s the only input the Martingale expert adviser has. This is the gap, or so called the imaginary stop loss level where we will double the position in attempt to close the martingale. Whenever the position goes against it&#39;s take profit direction for 100 pips as the default value, a new order will open up.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;int OnInit()&lt;br/&gt;{&lt;br/&gt;MartingalePips*=Point;&lt;br/&gt;MathSrand(GetTickCount());&lt;br/&gt;return INIT_SUCCEEDED;&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;The initialization function is straight forward, I convert the input points to pips and set the seed for the random numbers we will use later on using the recommend value of GetTickCount() as per &lt;a href=&quot;https://docs.mql4.com/math/mathsrand&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://docs.mql4.com/math/mathsrand&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;The main body is what makes the martingale magic works:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;void OnTick()&lt;br/&gt;{&lt;br/&gt;if(OrdersTotal()==0)&lt;br/&gt;{&lt;br/&gt;if(MathRand()%2==0 &amp;amp;&amp;amp; OrderSend(Symbol(),OP_BUY,MarketInfo(Symbol(),MODE_MINLOT),Ask,3,0,NormalizeDouble(Bid+MartingalePips,Digits))==-1)&lt;br/&gt;{&lt;br/&gt;SendNotification(&quot;Something went wrong when opening an order, existing&quot;);&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;else if(OrdersTotal()==0 &amp;amp;&amp;amp; OrderSend(Symbol(),OP_SELL,MarketInfo(Symbol(),MODE_MINLOT),Bid,3,0,NormalizeDouble(Ask-MartingalePips,Digits))==-1)&lt;br/&gt;{&lt;br/&gt;SendNotification(&quot;Something went wrong when opening an order, existing&quot;);&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;If there are no orders open, I use a random number and decide based if it&#39;s even or not to go long or short. I do this as I have no idea in which direction the market will go and I am using the martingale input pips as the take profit level. For example, if the random number is 11232 I will open a long position with a take profit target of Bid+MartingalePips.&lt;br/&gt;Of course, you may improve this logic and decide smarter using indicators or some statistical values to take a long or short position, I kept it simple for the sake of education.&lt;br/&gt;&lt;br/&gt;Next is where the real martingale kicks in:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;else&lt;br/&gt;{&lt;br/&gt;if(OrdersTotal()&amp;gt;1 &amp;amp;&amp;amp; AccountProfit()&amp;gt;0)&lt;br/&gt;{&lt;br/&gt;for(int i=OrdersTotal()-1; i&amp;gt;=0; i--)&lt;br/&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; OrderClose(OrderTicket(),OrderLots(),OrderType()==OP_BUY?Bid:Ask,3)==false)&lt;br/&gt;{&lt;br/&gt;SendNotification(&quot;Something went wrong when closing an order, existing&quot;);&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;else if(OrderSelect(OrdersTotal()-1,SELECT_BY_POS) &amp;amp;&amp;amp; MathAbs(OrderOpenPrice()-(OrderType()==OP_BUY?Ask:Bid))&amp;gt;MartingalePips&lt;br/&gt;&amp;amp;&amp;amp; OrderSend(Symbol(),OrderType(),2*OrderLots(),OrderType()==OP_BUY?Ask:Bid,3,0,0)==-1)&lt;br/&gt;{&lt;br/&gt;SendNotification(&quot;Something went wrong when opening an order, existing&quot;);&lt;br/&gt;ExpertRemove();&lt;br/&gt;return;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;As soon as the position was opened, there could be two options:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;The take profit level reached and the position is closed successfully.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;The price went against us MartingalePips so we must double our position to close it.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;The first case is where we make the money. The second is only to be able to close the martingale with 0 profit (again, you can improve this logic and try capturing some profit when the trend changes).&lt;br/&gt;&lt;br/&gt;The first case checks if we have more than one trade and whether the account profit is larger than 0. This case relates to the open martingale, and can only happen when the last order is big enough to cover the other open orders. For example, having 0.01, 0.02, 0.04 and then the last order of the 0.08 profit is larger than the sum of the first three orders.&lt;br/&gt;&lt;br/&gt;The second case checks if the last order which was open went  below the imaginary stop loss of MartingalePips. If yes, then it opens a new order with the same direction but double the lot size - 2*OrderLots(). Then, if the trend reverses and last position gets stronger than the others, the martingale closes and we open a new position with a take profit.&lt;br/&gt;&lt;br/&gt;Run the code yourself, just download the mq4 file, compile it and back test it. There is always a trade off between the martingale pips and the risk, the smaller the more frequent a new position will open with double size.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Summary&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;I introduced a simple working MQL Martingale code for MetaTrader 4. This strategy doubles the position every X pips aiming to close all the positions as soon as the trend changes. It carries significant risk and I would not recommend using it with real money, rather as an educational or a starting point for improved strategy.&lt;br/&gt;&lt;br/&gt;As always, feel free to leave comments or join our discussion in &lt;a href=&quot;https://www.facebook.com/groups/fxtrading2.0/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Facebook.&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/7129514463745413890/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/05/martingale-mql-implementation-for_26.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7129514463745413890'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7129514463745413890'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/05/martingale-mql-implementation-for_26.html' title='Martingale MQL Implementation for MetaTrader 4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-1642543426072062568</id><published>2018-05-06T13:23:00.001+02:00</published><updated>2019-01-18T21:41:04.666+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>The Ten Commandments for Successful Trading - Part 2</title><content type='html'>This is the second part of the &quot;&lt;a href=&quot;https://www.ilantree.com/the-ten-commandments-for-successful-trading/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;The Ten Commandments for Successful Trading&lt;/a&gt;&quot; post.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;4th Commandment - Choose the right Broker&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;size-full wp-image-659 aligncenter&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/05/3328776459_7b0b87d942_o.jpg&quot; alt=&quot;&quot; width=&quot;500&quot; height=&quot;444&quot; /&gt;&lt;br/&gt;&lt;br/&gt;I can be the best trader in the world, with the best algorithms, risk management paradigms, trading methods etc. But if I won&#39;t have the right broker with me, I would be a complete loser! It took me ages, a lot of reading and disappointments until I found the right one for me, in this case it was &lt;a href=&quot;https://www.darwinex.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Darwinex&lt;/a&gt;:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;&lt;strong&gt;They have the tightest spread on EURUSD I could get&lt;/strong&gt;, even over the weekend when the market is, the spread is 0.7 pips and less compare to other brokers who could reach 2.5+ easily. During trading hours EURUSD spread becomes so tiny that I don&#39;t even consider it in my algorithm. Since I only trade EURUSD like the 1st Commandment says, I don&#39;t care about the other currencies at all.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;strong&gt;Darwinex has a Direct Market Access&lt;/strong&gt;, meaning they send all of the client orders direct to market with institutional quality spreads and execution speeds of &amp;lt;5ms. They don&#39;t mess with your orders, they don&#39;t open a trade again you or net it with others, they just execute it without messing around!&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;strong&gt;Their team is super nice and supportive&lt;/strong&gt;, always available via their online chat or phone. I never had an issue getting a response to any of my queries during and after working hours. Their CEO has a startup mentality and bring a lot of innovation to the platform.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;They have the best method to let investors invest in my trading algorithm without giving up my proprietary knowledge. &lt;strong style=&quot;font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &#39;Helvetica Neue&#39;, sans-serif;&quot;&gt;So on top of the equity I invested in my algorithm, investors are able to trade my algorithm as if it is a registered product - &lt;a href=&quot;https://www.darwinex.com/darwin/GFA.4.21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.darwinex.com/darwin/GFA.4.21&lt;/a&gt;&lt;/strong&gt;&lt;span style=&quot;font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &#39;Helvetica Neue&#39;, sans-serif;&quot;&gt;. I don&#39;t need to deal with regulation or money management, I leave it up to Darwinex and focus on what I know, to trade.&lt;/span&gt;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;On those investors, &lt;strong&gt;I earn performance fees equal to 20% every three months&lt;/strong&gt;, so the more money I make for them, means more money is made for me. There are traders in Darwinex with millions in investment, they basically living off their trading skills. No other broker I know opens up the door for investors like Darwinex does.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;strong&gt;They don&#39;t give bonuses for signing up or gifts for nothing&lt;/strong&gt;. I stay away from all the brokers out there promising you X amount of $$ if you sign up with them. This is so wrong, there is no free money, they only give it away as they know how to get it back from you. For me, a broker who gives money, is a warning sign.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;strong&gt;Darwinex do have a certain method you can earn based on performance&lt;/strong&gt;. So, the better trader you are, the better changes you win a monthly competition called &lt;a style=&quot;font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &#39;Helvetica Neue&#39;, sans-serif;&quot; href=&quot;https://www.darwinex.com/darwinia&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Darwinia&lt;/a&gt;&lt;span style=&quot;font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &#39;Helvetica Neue&#39;, sans-serif;&quot;&gt; which entitles you to earn X thousands $ to manage.&lt;/span&gt;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Darwinex analyses my algorithm from different statistical and performance angles which helps me to refine and optimise it. Since I started trading with them, I improved my risk management significantly and started to perform much better thanks to their intuitive repots and information, all for free. &lt;strong style=&quot;font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &#39;Helvetica Neue&#39;, sans-serif;&quot;&gt;So they help you to become a better trader instead of working against you like other brokers&lt;/strong&gt;&lt;span style=&quot;font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, Roboto, Oxygen-Sans, Ubuntu, Cantarell, &#39;Helvetica Neue&#39;, sans-serif;&quot;&gt;.&lt;/span&gt;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;strong&gt;Deposit and withdrawal is straight forward&lt;/strong&gt;, no need to wait X days to see my money withdrawn to my account like other brokers out there.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;These are the main reasons I chose Darwinex, it helped me to become a better trader and it helped me to get visibility for other investors to buy into my product. So, just like the picture is saying, I work with a broker who helps me to generate money and not eat it away from me.&lt;br/&gt;&lt;br/&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;The 5th Commandment - Be Real&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;aligncenter wp-image-660 size-full&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/05/2230902429_b15d8a901e_o.jpg&quot; alt=&quot;Returns&quot; width=&quot;800&quot; height=&quot;533&quot; /&gt;&lt;br/&gt;&lt;br/&gt;Get real about your return expectations. Don&#39;t aim for imaginary numbers like 100%, 70% or even 10% return per month, this will not happen consistently and you will have to take insane risk which will bite you in the end, just a matter of time.&lt;br/&gt;&lt;br/&gt;As a comparison, the hedge funds industry finished the year with an average return of 8.5% - &lt;a href=&quot;https://www.ft.com/content/cd928772-f08a-11e7-b220-857e26d1aca4&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.ft.com/content/cd928772-f08a-11e7-b220-857e26d1aca4&lt;/a&gt;! So, I am VERY happy if I manage to make a return of 0.5-2% a month. Even it seems very little compare to the many offers out there, it&#39;s realistic, and if you add compounding, a monthly return of 2% ends up with 26% annually.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;The 6th Commandment - Automate your Trading&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;aligncenter size-full wp-image-679&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/05/6337254012_36f8a2d564_o.jpg&quot; alt=&quot;Expert Adviser&quot; width=&quot;1250&quot; height=&quot;1680&quot; /&gt;&lt;br/&gt;&lt;br/&gt;I was so relived when I finished automated my trading style and let it run. To trade manually took me so much time and effort. Sitting in front of the screen all day, tracking the news, seeing how the currency moves, the volatility, the risk. So, I decided I take it serious, learn to program MQL, the MetaTrader language and did it.&lt;br/&gt;&lt;br/&gt;As my trading style is based on technical details, mathematically simple, it took couple of months to work it out and build a reliable algorithm which runs on real money and open for investor to buy in - &lt;a href=&quot;https://www.darwinex.com/darwin/GFA.4.21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.darwinex.com/darwin/GFA.4.21&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;If you want a really good starting point to start programming your own algorithm, I suggest you attend one of my webinars where I explain step by step how to develop your own expert adviser from scratch, it&#39;s only a matter of time until you are able to write your own code, test it and run it. Otherwise, there are numerous of books on the topic like this one - &lt;a href=&quot;https://www.amazon.com/Expert-Advisor-Programming-Automated-MetaTrader/dp/0982645902&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://www.amazon.com/Expert-Advisor-Programming-Automated-MetaTrader/dp/0982645902&lt;/a&gt;. The moment your algorithm will run, you will relieved, you will not have to worry yourself anymore with looking at the charts non-stop, checking the risk, open and close timing and so on. Just let the PC do it for you. In this time, you will be able to do other things like getting more education, learn new things and improve your strategy.&lt;br/&gt;&lt;br/&gt;I am not saying it is straightforward thing to build up a successful expert adviser, otherwise, everyone will do so, but it is far more better than sitting and waiting for the right movement to come, plus, there are so many fake signal providers and expert advisers for sale, I wouldn&#39;t count on them to do what I do best.&lt;br/&gt;&lt;br/&gt;&amp;nbsp;&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;tbc&lt;/strong&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/1642543426072062568/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/05/the-ten-commandments-for-successful_6.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1642543426072062568'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1642543426072062568'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/05/the-ten-commandments-for-successful_6.html' title='The Ten Commandments for Successful Trading - Part 2'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-7337110716830064835</id><published>2018-04-29T21:57:00.001+02:00</published><updated>2019-01-18T21:41:04.556+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>The Ten Commandments for Successful Trading</title><content type='html'>&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;By now, you have probably numerous articles written by professionals telling you how to succeed in trading. These posts were basically telling that you do X or follow plan Y, your trading skills will improve significantly and you will be one step away from retirement and living the dream.&lt;br/&gt;&lt;br/&gt;And then reality kicked in, you actually tried, follow the plan step by step but it didn&#39;t work. So you read another article, another tip and nothing changes. Why?! I asked myself the same question, and to be honest the answer is quite simple, there is no magic trick, there is no single trick that works generically for everyone and there&#39;s no plan for beating the market!&lt;br/&gt;&lt;br/&gt;So, instead of telling you what you should do, I will tell you what I do and leave the choice with you if you want to follow or not. I will not claim that I have a method to make you a millionaire overnight and all this crap... I will simply write 10 points which I do my best to follow, 10 painful points which I had to learn by mistake and money loss...&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;1st Commandment - Trade one product&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Just like the first commandment &quot;I am the Lord thy God&quot; I learned the hard way that &lt;strong&gt;less is more&lt;/strong&gt;. I used to trade up to 10 products simultaneously, trying to follow up all the news, all the events, around the clock, non stop. I missed opportunities, closed positions too late, my VAR was insane and overall, I lost more than I gained.&lt;br/&gt;&lt;br/&gt;It might sound weird and counterintuitive, but since I started trading only one product, namely - EURUSD, my returns improved significantly and above all, I wasn&#39;t worried anymore from burn out. Unless you have some extraordinary artificial intelligence trading system who can go through thousands of news items and understand the impact on the market, then you may ignore what I wrote above. But honestly, my life became much more easy when I started running my algorithmic trading system on EURUSD only. Even it&#39;s 95% automated, there are some events which I decide to switch it off, like high volatility ones as non farm payroll in the US (so called NFP), or end of a period to capture the return for that time, so, having it run on a single product, gave me tight control on what&#39;s going on.&lt;br/&gt;&lt;br/&gt;Now, if you think that I miss other opportunities or make less than I used to, believe me I am not. When EURUSD is ranging, I scalp it, when it is trending, I go with the trend and when it&#39;s undergoing some high volatility event, I either ride the wave or pull out. Since I switched, I made in the first month 3.94% and 1.90% in the second.&lt;br/&gt;&lt;br/&gt;just to give an example, looking at the upcoming events for the following week using Forex Factory &lt;a href=&quot;https://www.forexfactory.com/calendar.php&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;calendar&lt;/a&gt;, it was insane and stressful to follow all the high volatility events for the week for all the products I traded, each one can either makes a lot of profit, or ends in a loss:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone size-full wp-image-624&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/Screen-Shot-2018-04-29-at-21.00.47-1.png&quot; alt=&quot;Full calendar&quot; width=&quot;1035&quot; height=&quot;632&quot; /&gt;&lt;br/&gt;&lt;br/&gt;Now, filtering for EURUSD, it&#39;s much more easier to follow what&#39;s coming and act accordingly, from 22 high impact events, it went down to only 9 I need to track:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone wp-image-625 size-full&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/Screen-Shot-2018-04-29-at-21.01.11.png&quot; alt=&quot;Filtered events&quot; width=&quot;1035&quot; height=&quot;282&quot; /&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;2nd Commandment - Become product expert&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Going along with the 1st commandment and with &quot;Thou shalt have no other gods before me&quot;, it is critical that now that you chose a single product, become an expert on it, and I am talking to know the internal organs of it if needed:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;What is the current rate?&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;What was the rate a month ago?&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;What is the expectations of the price to go this year?&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Where can you find reliable information on the product? Is it a blog? New agency?...&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Are there any analysts covering this product? Is it possible to follow them?&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;What is a typical volatility of the product? What is a typical a technical indicator of this product?&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;When is the best time to trade it? Morning? Afternoon? Monday?&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Is the product pegged to another product? Are the governments involved tightly overlook the price? How is supply and demand works for this product?&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Which impacts certain news events have on the product, what happens to the price if the outcome is above/below expectations etc.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;...&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;These are some of the questions you need to know even you get woken up in the middle of the night, especially the current price! And that&#39;s what I learned on EURUSD, compare to trading and learning ten products in parallel and knowing their behaviour on the surface, I dig deep into EURUSD and understood how it behaves and what impact it.&lt;br/&gt;&lt;br/&gt;Only when I truly understand the product I am dealing with, I started to trade it successfully. I minimised the surprise factor to a minimum and then I automated what I learned. You could argue that I over optimised my system for this single product, but that&#39;s actually what I wanted, there is no single system fits all in my eyes anyway...&lt;br/&gt;&lt;br/&gt;On the other hand, if at some point in the future the product I chose will fail and proves itself unworthy anymore, I will move on and choose another one, just to say, it is not till death do us part, only until the product cheats on us again and again so we have no chance but move on with our life.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;3rd Commandment - Manage risk&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;I already dedicated a full &lt;a href=&quot;https://www.ilantree.com/leverage-explained/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;post&lt;/a&gt; about managing risk just to stress how much it is important. The majority of accounts blowing up is due to poor risk management, meaning opening far too many orders with massive lot sizes which can&#39;t be managed. And once the margin is below the critical level, each order gets closed one after the other leaving the investor with nothing. It happened to me so many times when I started trading years ago, super frustrating!&lt;br/&gt;&lt;br/&gt;And still, it is always amazes me to see people posting pictures of their accounts claiming they made thousands in couple of days, then people are super excited and actually follow these clowns. Every time I took a chance and follow these over-leveraged account they blew out, it is not the way it should work.&lt;br/&gt;&lt;br/&gt;Just as an example, I recently followed a guy who claimed he was able to make 3,000$ every week using an initial investment of 1,000$ which is of course not possible, guess what, here was his account after couple of weeks:&lt;br/&gt;&lt;br/&gt;&lt;a href=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/31749496_149742049204744_7584794665711304704_n.jpg&quot;&gt;&lt;img class=&quot;aligncenter wp-image-629 size-medium&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/31749496_149742049204744_7584794665711304704_n-168x300.jpg&quot; alt=&quot;&quot; width=&quot;168&quot; height=&quot;300&quot; /&gt;&lt;/a&gt;&lt;br/&gt;&lt;br/&gt;So things started to get out of control, then what he did was even more insane was to open more positions agains the trend, obviously EURUSD was going down but this guy went with more positions against it, only to get:&lt;br/&gt;&lt;br/&gt;&lt;a href=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/31688012_149742025871413_2780869166700167168_n.jpg&quot;&gt;&lt;img class=&quot;aligncenter wp-image-630 size-medium&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/31688012_149742025871413_2780869166700167168_n-168x300.jpg&quot; alt=&quot;&quot; width=&quot;168&quot; height=&quot;300&quot; /&gt;&lt;/a&gt;&lt;br/&gt;&lt;br/&gt;Obviously, it didn&#39;t less for long and his account got blown up...&lt;br/&gt;&lt;br/&gt;As a rule of thumb, perform this calculation BEFORE opening a new order:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Sum up all the lots, longs as positive, shorts as negative&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Get the absolute value of the previous step&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Multiply with 100,000&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Divide with your account balance&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;For example, the guy had 8 long positions of 0.25 which is 2 lots in total minus two short positions of 0.25 which leaves us with 1.5 lots. Multiply with 100,000 gives 150,000 and dividing with his equity is 150,000 / 2,087 = 71. This is INSANE leverage, so called &lt;strong&gt;effective leverage of 1:71. &lt;/strong&gt;When I speak with investors, they want values in the range of 1:5-6 maximum.&lt;br/&gt;&lt;br/&gt;So bottom line, I always make sure my risk is under control and I never over leverage and keeping my trading under control. For example, one of my algorithms has effective leverage of 0 as I am net zero on both directions:&lt;br/&gt;&lt;br/&gt;&lt;a href=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/31674165_10155504114315036_6919513349776474112_n.jpg&quot;&gt;&lt;img class=&quot;aligncenter wp-image-631 size-medium&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/04/31674165_10155504114315036_6919513349776474112_n-168x300.jpg&quot; alt=&quot;&quot; width=&quot;168&quot; height=&quot;300&quot; /&gt;&lt;/a&gt;&lt;br/&gt;&lt;br/&gt;The numbers might look small, but as I am trading over &lt;a href=&quot;https://www.darwinex.com/darwin/GFA.4.21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Darwinex&lt;/a&gt;, the investor copies the strategy and enjoys a nice return 1-4% with minimum risk.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/7337110716830064835/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/04/the-ten-commandments-for-successful_29.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7337110716830064835'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7337110716830064835'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/04/the-ten-commandments-for-successful_29.html' title='The Ten Commandments for Successful Trading'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-1701197668485957297</id><published>2018-03-31T18:21:00.001+02:00</published><updated>2019-01-18T21:41:04.448+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>How to Remote Control an Expert Adviser in MQL4 using Pending Orders</title><content type='html'>&lt;h1&gt;Introduction&lt;/h1&gt;&lt;br/&gt;&lt;br/&gt;Our goal as algotraders, is to create an autonomous trading algorithm with as little as possible manual intervention. An algorithm which can run by it&#39;s own on a certain product while we are doing something else, letting the money work classic paradigm.&lt;br/&gt;&lt;br/&gt;Alas, sometimes life is not the way we want to be and the algorithm we design, programmed and tested behaves completely different under certain market conditions. But you&#39;re not always next to your PC, you&#39;re not always able to perform or change something as you have your own life. Assuming you&#39;re sitting in your favourite bar with friends and suddenly some news event happens which impacts significantly the volatility, what can you do then?&lt;br/&gt;&lt;br/&gt;I had the same scenarios over and over again, where I couldn&#39;t control my expert adviser without logging into my PC or to the remote PC to make the actual change, which was really frustrating and time consuming. I was thinking again and again, why isn&#39;t there a way to signal the EA to do something and move on, how can I &quot;speak&quot; with the EA even I am 100km away...&lt;br/&gt;&lt;br/&gt;&lt;h1&gt;Solution&lt;/h1&gt;&lt;br/&gt;&lt;br/&gt;I realised that the solution is much simpler than I thought. Basically, my idea was having a listener on the number of the orders opened, and each time a new order was added, I would check whether it&#39;s an ordinary order or an instruction order. Where an instruction order is a normal pending order with a dedicated range of prices, in my case 2000-... (I am trading mainly FX products who are not in this range of pricing).&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Setup&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Before looking at the code itself, you must make sure that you enabled notifications in Metatrader. Doing so is quite straightforward, select from the menu tools -&amp;gt; options and navigate to the notifications tab:&lt;br/&gt;&lt;br/&gt;&lt;img src=&quot;https://www.ilantree.com/wp-content/uploads/2018/03/Screen-Shot-2018-03-31-at-17.30.11.png&quot; class=&quot;alignnone size-full wp-image-457&quot; alt=&quot;Notifications&quot; width=&quot;578&quot; height=&quot;399&quot;&gt;&lt;br/&gt;&lt;br/&gt;In there, tick the &quot;Enable Push Notifications&quot; and enter your MetaQuotes ID, a value which can be found in the mobile application you&#39;re using. In iPhone the ID is found at the bottom of the &quot;Chat and Messages Page&quot;:&lt;br/&gt;&lt;br/&gt;&lt;img src=&quot;https://www.ilantree.com/wp-content/uploads/2018/03/Code-1-169x300.png&quot; class=&quot;alignnone size-medium wp-image-459&quot; width=&quot;169&quot; height=&quot;300&quot; alt=&quot;Meta Quotes ID&quot;&gt;&lt;br/&gt;&lt;br/&gt;Once you entered the ID details in Metatrader, click test and expect to see a message in your mobile device, if not, double check your input.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Orders Number Listener&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;As the title suggests, this piece of code listens to the Orders number and acts upon a change:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;if(OrdersNumber!=OrdersTotal())&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;  OrdersNumber=OrdersTotal();&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;  ProcessRemoteInstructions();&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;I place it in the OnTick function and check whether the Orders Number changed from the last tick, normally I check every minute as I don&#39;t expect to have so many instructions coming in.&lt;br/&gt;&lt;br/&gt;OrdersNumber is a global integer variable which I initialise as part of the OnInit function to the current OrdersNumber value:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;OrdersNumber=OrdersTotal();&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;So the number did change, I store the new value and process the remote instructions if any.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Processing Remote Instructions&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Now that we are listening on the orders number, it&#39;s time to do something if the number changed. In the following function, I run over the orders and if it is a pending buy sell order with a price in the range of 2000... I execute according to predefined action:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;void ProcessRemoteInstructions()&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; {&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; for(int i=OrdersTotal()-1;i&amp;gt;=0;i--)&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; StringCompare(TheSymbol,OrderSymbol())==0 &amp;amp;&amp;amp; (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLLIMIT))&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; {&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; switch((int)OrderOpenPrice())&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; {&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; case 2000:&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; {&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; OrderDelete(OrderTicket());&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;SendNotification(StringConcatenate(&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; &quot;1 Remove expert\n&quot;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; &quot;2 ...&quot;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; ));&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; break;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; }&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; case 2001:&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; {&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;OrderDelete(OrderTicket());&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;SendNotification(&quot;Incoming request to remove the expert, exiting...&quot;);&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; ExpertRemove();&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; return;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; }&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;pre&gt; case 2002:...&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;In this small example, I loop through the open orders looking for pending orders. If the pending order is in the price range of 2000+ I act upon it and delete it. In this case, I have two scenarios:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;2000: In this case just send a notification to the mobile device with all the avaialble remote instructions.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;2001: Terminate the expert adviser.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Usage&lt;/h2&gt;&lt;br/&gt;&lt;br/&gt;Coming back to our scenario. Assuming I am sitting in a bar chilling out after a long day of trading and suddenly I see something I don&#39;t like in the market. All I need to do now is open a pending order with the price of 2001 and the expert adviser will pick it up and terminate itself so I can go back and relax (instead of  login into the remote host and do the same, which is not straightforward).&lt;br/&gt;&lt;br/&gt;Of course, I gave here a simple example of a remote instruction. In my expert adviser, I tailored the instructions to my trading style, there in an instruction to open up a specific order, or open a hedge, calculate volatility and so on. But the pattern is still the same:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Open a pending order with a specific price&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;The expert adviser picks up the instruction and execute remotly&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;The expert adviser sends a notification open receipt / completion.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;Hope it helps, for any questions don&#39;t hesitate to comment here or contact me per &lt;a href=&quot;https://t.me/ilantree&quot;&gt;telegram&lt;/a&gt; / &lt;a href=&quot;admin@ilantree.com&quot;&gt;email&lt;/a&gt;.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/1701197668485957297/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/03/how-to-remote-control-expert-adviser-in_31.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1701197668485957297'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1701197668485957297'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/03/how-to-remote-control-expert-adviser-in_31.html' title='How to Remote Control an Expert Adviser in MQL4 using Pending Orders'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-3581091206093405523</id><published>2018-01-13T16:34:00.001+01:00</published><updated>2019-01-18T21:41:04.278+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>Release Management Pattern for Expert Advisors</title><content type='html'>&lt;h3&gt;The Challenge&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;As an FX algotrader who is implementing his own Expert Advisers, I make code changes from time to time which must be reflected in the production environment as soon as possible. But running Experts on different hosts with different brokers means that I need to login to each box, update the SVN repo, compile and install the Expert again. What if this task could be automated? So every time I check in a new version, the Expert auto update and restarts itself.&lt;br/&gt;&lt;br/&gt;That´s exactly the setup I am going to explain in this post. Once understood, you will be able to implement the same method in your code and have your Experts always running the last version as soon as you check in, sort of release management setup for Metatrader.&lt;br/&gt;&lt;br/&gt;Before divining into the actual setup, make sure you familiarize yourself with MQL5Storage and how to register to get it by visiting this &lt;a href=&quot;https://www.metatrader5.com/en/metaeditor/help/mql5storage&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;link&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Metatrader Setup&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Before looking at the code changes, we need to make sure Metatrader is set up properly to update the local repository. We do that by navigating to the MQL4 folder where the SVN root is located and checking out the files again (It might sound weird to check out via the terminal even we check out inside the platform, but it is necessary as the platform does not create the .svn folder).&lt;br/&gt;&lt;br/&gt;We do this by checking out the repository by typing:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;svn co https://storage.mql5.com/svn/personal/REPO_NAME.&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Once the MQL4 folder is checked out, you may test is by typing &lt;em&gt;&lt;strong&gt;svn info&lt;/strong&gt;&lt;/em&gt; and get an informative response such as:&lt;br/&gt;&lt;br/&gt;&lt;pre style=&quot;padding-left: 30px;&quot;&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Working Copy Root Path: C:\Users\...\MQL4&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;URL: https://storage.mql5.com/svn/personal/.../MQL4&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Relative URL: ^/..../MQL4&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Repository Root: https://storage.mql5.com/svn/personal&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Repository UUID: ...&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Revision: ...&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Node Kind: directory&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Schedule: normal&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Last Changed Author: ...&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Last Changed Rev: ...&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Last Changed Date: 2018-01-18 17:36:26 +0100 (Thu, 18 Jan 2018)&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Next, in the /files folder create a file called SVNUP.bat with the following contents:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;svn cleanup ../&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;svn up ../&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;This file will be used later when updating the repository from within the Expert Advisor.&lt;br/&gt;&lt;br/&gt;Also, create a file called &lt;span style=&quot;color: #0000ff;&quot;&gt;revision.txt&lt;/span&gt; with a numerical value representing the current SVN version you work on, in my case I marked the starting value as 1.&lt;br/&gt;&lt;br/&gt;If you follow the above steps, the MQL4 folder should have the .svn folder containing the repository information:&amp;nbsp;&lt;img class=&quot;alignnone size-full wp-image-402&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/01/TopFolder.jpg&quot; alt=&quot;Top Folder&quot; width=&quot;574&quot; height=&quot;234&quot;&gt;&lt;br/&gt;&lt;br/&gt;and the Files folder should have two new files, SVNUP.bat and revision.txt:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone size-full wp-image-405&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2018/01/Files.jpg&quot; alt=&quot;Added Files&quot; width=&quot;577&quot; height=&quot;45&quot;&gt;&lt;br/&gt;&lt;br/&gt;Let´s move on to the next step...&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Shell Execute Function&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;For the release management tool to work, you must be familiar with ShellExecuteW function available by importing shell32.dll in Windows. As noted in &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx&quot;&gt;MSDN&lt;/a&gt;, this function call allows you to perform an action on a file. We will use this function in our calls for the following actions:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Update the local SVN repository using the SVNUP.bat we created in the previous step.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Compile the relevant files using a call to Metaeditor /compile&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;Starting with the first step, in my code I created an hourly timer event to check whether something changed in the repository, sort of pulling behavior. In the Timer I execute the following code snippet:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;int HINSTANCE=ShellExecuteW(NULL,NULL,&quot;SVNUP.bat&quot;,&quot;&quot;,StringConcatenate(TerminalInfoString(TERMINAL_DATA_PATH),&quot;\\MQL4\\Files&quot;),0);&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;if(HINSTANCE&amp;lt;=32)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;{&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;SendNotification(StringConcatenate(IntegerToString(AccountNumber()),&quot;: ShellExecuteW SVNUP.bat failed - &quot;,ShellExecuteErrorDescription(HINSTANCE)));&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;return false;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;}&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;This basically calls the SVNUP.bat file I created in the previous stage which check and updates the local SVN repo. If the return code is smaller than 32, it means some error occurred while calling ShellExecuteW function. If all went well, the local repo has the latest files locally, so we can go ahead and check whether something actually changed.&lt;br/&gt;&lt;br/&gt;As mentioned above, I created a text file called Revision.txt where I save a numerical value which tracks the current version. Each time I make a code change worth updating, I change this value, i.e 19 -&amp;gt; 20...&lt;br/&gt;&lt;br/&gt;Next, following a SVN update call, I have a function checking whether this version changed by reading the file and comparing the value to the current one in the memory:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;int GetRevision()&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;{&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;string RevisionFileName=&quot;Revision.txt&quot;;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;if(FileIsExist(RevisionFileName)==false)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    {&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    SendNotification(StringConcatenate(IntegerToString(AccountNumber()),&quot;: Revision file doesn&#39;t exist&quot;));&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    return -1;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    }&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;else&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    {&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    int RevisionFileHandle=FileOpen(RevisionFileName,FILE_TXT|FILE_READ);&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    if(RevisionFileHandle==INVALID_HANDLE)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        {&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        SendNotification(StringConcatenate(IntegerToString(AccountNumber()),&quot;: Operation FileOpen failed, &quot;,ErrorDescription(GetLastError())));&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        return -1;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        }&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    else&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        {&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        int Output=(int)StringToInteger(FileReadString(RevisionFileHandle));&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        FileClose(RevisionFileHandle);&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        return Output;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        }&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    }&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;}&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Now that I have the revision value, I call the following check (worth mentioning that I let the adviser sleep for a minute to make sure the updated files are available already and got synched locally after the svn up call):&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Sleep(60000);&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;int Output=GetRevision();&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;if(Output==-1)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    return false;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;else if(Revision!=Output)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;{&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    Revision=Output;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    SendNotification(StringConcatenate(IntegerToString(AccountNumber()),&quot;: Revision updated to &quot;,IntegerToString(Revision),&quot;, initializing experts&quot;));&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    if(CompileFile(FilePath)==false)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;        return false;&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;I am checking whether the revision value changed, and if it did, I call CompileFile function which compile the path to the file I work on:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;bool CompileFile(string Filename)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;{&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;int HINSTANCE=ShellExecuteW(NULL,NULL,&quot;metaeditor.exe&quot;,StringConcatenate(&quot;/compile:\&quot;&quot;,Filename,&quot;\&quot;&quot;),TerminalPath(),4);&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;if(HINSTANCE&amp;lt;=32)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    {&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    SendNotification(StringConcatenate(IntegerToString(AccountNumber()),&quot;: ShellExecuteW metaeditor.exe &quot;,Filename,&quot; failed - &quot;,ShellExecuteErrorDescription(HINSTANCE)));&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    return false;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;    }&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;return true;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;}&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;This is achieved again by using ShellExecuteW and calling Metaeditor, which with the /compile parameter is compiling the input file. After compilation, I let the adviser sleep again a minute before restarting the it:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;Sleep(60000);&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;ChartApplyTemplate(ChartID(),&quot;Template.tpl&quot;);&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;In this case, the template Controller.tpl is applying the same adviser on the current chart, thus triggering a restart with the new code I just created.&lt;br/&gt;&lt;br/&gt;For completeness, here is the function I am using to describe the error in case ShellExecuteW fails:&lt;br/&gt;&lt;br/&gt;&lt;pre&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt;string ShellExecuteErrorDescription(int error_code) export&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; {&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; string error_string;&lt;/span&gt;&lt;br/&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; switch(error_code)&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; {&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; //--- codes returned from shell execute&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 0: error_string=&quot;The operating system is out of memory or resources.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 2: error_string=&quot;The specified file was not found&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 3: error_string=&quot;The specified path was not found.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 5: error_string=&quot;Windows 95 only: The operating system denied access to the specified file&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 8: error_string=&quot;Windows 95 only: There was not enough memory to complete the operation.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 10: error_string=&quot;Wrong Windows version&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 11: error_string=&quot;The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 12: error_string=&quot;Application was designed for a different operating system&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 13: error_string=&quot;Application was designed for MS-DOS 4.0&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 15: error_string=&quot;Attempt to load a real-mode program&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 16: error_string=&quot;Attempt to load a second instance of an application with non-readonly data segments&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 19: error_string=&quot;Attempt to load a compressed application file&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 20: error_string=&quot;Dynamic-link library (DLL) file failure&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 26: error_string=&quot;A sharing violation occurred.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 27: error_string=&quot;The filename association is incomplete or invalid.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 28: error_string=&quot;The DDE transaction could not be completed because the request timed out.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 29: error_string=&quot;The DDE transaction failed.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 30: error_string=&quot;The DDE transaction could not be completed because other DDE transactions were being processed.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 31: error_string=&quot;There is no application associated with the given filename extension.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; case 32: error_string=&quot;Windows 95 only: The specified dynamic-link library was not found.&quot;; break;&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; default: error_string=StringConcatenate(&quot;unknown error - &quot;,IntegerToString(&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; return(error_string);&lt;/span&gt;&lt;br/&gt;&lt;span style=&quot;color: #0000ff;&quot;&gt; }&lt;/span&gt;&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Summary&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;In this post, I introduced the method I am using to monitor and update my Expert advisers remotely across the different brokers I work with. Using this method, you will be able to develop, compile and check in your code locally followed by an auto updated of the remote Experts.&lt;br/&gt;&lt;br/&gt;I used an hourly check where I am calling a function to confirm whether the code actually changed using the revision file, but you may want to use shorter timer if you want more frequent checks.&lt;br/&gt;&lt;br/&gt;This method saved me time login into different hosts and made it quite simple and convenient for me to check in once and have all of the different experts updated at the same time.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/3581091206093405523/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2018/01/release-management-pattern-for-expert_13.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3581091206093405523'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3581091206093405523'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2018/01/release-management-pattern-for-expert_13.html' title='Release Management Pattern for Expert Advisors'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-8855665241790943077</id><published>2017-09-23T13:13:00.001+02:00</published><updated>2019-01-18T21:41:04.169+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="Donchian"/><category scheme="http://www.blogger.com/atom/ns#" term="Indicators"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><title type='text'>Using the Donchian Indicator to enhance your Trading</title><content type='html'>The Donchian channel is available for purchase &lt;a href=&quot;https://www.ilantree.com/downloads/donchian-levels/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;Richard Davoud Donchian was an Armenian-American commodities and futures trader, and pioneer in the field of managed futures who came up with a simple intuitive indicator called the Donchian channel. It is basically based on the lowest low value or the highest high value in a given period of time:&lt;br/&gt;&lt;img class=&quot;alignnone size-full wp-image-343&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/09/USDCAD.png&quot; alt=&quot;USDCAD with Donchian&quot; width=&quot;1227&quot; height=&quot;702&quot; /&gt;&lt;br/&gt;&lt;br/&gt;&lt;h5&gt;Calculation&lt;/h5&gt;&lt;br/&gt;&lt;br/&gt;As mentioned, Donchian is based on marking the lowest low line or the highest high line, so visually you see the trend of the product. Whenever the product reached a value which is higher than the last 24 values or lower than the previous ones, a new markup will start until it reverses.&lt;br/&gt;Calculating it with MQL is straightforward, to find out the highest value of the product in a given period, we use the following snippet:&lt;br/&gt;&lt;code&gt;double HighestHigh=iClose(Symbol(),Period(),iHighest(Symbol(),Period(),MODE_CLOSE,TradePeriod,0));&lt;br/&gt;&lt;/code&gt;&lt;br/&gt;Here, reading from right to left, we first find the shift of the highest value using a call to iHighest, and then, using the return value which is the shift itself, calling iClose to retrieve it. It is possible to run this code with MODE_HIGH, MODE_OPEN etc to get the highest value, but normally I call it with MODE_CLOSE as this is the final value after the price vibrated in that period.&lt;br/&gt;Calculating the lowest low is more or less the same:&lt;br/&gt;&lt;code&gt;double LowestLow=iClose(Symbol(),Period(),iLowest(Symbol(),Period(),MODE_CLOSE,TradePeriod,0));&lt;/code&gt;&lt;br/&gt;Here, we just call the iLowest function instead to receive the value.&lt;br/&gt;&lt;br/&gt;Now that we have these values, we can mark them on the indicator and paint the chart accordingly. For example, I use the following code to make the painting:&lt;br/&gt;&lt;code&gt;  if(i&amp;gt;0)&lt;br/&gt;{&lt;br/&gt;if(CLOSE&amp;gt;HighestHigh &amp;amp;&amp;amp; TrendDirection[i+1]!=OP_BUY)&lt;br/&gt;{&lt;br/&gt;TrendDirection[i]=OP_BUY;&lt;br/&gt;SendNotification(StringConcatenate(Symbol(),&quot; go long&quot;));&lt;br/&gt;}&lt;br/&gt;else if(CLOSE&lt;br/&gt;{&lt;br/&gt;TrendDirection[i]=OP_SELL;&lt;br/&gt;SendNotification(StringConcatenate(Symbol(),&quot; go short&quot;));&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;if(TrendDirection[i]==OP_BUY)&lt;br/&gt;ExtMapBuffer1[i]=LowestLow;&lt;br/&gt;else if(TrendDirection[i]==OP_SELL)&lt;br/&gt;ExtMapBuffer2[i]=HighestHigh;&lt;br/&gt;&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Whenever the trend changed direction, I get notified over Metatrader, but it is possible also to get an E-mail or any other means of communication. This way, whenever new highs or lows are achieved, I am notified immediately and can make trading decisions on how to proceed with my positions.&lt;br/&gt;&lt;br/&gt;&lt;h5&gt;Usage&lt;/h5&gt;&lt;br/&gt;&lt;br/&gt;I mostly run this indicator on the hourly chart of the products I trade. It is not too short time frame for randomness and noise to kick in, and not too long that the trend might be discovered towards the end. On my mobile, the notifications will look like:&lt;br/&gt;&lt;code&gt;EURGBP go long 10:30&lt;br/&gt;EURGBP go short 12:45&lt;br/&gt;...&lt;br/&gt;&lt;/code&gt;&lt;br/&gt;As it is just one of the indicators I use, I don&#39;t rush and open a position, rather check the current market conditions and news to see what the overall sentiment for this product.&lt;br/&gt;For example, I was long EURGBP the last month, strongly believing the Brexit does good to the EUR, the upcoming elections and many supporting ideas for me to follow. But actually, after looking at the Donchian around the time I opened the order, I noticed it is a free fall, which only recently is coming towards an end:&lt;br/&gt;&lt;img class=&quot;alignnone size-full wp-image-344&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/09/EURGBPH1.png&quot; alt=&quot;EURGBP Donchian&quot; width=&quot;1214&quot; height=&quot;700&quot; /&gt;&lt;br/&gt;Looking at the indicator behavior around the 8th September, shows a clear sign of an upcoming bearish trend of EURGBP, with a short reversal and then down again. So, going long was not the right choice at the time and closing the positions was the right choice.&lt;br/&gt;&lt;br/&gt;Normally, as I am a volatility trader, I don&#39;t look for trend and trade both directions of the market to capture profit. But still, as I like simplicity, the Donchian give me that trending piece of information I need to make a decision whether it is a ranging market which is my favorite or a trending market and then my decisions on taking a side are critical.&lt;br/&gt;&lt;br/&gt;&lt;h5&gt;Turtle Trading&lt;/h5&gt;&lt;br/&gt;&lt;br/&gt;Interesting point was that during the 80&#39;s, there was the famous experiment to prove that anyone can be a trader, so called the turtle traders. And as mentioned in the original rules which can be found here - &lt;a href=&quot;http://bigpicture.typepad.com/comments/files/turtlerules.pdf&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;http://bigpicture.typepad.com/comments/files/turtlerules.pdf&lt;/a&gt;. The trading entry system was based on breakouts, where breakout was defined as the price exceeding the high or low of a particular number of days. Thus a 20-day breakout would be defined as exceeding the high or low of the preceding 20 days.&lt;br/&gt;In my trading, I use it more as a flag signaling me whether I should go into a trade or not, but only after I have several positions and I want to hedge them, plus, I am using the hourly chart as mentioned above.&lt;br/&gt;&lt;br/&gt;&lt;h5&gt;Code&lt;/h5&gt;&lt;br/&gt;&lt;br/&gt;The full code is here and in the &lt;a href=&quot;https://www.ilantree.com/downloads/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;downloads&lt;/a&gt; page for you to use it, feel free to contact me for any questions:&lt;br/&gt;//+------------------------------------------------------------------+&lt;br/&gt;//| Donchian |&lt;br/&gt;//| Copyright 2017, IlanTree |&lt;br/&gt;//| http://www.ilantree.com |&lt;br/&gt;//+------------------------------------------------------------------+&lt;br/&gt;#property copyright &quot;Roy Meshulam&quot;&lt;br/&gt;#property version &quot;1.00&quot;&lt;br/&gt;#property description &quot;As a user of this trading system, you acknowledge and agree to accept complete responsibility for ANY and ALL results in your trading account. You acknowledge and agree that you are fully aware of the high risk associated with trading. You acknowledge and agree that leveraged currency trading can cause losses greater than your beginning balance. You acknowledge and agree that Roy Meshulam has made NO promises or guarantees suggesting that this trading system will result in a profit or loss.&quot;&lt;br/&gt;#property link &quot;http://www.ilantree.com&quot;&lt;br/&gt;#property strict&lt;br/&gt;&lt;br/&gt;#property indicator_chart_window&lt;br/&gt;#property indicator_buffers 2&lt;br/&gt;#property indicator_color1 DodgerBlue&lt;br/&gt;#property indicator_color2 Red&lt;br/&gt;#property indicator_width1 3&lt;br/&gt;#property indicator_width2 3&lt;br/&gt;&lt;br/&gt;input int TradePeriod=24;// Donchian channel period&lt;br/&gt;&lt;br/&gt;double ExtMapBuffer1[];&lt;br/&gt;double ExtMapBuffer2[];&lt;br/&gt;double TrendDirection[];&lt;br/&gt;&lt;br/&gt;static datetime TimeStamp;&lt;br/&gt;//+------------------------------------------------------------------+&lt;br/&gt;//| |&lt;br/&gt;//+------------------------------------------------------------------+&lt;br/&gt;int init()&lt;br/&gt;{&lt;br/&gt;IndicatorBuffers(3);&lt;br/&gt;&lt;br/&gt;SetIndexStyle(0,DRAW_LINE);&lt;br/&gt;SetIndexStyle(1,DRAW_LINE);&lt;br/&gt;IndicatorDigits((int)MarketInfo(Symbol(),MODE_DIGITS));&lt;br/&gt;&lt;br/&gt;IndicatorShortName(&quot;Donchian Channels (&quot;+IntegerToString(TradePeriod)+&quot;)&quot;);&lt;br/&gt;SetIndexLabel(0,&quot;Lower channel&quot;);&lt;br/&gt;SetIndexLabel(1,&quot;Upper channel&quot;);&lt;br/&gt;&lt;br/&gt;SetIndexBuffer(0,ExtMapBuffer1);&lt;br/&gt;SetIndexBuffer(1,ExtMapBuffer2);&lt;br/&gt;SetIndexBuffer(2,TrendDirection);&lt;br/&gt;&lt;br/&gt;return(0);&lt;br/&gt;}&lt;br/&gt;//+------------------------------------------------------------------+&lt;br/&gt;//| |&lt;br/&gt;//+------------------------------------------------------------------+&lt;br/&gt;int start()&lt;br/&gt;{&lt;br/&gt;int counted_bars=IndicatorCounted();&lt;br/&gt;if(counted_bars&amp;lt;0) return(-1); int limit=Bars-1-counted_bars; if(counted_bars==0) limit-=1+1; for(int i=limit; i&amp;gt;=0; i--)&lt;br/&gt;{&lt;br/&gt;TrendDirection[i]=TrendDirection[i+1];&lt;br/&gt;&lt;br/&gt;ExtMapBuffer1[i]=ExtMapBuffer2[i]=EMPTY_VALUE;&lt;br/&gt;&lt;br/&gt;double HighestHigh=iClose(Symbol(),Period(),iHighest(Symbol(),Period(),MODE_CLOSE,TradePeriod,i+1));&lt;br/&gt;double LowestLow=iClose(Symbol(),Period(),iLowest(Symbol(),Period(),MODE_CLOSE,TradePeriod,i+1));&lt;br/&gt;&lt;br/&gt;double CLOSE=iClose(Symbol(),0,i);&lt;br/&gt;&lt;br/&gt;if(i&amp;gt;0)&lt;br/&gt;{&lt;br/&gt;if(CLOSE&amp;gt;HighestHigh &amp;amp;&amp;amp; TrendDirection[i+1]!=OP_BUY)&lt;br/&gt;{&lt;br/&gt;TrendDirection[i]=OP_BUY;&lt;br/&gt;SendNotification(StringConcatenate(Symbol(),&quot; go long&quot;));&lt;br/&gt;}&lt;br/&gt;else if(CLOSE {&lt;br/&gt;TrendDirection[i]=OP_SELL;&lt;br/&gt;SendNotification(StringConcatenate(Symbol(),&quot; go short&quot;));&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;if(TrendDirection[i]==OP_BUY)&lt;br/&gt;ExtMapBuffer1[i]=LowestLow;&lt;br/&gt;else if(TrendDirection[i]==OP_SELL)&lt;br/&gt;ExtMapBuffer2[i]=HighestHigh;&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;return(0);&lt;br/&gt;}&lt;br/&gt;//+------------------------------------------------------------------+</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/8855665241790943077/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2017/09/using-donchian-indicator-to-enhance_23.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/8855665241790943077'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/8855665241790943077'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2017/09/using-donchian-indicator-to-enhance_23.html' title='Using the Donchian Indicator to enhance your Trading'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-2389195686040643464</id><published>2017-08-20T17:37:00.001+02:00</published><updated>2019-01-18T21:41:04.062+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>Checking Metatrader connectivity</title><content type='html'>When running Metatrader locally, the first action the platform does when it starts up is connecting to the near by broker server. You may it clearly by looking at the lower right part of the platform and checking the connectivity status:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone size-medium wp-image-282&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/08/Connectivity-1-226x300.jpg&quot; alt=&quot;Server Connectivity&quot; width=&quot;226&quot; height=&quot;300&quot; /&gt;&lt;br/&gt;&lt;br/&gt;In this case, you may see it is green and traffic is floating successfully between the terminal to the server. If from some reason, there is no connectivity, this terminal section would look like:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone size-medium wp-image-283&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/08/Connectivity-2-234x300.jpg&quot; alt=&quot;No Connectivity&quot; width=&quot;234&quot; height=&quot;300&quot; /&gt;&lt;br/&gt;&lt;br/&gt;&lt;h6&gt;Manual solution&lt;/h6&gt;&lt;br/&gt;&lt;br/&gt;The manual solution is quite straightforward, mainly close and reopening the terminal. The challenge is knowing the connectivity got lost at the first place. When it happens, there is no way to tell unless you write the code which tells you the connectivity got lost. Once you know it happened, you need to restart the terminal and hope the problem got sorted out. If it continues, you can either scan the available serves or contact your broker.&lt;br/&gt;&lt;br/&gt;&lt;h6&gt;Automated Connection monitoring&lt;/h6&gt;&lt;br/&gt;&lt;br/&gt;As noted above, it is challenging to know when the connectivity is lost if you&#39;re not sitting in front of your PC 24/5. For someone like who uses fully automated expert advisers, it is critical for me to know ASAP when the connectivity got lost. So, I will able to action on this issue and resolve it. The good news are that with 10-20 lines of code, you may create your own monitoring utility:&lt;br/&gt;- first, we setup a timer. As we can&#39;t trust OnTick function to be called when there is a disconnection with the server, we must check it every X minutes, I personally use an hourly timer:&lt;br/&gt;&lt;code&gt;EventSetTimer(60*PERIOD_H1);&lt;/code&gt;&lt;br/&gt;This will call OnTimer function every hour so we will be able to test for connectivity.&lt;br/&gt;- In the function OnTimer, I will check for connectivity and set a certain flag to notify me if the connectivity got restored:&lt;br/&gt;&lt;code&gt;void OnTimer()&lt;br/&gt;{&lt;br/&gt;if(IsDisconnectedFlag==false &amp;amp;&amp;amp; IsConnected()==false)&lt;br/&gt;{&lt;br/&gt;SendNotification(&quot;Broker connection lost...&quot;);&lt;br/&gt;IsDisconnectedFlag=true;&lt;br/&gt;}&lt;br/&gt;else if(IsDisconnectedFlag==true &amp;amp;&amp;amp; IsConnected()==true)&lt;br/&gt;{&lt;br/&gt;SendNotification(&quot;Broker connection retrieved...&quot;);&lt;br/&gt;IsDisconnectedFlag=false;&lt;br/&gt;}&lt;br/&gt;}&lt;br/&gt;&lt;/code&gt;&lt;br/&gt;This code simply notifies you if the connection got lost, or later on restored. Since the server connectivity is lost and not the internet connection, it is still possible to send notifications to your mobile device.&lt;br/&gt;&lt;br/&gt;With this simple addition to your expert adviser, you will be able to get notified in real time that the terminal lost connection with the broker so you can safely act on it and try to fix it.&lt;br/&gt;&lt;br/&gt;Don&#39;t forget to visit my &lt;a href=&quot;https://www.ilantree.com/downloads/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;downloads&lt;/a&gt; page for additional expert advisers, indicators and libraries.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/2389195686040643464/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2017/08/checking-metatrader-connectivity_20.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/2389195686040643464'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/2389195686040643464'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2017/08/checking-metatrader-connectivity_20.html' title='Checking Metatrader connectivity'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-1776670621702189415</id><published>2017-08-06T19:02:00.001+02:00</published><updated>2019-01-18T21:41:03.927+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><title type='text'>How to safely open an order in MQL4</title><content type='html'>All the functions discussed here are part of the &lt;a href=&quot;https://www.ilantree.com/downloads/common/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Common&lt;/a&gt; library available for purchase.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;In trading, it&#39;s critical to confirm certain criteria and conditions before opening an order. These checks may impact on your profitability or notify you in case something failed.&lt;br/&gt;&lt;br/&gt;&lt;h6&gt;My checks&lt;/h6&gt;&lt;br/&gt;&lt;br/&gt;For me, it&#39;s important to verify before opening an order in MQL4 the following conditions:&lt;br/&gt;- Is the spread acceptable? i.e. whether it&#39;s below a certain fixed value which I predefined.&lt;br/&gt;- Is the trade context busy? This thread is the one which eventually opens the orders, if busy, it will not be possible to open the order anyway.&lt;br/&gt;- Do we have enough margin to trade? As noted &lt;a href=&quot;https://www.ilantree.com/useful-mql4-lot-size-functions/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;, margin is critical factor when trading and could make a difference between a successful account to wiped one.&lt;br/&gt;- Check open order returned value. As per MQL4 specifications, open order returns the order id which was opened or -1 in case it failed - &lt;a href=&quot;https://docs.mql4.com/trading/ordersend&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://docs.mql4.com/trading/ordersend&lt;/a&gt;. It is a good practice to check the value before doing anything with that order.&lt;br/&gt;&lt;br/&gt;&lt;h6&gt;Coding it all&lt;/h6&gt;&lt;br/&gt;&lt;br/&gt;Let&#39;s build the code that does these checks and open an order if all conditions are satisfied. The function signature is:&lt;br/&gt;&lt;code&gt;int OpenOrder(string argSymbol,int argOrderType,double argLotSize,double argSL=0,double argTP=0,string argComment=NULL,int argMagicNumber=0,int argSpread=0) export&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;The function returns the value received from OrderSend function, or -1 if the function fails from any reason.&lt;br/&gt;1. argSymbol is the symbol we want to open order on.&lt;br/&gt;2. argOrderType whether it&#39;s OP_BUY or OP_SELL&lt;br/&gt;3. argLotSize - how many lots we want to trade&lt;br/&gt;4. argSL - optional argument holding the order stop loss level. If the order is a Buy, then the stop loss must be below the open price, otherwise, for a sell, the stop loss must be above the open price.&lt;br/&gt;5. argTP - optional argument holding the order take profit level. If the order is a Buy, then the take profit must be above the open price, otherwise, for a sell, the take profit must be below the open price.&lt;br/&gt;6. argComment - optional string to use as the order&#39;s comment. Please note, that If the order comment length is above 31 characters. the mt4 server will automatically reject the order.&lt;br/&gt;7. argMagicNumber - optional integer representing the order magic number, a value which can be used later to link order to an expert adviser.&lt;br/&gt;8. argSpread - an optional value used as a spread threshold to open an order.&lt;br/&gt;&lt;br/&gt;&lt;h6&gt;putting it all together&lt;/h6&gt;&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;&lt;li&gt;starting from the last argument, if provided I will not open an order, if the symbol spread is larger than the value:&lt;br/&gt;&lt;code&gt;if(argSpread&amp;gt;0 &amp;amp;&amp;amp; MarketInfo(argSymbol,MODE_SPREAD)&amp;gt;argSpread)&lt;br/&gt;{&lt;br/&gt;SendNotification(StringConcatenate(&quot;Open order declined, symbol spread &quot;,DoubleToString(MarketInfo(argSymbol,MODE_SPREAD),0),&quot; is larger than &quot;,IntegerToString(argSpread)));&lt;br/&gt;return -1;&lt;br/&gt;}&lt;/code&gt;&lt;br/&gt;Using the latest spread value for this symbol, I reject it if it&#39;s larger.&lt;/li&gt;&lt;br/&gt;&lt;li&gt;Next, I am checking whether the trade context, the thread which is responsible for the order themselves is busy. If it is, I will reject the open order request:&lt;br/&gt;&lt;code&gt;else if(IsTradeContextBusy())&lt;br/&gt;{&lt;br/&gt;SendNotification(&quot;Open order declined, trade context is busy&quot;);&lt;br/&gt;return -1;&lt;br/&gt;}&lt;/code&gt;&lt;/li&gt;&lt;br/&gt;&lt;li&gt;If the function was called with an order type different than OP_BUY/OP_SELL this code will reject &lt;code&gt;if(argOrderType!=OP_BUY &amp;amp;&amp;amp; argOrderType!=OP_SELL)&lt;br/&gt;{&lt;br/&gt;SendNotification(StringConcatenate(&quot;Open order declined, illegal order type = &quot;,IntegerToString(argOrderType)));&lt;br/&gt;return -1;&lt;br/&gt;}&lt;/code&gt;&lt;/li&gt;&lt;br/&gt;&lt;li&gt;We then check for enough margin to make this order, but calling a function I mentioned in my post about margin:&lt;br/&gt;&lt;code&gt;else if(ConfirmEnoughMargin(argSymbol,argOrderType,argLotSize)==false)&lt;br/&gt;{&lt;br/&gt;SendNotification(StringConcatenate(&quot;Open order declined, not enough equity to open new position, remaining equity if opened = &quot;,DoubleToString(AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize),2),&quot; &quot;,AccountCurrency()));&lt;br/&gt;return -1;&lt;br/&gt;}&lt;/code&gt;&lt;br/&gt;Where ConfirmEnoughMargin is defined as:&lt;br/&gt;&lt;code&gt;bool ConfirmEnoughMargin(string argSymbol,int argOrderType,double argLotSize) export&lt;br/&gt;{&lt;br/&gt;if(AccountStopoutMode()==0 &amp;amp;&amp;amp; MathRound(AccountMargin()+AccountFreeMargin()-AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize))!=0 &amp;amp;&amp;amp; (100*AccountEquity()/(AccountMargin()+AccountFreeMargin()-AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize)))&amp;lt;AccountStopoutLevel() &amp;amp;&amp;amp; GetLastError()==134)&lt;br/&gt;{&lt;br/&gt;SendNotification(StringConcatenate(&quot;Confrim enough margin failed with account stopout mode 0, free margin if opened will be &quot;,DoubleToString(AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize),2)),134);&lt;br/&gt;return false;&lt;br/&gt;}&lt;br/&gt;else if(AccountStopoutMode()==1 &amp;amp;&amp;amp; AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize)&amp;lt;AccountStopoutLevel() &amp;amp;&amp;amp; GetLastError()==134)&lt;br/&gt;{&lt;br/&gt;SendNotification(argSymbol,argLotSize,StringConcatenate(&quot;Confrim enough margin failed with account stopout mode 1, free margin if opened will be &quot;,DoubleToString(AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize),2)),134);&lt;br/&gt;return false;&lt;br/&gt;}&lt;br/&gt;return true;&lt;br/&gt;}&lt;/code&gt;&lt;/li&gt;&lt;br/&gt;&lt;li&gt;Finally, if all the checks passed successfully, we call MQL4 internal OrderSend function and return the value:&lt;br/&gt;&lt;code&gt;else&lt;br/&gt;{&lt;br/&gt;int Order=OrderSend(argSymbol,argOrderType,VerifyLotSize(argSymbol,argLotSize),argOrderType==OP_BUY?MarketInfo(argSymbol,MODE_ASK):MarketInfo(argSymbol,MODE_BID),Slippage,NormalizeDouble(argSL,(int)MarketInfo(argSymbol,MODE_DIGITS)),NormalizeDouble(argTP,(int)MarketInfo(argSymbol,MODE_DIGITS)),argComment==NULL?MQLInfoString(MQL_PROGRAM_NAME):argComment,argMagicNumber,0,argOrderType==OP_BUY?clrGreen:clrRed);&lt;br/&gt;if(Order==-1)&lt;br/&gt;LogError(argSymbol,argLotSize,&quot;Open order failed&quot;);&lt;br/&gt;return Order;&lt;br/&gt;}&lt;/code&gt;&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;The whole function is:&lt;br/&gt;&lt;code&gt;int OpenOrder(string argSymbol,int argOrderType,double argLotSize,double argSL=0,double argTP=0,string argComment=NULL,int argMagicNumber=0,int argSpread=0) export&lt;br/&gt;{&lt;br/&gt;if(argSpread&amp;gt;0 &amp;amp;&amp;amp; MarketInfo(argSymbol,MODE_SPREAD)&amp;gt;argSpread)&lt;br/&gt;{&lt;br/&gt;LogError(argSymbol,argLotSize,StringConcatenate(&quot;Open order declined, symbol spread &quot;,DoubleToString(MarketInfo(argSymbol,MODE_SPREAD),0),&quot; is larger than &quot;,IntegerToString(argSpread)));&lt;br/&gt;return -1;&lt;br/&gt;}&lt;br/&gt;else if(IsTradeContextBusy())&lt;br/&gt;{&lt;br/&gt;LogError(argSymbol,argLotSize,&quot;Open order declined, trade context is busy&quot;);&lt;br/&gt;return -1;&lt;br/&gt;}&lt;br/&gt;if(argOrderType!=OP_BUY &amp;amp;&amp;amp; argOrderType!=OP_SELL)&lt;br/&gt;{&lt;br/&gt;LogError(argSymbol,argLotSize,StringConcatenate(&quot;Open order declined, illegal order type = &quot;,IntegerToString(argOrderType)));&lt;br/&gt;return -1;&lt;br/&gt;}&lt;br/&gt;else if(ConfirmEnoughMargin(argSymbol,argOrderType,argLotSize)==false)&lt;br/&gt;{&lt;br/&gt;LogError(argSymbol,argLotSize,StringConcatenate(&quot;Open order declined, not enough equity to open new position, remaining equity if opened = &quot;,DoubleToString(AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize),2),&quot; &quot;,AccountCurrency()));&lt;br/&gt;return -1;&lt;br/&gt;}&lt;br/&gt;else&lt;br/&gt;{&lt;br/&gt;int Order=OrderSend(argSymbol,argOrderType,VerifyLotSize(argSymbol,argLotSize),argOrderType==OP_BUY?MarketInfo(argSymbol,MODE_ASK):MarketInfo(argSymbol,MODE_BID),Slippage,NormalizeDouble(argSL,(int)MarketInfo(argSymbol,MODE_DIGITS)),NormalizeDouble(argTP,(int)MarketInfo(argSymbol,MODE_DIGITS)),argComment==NULL?MQLInfoString(MQL_PROGRAM_NAME):argComment,argMagicNumber,0,argOrderType==OP_BUY?clrGreen:clrRed);&lt;br/&gt;if(Order==-1)&lt;br/&gt;LogError(argSymbol,argLotSize,&quot;Open order failed&quot;);&lt;br/&gt;return Order;&lt;br/&gt;}&lt;br/&gt;}&lt;/code&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/1776670621702189415/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2017/08/how-to-safely-open-order-in-mql4_6.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1776670621702189415'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/1776670621702189415'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2017/08/how-to-safely-open-order-in-mql4_6.html' title='How to safely open an order in MQL4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-3435935633927524637</id><published>2017-07-17T13:37:00.001+02:00</published><updated>2019-01-18T21:41:03.822+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Correlation"/><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="Indicators"/><category scheme="http://www.blogger.com/atom/ns#" term="mql4"/><title type='text'>Forex correlation calculation with MQL4</title><content type='html'>All the functions discussed here are part of the &lt;a href=&quot;https://www.ilantree.com/downloads/statistics/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Statistics&lt;/a&gt; library available for purchase.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;While watching Wimbledon finals yesterday in the UK. I was thinking of all the significant economical events we are going through in Europe, the Brexit, elections etc. and how are the different pairs I am trading got affected. The statistical value which show the significance of the dependency between two products is called Correlation.&lt;br/&gt;&lt;br/&gt;According to &lt;a href=&quot;https://en.wikipedia.org/wiki/Correlation_and_dependence&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://en.wikipedia.org/wiki/Correlation_and_dependence&lt;/a&gt;, Correlation can be calculated using the following equation:&lt;br/&gt;&lt;br/&gt;Correlation(EURUSD,USDJPY)=Covariance(EURUSD,USDJPY) / STD(EURUSD)*STD(USDJPY)&lt;br/&gt;&lt;br/&gt;Correlation ranges between -1, that when EURUSD trends upwards, USDJPY expected to trend downwards. 0, meaning there is no dependency between these currencies at all. Or +1, meaning the currencies are expected to trend in the same direction.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Why would you care?&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;EURUSD and EURCHF have correlation of -1 in most of the times. Imagine you went long on EURUSD believing there is an upwards potential for the currency and profit to be made. Now, if indeed EURCHF is reversed correlated to EURUSD, opening a short position on EURCHF will increase your risk twice when EURUSD changes direction. Because now, EURUSD will be short, and EURCHF which is reversed correlated will go long. You are losing both on the long EURUSD position AND the short EURCHF one.&lt;br/&gt;&lt;br/&gt;If you are not able to calculate Correlations dynamically, you would not identify this situation and make this mistake, not able to recognize what went wrong. The challenge with calculating correlation is the dynamics of the products. The values are always changing, it is not a static set of values which are easy to calculate.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Calculating Correlation step by step&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;We start with the simple part of the equation and that is the denominator. Meaning, we need to calculate the standard deviation of the currency for a given values over a period of time. Standard deviation is defined as the squared root of the sample variance, which is the sum of differences of the sample from the sample mean:&lt;br/&gt;&lt;br/&gt;Standard Deviation = Square(Variance(EURUSD)) = Square(∑(EURUSDi - mean(EURUSD)) / Sample Size)&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Calculating the mean&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;Let&#39;s start by calculating the sample mean. This is basically running over the sample which is captured in an array, summing the values and dividing with the sample size.&lt;br/&gt;&lt;br/&gt;double Mean(double &amp;amp;argArr[]) export&lt;br/&gt;{&lt;br/&gt;double length=ArraySize(argArr);&lt;br/&gt;&lt;br/&gt;double sum=0;&lt;br/&gt;for(int i=(int)(length-1); i&amp;gt;=0; i--)&lt;br/&gt;sum+=argArr[i];&lt;br/&gt;return sum/length;&lt;br/&gt;}&lt;br/&gt;Since I place this function in a library, I used the keyword export. This function runs on argArr, summing it&#39;s values and then dividing by the array size.&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Calculating the variance&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;In the previous step, we calculated the sample mean. Now we will use it to calculate the sample variance. As per the variance formula, we need to sum up the square difference of the sample values from it&#39;s mean:&lt;br/&gt;&lt;br/&gt;double Variance(double &amp;amp;argArr[]) export&lt;br/&gt;{&lt;br/&gt;double length=ArraySize(argArr);&lt;br/&gt;double mean=Mean(argArr);&lt;br/&gt;&lt;br/&gt;double sum=0;&lt;br/&gt;for(int i=(int)(length-1); i&amp;gt;=0; i--)&lt;br/&gt;sum+=MathPow(argArr[i]-mean,2);&lt;br/&gt;return sum/(length-1);&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;Again, I am using this function from within a library, so I used the export reserved keyword. Then, calling the Mean function introduced in the previous part, mean saves the argArr mean value. All we have to do, is to run over the array and sum up the difference between the array values in index i to the mean we calculated. The returned value is the sample&#39;s variance, thus we divide it with (n-1).&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Calculating the standard deviation&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;This part is rather simple. Since we have the sample&#39;s variance calculated already, all we need to do is to return it&#39;s squared root:&lt;br/&gt;&lt;br/&gt;double StandardDeviation(double &amp;amp;argArr[]) export&lt;br/&gt;{&lt;br/&gt;return MathSqrt(Variance(argArr));&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;As you can see, the standard deviation function only calculates the squared root on the variance function return value.&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Calculating Covariance&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;double Covariance(double &amp;amp;arrX[],double &amp;amp;arrY[]) export&lt;br/&gt;{&lt;br/&gt;if(ArraySize(arrX)!=ArraySize(arrY))&lt;br/&gt;return -1;&lt;br/&gt;&lt;br/&gt;double length=ArraySize(arrX);&lt;br/&gt;double meanX=Mean(arrX);&lt;br/&gt;double meanY=Mean(arrY);&lt;br/&gt;&lt;br/&gt;numerator=0;&lt;br/&gt;for(int i=(int)(length-1); i&amp;gt;=0; i--)&lt;br/&gt;numerator+=(arrX[i]-meanX)*(arrY[i]-meanY);&lt;br/&gt;return numerator/(length-1);&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;Covariance is the sum of differences between a value to it&#39;s mean between two series. So, in this case we calculate the mean of EURUSD, the mean of USDJPY and sum up the differences of the values from the currency series with the mean. Then dividing it with the series length-1 as it is a sample.&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Putting it all together&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;Now that we have it all the necessary code to calculate the correlation between two products, it&#39;s time to put it into action. The following code shows as an example how to print the correlation between the current product to the other open orders you have. You may use this code and print to the screen the correlation between the different products:&lt;br/&gt;&lt;br/&gt;const int CORRELATION_HISTORY=2&lt;em&gt;5&lt;/em&gt;24;&lt;br/&gt;double X[],Y[];&lt;br/&gt;ArrayResize(X,CORRELATION_HISTORY);&lt;br/&gt;ArrayInitialize(X,0);&lt;br/&gt;&lt;br/&gt;for(int i=0;i&amp;lt;CORRELATION_HISTORY;i++)&lt;br/&gt;X[i]=iClose(Symbol(),PERIOD_H1,i);&lt;br/&gt;&lt;br/&gt;ArrayResize(Y,CORRELATION_HISTORY);&lt;br/&gt;string CorrelationStr=&quot;&quot;;&lt;br/&gt;string CurrSymbol=&quot;&quot;;&lt;br/&gt;for(int i=OrdersTotal()-1;i&amp;gt;=0;i--)&lt;br/&gt;if(OrderSelect(i,SELECT_BY_POS) &amp;amp;&amp;amp; StringFind(CorrelationStr,OrderSymbol())==-1 &amp;amp;&amp;amp; StringCompare(OrderSymbol(),Symbol())!=0)&lt;br/&gt;{&lt;br/&gt;CurrSymbol=OrderSymbol();&lt;br/&gt;ArrayInitialize(Y,0);&lt;br/&gt;for(int j=0;j&amp;lt;CORRELATION_HISTORY;j++)&lt;br/&gt;Y[j]=iClose(CurrSymbol,PERIOD_H1,j); CorrelationStr=StringConcatenate(CurrSymbol,&quot; &quot;,DoubleToString(Correlation(X,Y),2),&quot; &quot;,CorrelationStr);&lt;br/&gt;}&lt;br/&gt;Print(CorrelationStr);&lt;br/&gt;&lt;br/&gt;I normally take a period of 240 values, but of course you may take larger values if you want. The following output shows the correlation between USDJPY to the other products I have open orders on:&lt;br/&gt;&lt;br/&gt;&lt;a href=&quot;https://www.ilantree.com/wp-content/uploads/2017/07/img_9230.jpg&quot;&gt;&lt;img class=&quot;alignnone size-full wp-image-192&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/07/img_9230.jpg&quot; alt=&quot;&quot; width=&quot;744&quot; height=&quot;135&quot; /&gt;&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/3435935633927524637/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2017/07/forex-correlation-calculation-with-mql4_17.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3435935633927524637'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/3435935633927524637'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2017/07/forex-correlation-calculation-with-mql4_17.html' title='Forex correlation calculation with MQL4'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-4193127151630954323</id><published>2017-07-02T18:10:00.001+02:00</published><updated>2019-01-18T21:41:03.599+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="Expert Advisor"/><title type='text'>The MQL4 Lot Size Functions I Use In My Algotrading Code</title><content type='html'>All the functions discussed here are part of the &lt;a href=&quot;https://www.ilantree.com/downloads/common/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Common&lt;/a&gt; library available for purchase.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;The goal of this post is to share with you some functions I am using to verify and manage the lot size I used when opening an order. As mentioned in my &lt;a href=&quot;https://www.ilantree.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;home&lt;/a&gt; page, I am using proprietary algorithm to trade the 25% cash I don&#39;t invest in the &lt;a href=&quot;https://www.ilantree.com/portfolio-performance-h12017/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;permanent portfolio&lt;/a&gt;. To achieve that, I programmed an Expert Advisor using MQL language which is running 24/5 and trade 5 currency pairs. In &lt;a href=&quot;https://www.darwinex.com/darwin/GFA.4.21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;, you can find the relevant darwin which can be traded as a normal financial product thanks to the Darwinex broker.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Managing Lot Size&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;As noted in another post about &lt;a href=&quot;https://www.ilantree.com/leverage-explained/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;leverage,&lt;/a&gt; it is important to keep the leverage / lot size under control. Most common junior mistakes are trading massive lot sizes to gain quick wins, but as soon as the market turns against them, their account is completely wiped out without a chance to react (speaking from experience). So, in this post I will share three functions I am using to verify and manage lot sizes I am using in my own expert advisor. You may copy paste this code and use it on your own responsibility in your own code.&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Verify Lot Size&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone wp-image-177 size-medium&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/07/4478696790_8e20d53092_o-268x300.jpg&quot; alt=&quot;Lot Size&quot; width=&quot;268&quot; height=&quot;300&quot; /&gt;&lt;br/&gt;&lt;br/&gt;Perhaps the simplest and most common function of all. I use this one whenever I am about to open a position, to verify the lot size is:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Above the minimum lot size allowed&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Below the maximum lot size allowed&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Allows micro or mini lots as per the broker.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;&lt;code&gt;double VerifyLotSize(string argSymbol,double argLotSize) export&lt;br/&gt;{&lt;br/&gt;argLotSize=MarketInfo(argSymbol,MODE_LOTSTEP)==0.1?NormalizeDouble(argLotSize,1):NormalizeDouble(argLotSize,2);&lt;br/&gt;return MathMax(MarketInfo(argSymbol,MODE_MINLOT),MathMin(MarketInfo(argSymbol,MODE_MAXLOT),argLotSize));&lt;br/&gt;}&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Starting from the declaration, you can the return value is the actual verified lot size. There are two arguments, the symbol you want to open the order for and the lot size you want to open. A typical call would look like:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;double Lots=VerifyLotSize(&quot;EURUSD&quot;,0.02);&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;If the size provided is legitimate, the return value will be equal to the input, in this case to 0.02 lot size. On the other hand, there are a couple of checks happening which will influence the result:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;First, we check in &lt;code&gt;MarketInfo(argSymbol,MODE_LOTSTEP)&lt;/code&gt; how many digits the broker allows, whether mini lots are allowed (0.1) or micro as well (0.01). Based on the return value, we trim the lot size if needed. If for example, the broker only allows mini lots, 0.11 will turn into 0.1 lots and the 0.01 will get trimmed.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Then, &lt;code&gt;MathMin(MarketInfo(argSymbol,MODE_MAXLOT),argLotSize)&lt;/code&gt; verifies that the requested lot size is smaller than the maximum for that currency, in my case, the maximum lot size I can open per trade is 1,000 which is 100,000,000 units.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Finally, &lt;code&gt;MathMax&lt;/code&gt; is called on the result of the previous step to verify the lot size is larger than the minimum lot size offered by the broker.&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;Running this function on several examples for EURUSD will give the following output:&lt;br/&gt;&lt;br/&gt;&lt;code&gt; Print(VerifyLotSize(Symbol(),0.001)); --&amp;gt; 0.01&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(VerifyLotSize(Symbol(),0.00)); --&amp;gt; 0.01&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(VerifyLotSize(Symbol(),100000.001)); --&amp;gt; 1,000&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(VerifyLotSize(Symbol(),0.123)); --&amp;gt; 0.12&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Best place to use this function is right before opening an order, so you can be certain that the lot size you are using is legal. I normally use specific exposure per trade based on percentage from my equity so it looks like that:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;double Lots = VerifyLotSize(TheSymbol,(Exposure/100)*AccountEquity()/100000);&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Confirm Enough Margin&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;[caption id=&quot;attachment_176&quot; align=&quot;alignnone&quot; width=&quot;300&quot;]&lt;img class=&quot;size-medium wp-image-176&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/07/31228042685_12aa801b43_o-300x169.jpg&quot; alt=&quot;Enough Margin&quot; width=&quot;300&quot; height=&quot;169&quot; /&gt; photo by &lt;a href=&quot;https://www.cafecredit.com&quot;&gt;CafeCredit&lt;/a&gt;[/caption]&lt;br/&gt;&lt;br/&gt;The next function verifies whether you have enough margin before opening the order. So, if you know how much lots you want to trade and verified it in the previous step, this step will check if you even have enough margin to open the order at all.&lt;br/&gt;&lt;br/&gt;&lt;code&gt;bool ConfirmEnoughMargin(string argSymbol,int argOrderType,double argLotSize) export { if(AccountStopoutMode()==0 &amp;amp;&amp;amp; (AccountMargin()+AccountFreeMargin()-AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize))!=0 &amp;amp;&amp;amp; (100*AccountEquity()/(AccountMargin()+AccountFreeMargin()-AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize)))&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;As per the signature, this function returns true or false based on the check it performs. The inputs are the symbol you want to open the order on, the lots size you want to trade and order type which is either OP_BUY or OP_SELL.&lt;br/&gt;&lt;br/&gt;As described in MQL &lt;a href=&quot;https://docs.mql4.com/account/accountstopoutmode&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;reference&lt;/a&gt;, there are two modes to calculate whether you have enough margin to open the order:&lt;br/&gt;&lt;br/&gt;&lt;span class=&quot;f_Function&quot;&gt;0 - calculation of percentage ratio between margin and equity.&lt;/span&gt;&lt;br/&gt;&lt;span class=&quot;f_Function&quot;&gt;1 - comparison of the free margin level to the absolute value.&lt;/span&gt;&lt;br/&gt;&lt;br/&gt;Based on that, I built the function to confirm there is enough margin to open the trade:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;If your broker is using the percentage method. We need to check that the ratio between the account equity and the margin is less the the stop out level using the following code - &lt;code&gt;(100*AccountEquity()/(AccountMargin()+AccountFreeMargin()-AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize)))&lt;/code&gt;&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;On the other case, if you broker is using method number 1 to compare the margin to the absolute value, we use the following code &lt;code&gt;- AccountFreeMarginCheck(argSymbol,argOrderType,argLotSize)&lt;/code&gt;&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;In both case, if the check fails, and opening the order will result with a situation you won`t have enough margin, error 134 will be thrown. In this case the function fails and a false value will return. Otherwise, if both checks passes, a true will return and you may proceed and open this position. Using this function will save you an error returned from the open order and check whether the order ticket is not equal to -1 upon failure.&lt;br/&gt;&lt;br/&gt;Running this function on several examples for EURUSD will give the following output, assuming equity is 100,000:&lt;br/&gt;&lt;br/&gt;&lt;code&gt; Print(ConfirmEnoughMargin(Symbol(),OP_BUY,0.01)); --&amp;gt; true&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(ConfirmEnoughMargin(Symbol(),OP_BUY,1)); --&amp;gt; true&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(ConfirmEnoughMargin(Symbol(),OP_BUY,100)); --&amp;gt; true&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(ConfirmEnoughMargin(Symbol(),OP_BUY,1000)); --&amp;gt; false&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;You can see in the last case it is failing, as I am trying to open a position to control 100,000,000 Units which requires a margin of 500,000 which is more than my equity. Otherwise, the other functions return true so it is safe from margin point of view to open them. Still, it doesn`t mean you need to ignore your effective leverage and make sure you are still nicely leverage, i.e. below 1:10 as explained &lt;a href=&quot;https://www.ilantree.com/leverage-explained/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Calculate Lot Size Based On Risk&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone size-medium wp-image-178&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/07/2219876290_0095abf466_o-300x221.jpg&quot; alt=&quot;Risk&quot; width=&quot;300&quot; height=&quot;221&quot; /&gt;&lt;br/&gt;&lt;br/&gt;The last function in my arsenal is to calculate the lot size I want to open based on a risk parameter. In my case, I use the volatility to open an order which will loss at the worse case a certain percentage of my account over a specific timeframe.&lt;br/&gt;&lt;br/&gt;&lt;code&gt;double CalcRiskBasedLotSize(string argSymbol,double argPercentageRiskPerOrder,int argTimeframe,int argSTDFactor,int argSTDPeriod) export { double Risk=AccountBalance()*argPercentageRiskPerOrder/100; double STDPips=argSTDFactor*iStdDev(argSymbol,argTimeframe,argSTDPeriod,0,MODE_SMA,PRICE_CLOSE,0)/MarketInfo(argSymbol,MODE_POINT); return STDPips==0?MarketInfo(argSymbol,MODE_MINLOT):VerifyLotSize(argSymbol,Risk/(STDPips*MarketInfo(argSymbol,MODE_TICKVALUE))); }&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;This function return value is the calculated lot size based on the risk parameters you provide:&lt;br/&gt;&lt;br/&gt;&lt;ul&gt;&lt;br/&gt;    &lt;li&gt;argSymbol - product the calculate the lot for.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;argPercentageRiskPerOrder - how much you want to risk for this trade (1%, 2%...).&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;argTimeframe - timeframe to calculate the volatility (PERIOD_D1, PERIOD_H1...).&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;argSTDFactor - factor to multiply the volatility, in case you want to have double the amount, triple etc...&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;argSTDPeriod - period to test the volatility over&lt;/li&gt;&lt;br/&gt;&lt;/ul&gt;&lt;br/&gt;&lt;br/&gt;The first line of code calculate how much of your balance you would like to risk as per the first argument -  &lt;code&gt;double Risk=AccountBalance()*argPercentageRiskPerOrder/100;&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Then, using the next parameters we calculate how much volatility in pips we have in his timeframe - &lt;code&gt;double STDPips=argSTDFactor*iStdDev(argSymbol,argTimeframe,argSTDPeriod,0,MODE_SMA,PRICE_CLOSE,0)/MarketInfo(argSymbol,MODE_POINT);&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;The division with MarketInfo(argSymbol, MODE_POINT) make sure we convert it from decimal value to pips value.&lt;br/&gt;&lt;br/&gt;Finally, the last line calculate the lot size according to the risk parameters. The main part is &lt;code&gt;Risk/(STDPips*MarketInfo(argSymbol,MODE_TICKVALUE))&lt;/code&gt;. Here, we divide the amount we would like to risk with the volatility. The value we get is the lot size, that over this volatility will lose the amount we calculated in the first stage.&lt;br/&gt;For example, let&#39;s say you have an account with 100,000 USD and you want to risk 2% of it using the daily volatility. Using a daily volatility of 890 pips the calculated pips will be:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;(2%*100,000) / 890 = 2.24.&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;Meaning, that if the order goes 890 pips against you as per the daily volatility, you will lost 2,000 USD which is 2% from your equity.&lt;br/&gt;&lt;br/&gt;In my code, usually I run it with the following input - &lt;code&gt;double Lots = CalcRiskBasedLotSize(&quot;EURUSD&quot;,2%,PERIOD_D1,1,20)&lt;/code&gt;, which calculates the lot size based on 20 days volatility.&lt;br/&gt;&lt;br/&gt;Running an example code with different values gives the following values:&lt;br/&gt;&lt;br/&gt;&lt;code&gt; Print(CalcRiskBasedLotSize(&quot;EURUSD&quot;,1,PERIOD_D1,1,20)); --&amp;gt; 1.69&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(CalcRiskBasedLotSize(&quot;EURUSD&quot;,2,PERIOD_D1,1,20)); --&amp;gt; 3.38&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(CalcRiskBasedLotSize(&quot;EURUSD&quot;,1,PERIOD_M1,1,20)); --&amp;gt; 140.98&lt;/code&gt;&lt;br/&gt;&lt;code&gt; Print(CalcRiskBasedLotSize(&quot;EURUSD&quot;,1,PERIOD_W1,1,20)); --&amp;gt; 0.63&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;If you look at the third line, you might be surprise we got 140.98 as lot size. But if you think about it, the volatility for one minute is really low, so to risk 1% of your balance, you must open a very large lot size position.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Summary&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;I presented these three functions I used almost always in my algotrading code. It make my code safe to use and run 24/5 a week, recognize errors and prevent over leveraging my portfolio. On top of these functions I have separate error handling logic I didn`t present when this functions return a negative value. One trick I usually do is setting a value to the AccountMargin() and &quot;putting&quot; the EA to sleep until the margin changes, but I will cover error handling in another post.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/4193127151630954323/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2017/07/the-mql4-lot-size-functions-i-use-in-my_2.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4193127151630954323'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/4193127151630954323'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2017/07/the-mql4-lot-size-functions-i-use-in-my_2.html' title='The MQL4 Lot Size Functions I Use In My Algotrading Code'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3581778232347889594.post-7535894210026873884</id><published>2017-07-01T22:39:00.001+02:00</published><updated>2019-01-18T21:41:03.321+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Default"/><category scheme="http://www.blogger.com/atom/ns#" term="Investing"/><category scheme="http://www.blogger.com/atom/ns#" term="Permanent portfolio"/><title type='text'>Swiss Permanent Portfolio Performance H1/2017</title><content type='html'>The first half of the year is over, time to check the Swiss permanent portfolio performance. As per the definition set by Harry Brown, the permanent portfolio should consist of 4 pillars:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;Equities&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Bondsbonds.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Gold&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;Cash&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;&lt;h4&gt;Swiss Permanent Portfolio Version&lt;/h4&gt;&lt;br/&gt;&lt;br/&gt;Using the above template as basis and as explained in &lt;a href=&quot;https://www.ilantree.com/about/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;, I split my investment within 3 funds:&lt;br/&gt;&lt;br/&gt;&lt;ol&gt;&lt;br/&gt;    &lt;li&gt;&lt;a href=&quot;https://www.six-swiss-exchange.com/funds/security_info_de.html?id=CH0106027128CHF4&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;AUCHAH &lt;/a&gt;- The fund aims to primarily reflect gold&#39;s performance, after deduction of the running costs. The fund&#39;s assets are exclusively invested in physical Gold.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;a href=&quot;https://www.six-swiss-exchange.com/funds/security_info_de.html?id=CH0016999861CHF4&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;CSBGC0 &lt;/a&gt;- The fund invests exclusively in bonds and other fixed or variable-rate debt instruments and rights, denominated in Swiss francs, of the Swiss Confederation, which are included in the Swiss Bond Index Domestic Government 7+.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;a href=&quot;https://www.six-swiss-exchange.com/funds/security_info_de.html?id=CH0131872431CHF4&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;SPICHA &lt;/a&gt;- The fund&#39;s investment objective is to replicate the price performance and returns of the Swiss Performance Index SPI(R). The SPI(R) comprises the about 230 largest stocks in the Swiss equity market.&lt;/li&gt;&lt;br/&gt;    &lt;li&gt;&lt;a href=&quot;https://www.darwinex.com/darwin/DKL.4.11&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Cash&lt;/a&gt; - Using my own proprietary algorithm to trade with Darwinex.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;January - June Performance&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;Just looking at the first three asset classes during the first six months. We can see that both equities and gold performed well, summing up to 16.46%:&lt;br/&gt;&lt;br/&gt;&lt;img class=&quot;alignnone wp-image-163 size-full&quot; src=&quot;https://www.ilantree.com/wp-content/uploads/2017/07/Capture.jpg&quot; alt=&quot;Performance in the first six month&quot; width=&quot;906&quot; height=&quot;640&quot; /&gt;&lt;br/&gt;&lt;br/&gt;This is somehow weird behavior as normally Gold and Equities are correlated reversely to each other, i.e. Gold tends to rise when Equities fall and vice versa. For me it shows that the market is not really certain what is going on, from one side rise of the equities is a good sign of stability and growth, but on the side gold appreciation shows a mood of uncertainty and worries.&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;In Summary&lt;/h3&gt;&lt;br/&gt;&lt;br/&gt;The beauty of the permanent portfolio is it&#39;s ability to generate positive revenue independently of the market behavior. There will always be a part which benefits of the current financial atmosphere. Growth environment will push the equities part upwards, inflation affects the gold and deflation affects positively the bonds. I created the Swiss version mentioned above since I want to remove the currency risk out of the equation.&lt;br/&gt;&lt;br/&gt;I love this setup as it is so easy to build and maintain. Basically, you need to make sure there is always equal parts of your capital split between the assets. Once in every three months invest your saved capital and re-balance the portfolio, that`s about it.&lt;br/&gt;&lt;br/&gt;&lt;hr /&gt;&lt;br/&gt;&lt;br/&gt;Disclaimer: I am an amateur investor. I don&lt;code&gt;t have financial adviser license or any other financial license. The contents of this post are not professional guidance or recommendation to do any action with any financial instrument and you can&lt;/code&gt;t use them instead of consulting a professional who knows your specific needs. If you choose to use this information, you are doing it on your account and responsibility.</content><link rel='replies' type='application/atom+xml' href='https://ilantree.blogspot.com/feeds/7535894210026873884/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://ilantree.blogspot.com/2017/07/swiss-permanent-portfolio-performance_1.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7535894210026873884'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/3581778232347889594/posts/default/7535894210026873884'/><link rel='alternate' type='text/html' href='https://ilantree.blogspot.com/2017/07/swiss-permanent-portfolio-performance_1.html' title='Swiss Permanent Portfolio Performance H1/2017'/><author><name>Roy Meshulam</name><uri>https://plus.google.com/104926270773883822829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-J3K1iuMu0i4/AAAAAAAAAAI/AAAAAAAA9us/kNcxTOEfE34/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry></feed>