The world's financial markets offer you a huge potential for profit and loss. There is always a potential for profit in the market as you can place trades in either direction. Whether your stance be bullish or bearish, the ability for the trader to make money is always present—as is the ability to make a loss.
Taking emotions out of the equation is one measure, but this does not mean robots cannot lose. In fact, even the big investment banks have had to pull the plug on their trading robots before the loss became fatal. You are responsible ultimately for the trades, even if program code is placing them for you. While loss is a possibility, you can also multiply the account and make it grow exponentially while you sleep. You could literally make money passively whilst you continue with your day-to-day life.
This strategy of totally hands-free trading is not one I promote—nor is it one I ever use and have found profitable at all. Monitoring an active robot and the current trades, in conjunction with keeping an eye on the economic calendar and events, is very different from letting it off wild and hoping for the best. The wins may be epic, but the unattended losses far grander. Once MT4 is running, you will need an account with a broker that supports MT4. They will then be able to give you your MT4 login credentials.
Once you have configured MT4 on your desktop, we can continue to creating our own Expert Advisor algorithm trading robot. Below is an example of a function that will be called on every tick of market data:.
This is a check function to check that the trading context is not currently busy. To enter the editor, just right-click on an existing expert advisor in the left-hand navigator pane and select modify from the menu. This offers the user syntax highlighting and debugging output. You will have to compile your mq4 files into ex4 expert advisors using the MetaEditor if you are editing in an external editor.
In either an uptrend or downtrend, the SMA can behave as a support or resistance , depending on the orientation. As we mentioned before, when the SMA is below the price less than the close price , we consider it a basis for support , and when the SMA is above the price greater than the close price , we consider this a line of resistance. So, in code, we do the following first to create a method for checking the cross-over of inputs for later determining our basis for entry:.
As with all support and resistance, the standard trading methodology works here: So, for our algorithm, we are going to do just that.
When there is a cross in either direction, we are going to apply the appropriate direction of trade and enter the market. As a best practice, the result is stored in the ticket variable and later checked for a positive return value so as to handle any error that may have been reported from the broker's side.
Like the basis for entry except in the inverse case , when the SMA creates a death cross , we can use this signal for closure of our trade, if any trades are open. The logic for this would be written as so:. Here we enter a for loop to iterate over all the open orders, although currently we will only trade one trade at a time—this allows us to expand in the future and have multiple open trades if we feel we need it.
We use AccountFreeMargin and NormalizeDouble to generate this lot size, and if it's calculated at below the minimal lot size of 0.
As the account grows or shrinks! Programmatically, this requires a parameter and a slight change to the code example above to check for that variable rather than the AccountFreeMargin value.
This can be achieved by monitoring the loss of our trade and relation to the open price. If the direction changes and our trade is left out of the money, we can attempt to close out the trade as close to the entry price as possible:.
This is only applied when the current unrealised profit is in a loss. A margin for break-even could be added by simply adding to the OrderOpenPrice method like so:.
Another way to ensure our gains are not lost is to use a trailing stop , which will be discussed in detail in another guide. Here is the full listing for our expert advisor. We have several parameters available at our disposal such as the take profit level, stop loss, and the SMA periods.
Please feel free to play with the parameters to see what is working best for your trading situation and fine tune your algorithm.
The Expert Advisor will then be available inside your MT4 software from the Navigator menu on the left-hand side under the experts section. Make sure you are testing on a demo account. A real account will trade with real money, and although the profits will be real, so will the losses. Whether this will work out in the real world is a whole other question, and is why forward testing is equally important, as is Z score testing. That's a much more advanced topic for machine learning your algorithm, which will not be discussed here, but in later more advanced guides.
The tester pane will open in the bottom of your window. From here, you can select the algorithm to run in the first dropdown menu, so choose the filename of the Expert advisor you have created here.
Next, you can choose the symbol financial instrument. I will be using the minute setting. While writing your script, you can opt for the Open Prices only, as it will rapidly execute your test—although the results won't be worth banking real money on yet!
For this, when you are looking for a real test before going to forward testing, it is recommended to run on Every Tick. This will take a lot longer to process!
These can be accessed via the Strategy tester by clicking the Expert Properties button and viewing the input tab. In the live market, you may find your strategy falls flat on its face due to elements you had not factored in your prior back tests.
Remember the market is always right. A forward test really is the acid test to see if the strategy will be profitable for you to put real money on it.
Let's take the case of Brexit. The British public seemed to believe in the majority that a Brexit vote would be highly unlikely. I was not so optimistic and pulled all my pounds out, saving a lot of my equity in the UK due to the plummeting exchange rate. As for others, I'm afraid to say they were not so lucky. Situations like this are ideal to turn off your trading robot and only trade outside of high market volatility. Coding for this kind of outcome is going to be very hard automatically going on leading or lagging indicators and is better traded after the event or manually.
The chances for false or contradictory signals are always higher during big events, and a manual fundamental approach rather than a technical one may be more profitable. There is nothing wrong with pausing your robot because you are expecting a crisis.
It may save you a loss, whilst on the other hand it may make you miss out on a huge win. We've laid down some of the basics of writing a trading algorithm and introduced many new ideas. In terms of money management, we have gone over the possibility of including break-even conditions and dynamic lot sizing to use one-fifth of the available equity.
Feel free to tweak these parts of the code to your desires for risk. We have gone over the back-testing strategy tester of MT4 and opened the doors for the potential of forward testing and even Z-score testing in the future, all of which are vital before going live.
Now that you have a good foundational expert advisor as a base script, you can start writing your own strategies into the MQL4 language—and testing out if they really work as well as you feel they ought to, or as some trading books and mentors may allude to!
Going forward, you will definitely want to test your algorithm more before committing real money to it. This article is not intended as investment or financial advice—it is intended purely as a technical tutorial for software creation and research.
Create an Algorithm Trading Robot: Below is an example of a function that will be called on every tick of market data: So, in code, we do the following first to create a method for checking the cross-over of inputs for later determining our basis for entry: Basis for Exit Like the basis for entry except in the inverse case , when the SMA creates a death cross , we can use this signal for closure of our trade, if any trades are open. The logic for this would be written as so: If the direction changes and our trade is left out of the money, we can attempt to close out the trade as close to the entry price as possible: The Whole Script Here is the full listing for our expert advisor.
Where to Place the Expert Files? Conclusions We've laid down some of the basics of writing a trading algorithm and introduced many new ideas.
Feed Like Follow Follow Weekly email summary. Download Attachment View on GitHub. Looking for something to help kick start your next project? Envato Market has a range of items for sale to help get you started. Get access to over , creative assets on Envato Elements.
Over 9 Million Digital Assets. Everything you need for your next creative project. Choose from 2, professionals ready to do the work for you.More...