olegas Mar 14, 2015 / 544 Views
Below is the process of creating a simple trading robot to work in the MetaTrader4 terminal.
Using this simple example, you can try to create your own trading robots for partial or complete automation of trading on the Forex market.
To create a trading robot we will use the MQL4
. In fact, everything is not so scary and even a child can do it. Of course, you will have to make some efforts to learn the basics of the programming language, but the result in the end is worth the effort.
Template of the created trading robot
A template is where the creation of any trading robot or advisor begins. The templates may differ slightly from each other, but I offer you a simple working option:
#property copyright ""
#property link ""
//This place in the program code describes all the variables used in the program
int start() // Special. start function
{
// At this point the algorithm of actions of the trading robot is written (using //special commands of the MQL4 language)
return; // Exit start()
}
How to install and connect
From the technical side, everything is simple.
Step 1: Open the root data folder.
After launching the trading terminal, click “File” in the top navigation menu. After that, open the desired folder from the drop-down menu.
You will be redirected to your MT4 data folder where you can install the advisor.
Step 2: Place the advisor in a folder.
In the folder that opens, double-click on the “MQL4” icon.
Here, select the Experts folder. This is where we need to put our code.
Step 3: Paste the bot files into the Experts folder.
In this example, the Bollinger Expert Advisor from Forex Robot Academy is used.
Finally, restart your MT4 terminal to ensure the EA is available for use.
After that, adjust the settings using standard MT4 methods, place it on the chart and you can start testing.
Algorithm of trading robot actions
We incorporate our own trading system into the algorithm of actions of the trading robot being created. Trading robots can have complex, branched action algorithms that take into account many factors and ways of developing events in the Forex market. In this case, we will limit ourselves to a simple algorithm based on buying at a price above the moving average and selling at a price below the moving average.
A moving average is a technical analysis concept that expresses some average price value, graphically represented as a line on a chart. See picture:
Click on the picture to enlarge |
So, we want the trading robot we are creating to make a purchase at a price above the moving average. To do this, we will write the following program code:
if( Bid>iMA (Symbol(), Period(),PMA, 0,MODE_SMA , PRICE_CLOSE, 0) )
{ OrderSend(Symbol(),OP_BUY,0.1,Ask,3,Bid-sl*Point,Bid+tp*Point); }
Let's take a closer look at this code. First, the condition is checked that the price is above the moving average:
if( Bid>iMA (Symbol(), Period(),PMA, 0,MODE_SMA , PRICE_CLOSE, 0) )
Here:
Bid
– demand price*;
iMA()
– an operator that calculates the value of the moving average (in this case, a simple moving average is used with a period specified in the settings of the trading robot);
If (condition)
–
if
translated from English means “if”.
In other words, if the condition written in brackets is met, then the action specified in curly brackets after is executed: { OrderSend(Symbol(),OP_BUY,0.1,Ask,3,Bid-sl*Point,Bid+tp*Point);
} OrderSend(Symbol(),OP_BUY,0.1,Ask,3,Bid—sl*Point, Bid+tp*Point)
— this is an order to buy 0.1 lot with the installation of stop loss (sl) and take profit (tp) orders specified in the settings of the trading robot.
In order for the created trading robot to sell at a price below the moving average, we will write the following program code:
if( Bid
{ OrderSend(Symbol(),OP_SELL,0.1,Bid,3,Ask+sl*Point,Ask-tp*Point); }
The construction is similar to the previous one, differing only in that in the if()
the price is less than the moving average, and in curly brackets there is an order to sell the same 0.1 lot, with the same stop loss and take profit orders.
Thus, at the moment we have the following algorithm of actions:
if( Bid>iMA (Symbol(), Period(),PMA, 0,MODE_SMA , PRICE_CLOSE, 0) )
{ OrderSend(Symbol(),OP_BUY,0.1,Ask,3,Bid-sl*Point,Bid+tp*Point);}
if( Bid
{ OrderSend(Symbol(),OP_SELL,0.1,Bid,3,Ask+sl*Point,Ask-tp*Point);}
This means that every time the price changes, the program will check both of these conditions and make a purchase or sale depending on which of the conditions is true at a given time.
And if we do not limit the program with an additional condition, then it will immediately open a bunch of positions, having exhausted the entire deposit.
Let's set it an additional condition, to open a position only if there are no open positions: if( OrdersTotal()=0)
, here
OrdersTotal()
is a function that returns the value of open and pending orders.
Moreover, let's make sure that the trading robot first checks for the presence of open positions, and then, if there are no open positions, performs further actions according to the algorithm:
if(OrdersTotal()=0)
{
if( Bid>iMA (Symbol(), Period(),PMA, 0,MODE_SMA , PRICE_CLOSE, 0) )
{ OrderSend(Symbol(),OP_BUY,0.1,Ask,3,Bid-sl*Point,Bid+tp*Point);}
if( Bid
{ OrderSend(Symbol(),OP_SELL,0.1,Bid,3,Ask+sl*Point,Ask-tp*Point);}
}
As you can see, we placed the entire algorithm with condition checking in curly braces under the condition if( OrdersTotal()=0)
and if this condition is not met, the trading robot will simply wait for the next tick (price change).
This completes the simplest trading robot algorithm, but such a program will not work until we describe all the variables included in the algorithm.
MQL5 Wizard. Make an advisor in 5 minutes
So, first, launch MetaTrader 5 and go to the application editor (F4 button). On the top menu, click the “Create” button and in the dialog that appears, select the generation of a new advisor.
Next you need to specify the name of the advisor and the main input parameters.
Adding trading signal modules. Modules can be either standard or developed by the community (you can also participate in this process).
Actually, all standard signals are well described in the online help on the official website. You can also download custom ones there.
Having selected a suitable indicator, you need to specify its input parameters. Here you can indicate the weight of the signal in relation to others, if there are many of them.
Regular trailing stop or closing a trade based on indicator values is your choice.
You can also choose from a fixed lot or the transaction volume as a percentage of the deposit. For the most risky new programmers, there is also the Martingale with its geometric progression of the lot, which can bring you millions in a couple of extra passes in the strategy tester.
Actually, even if you are not a member of the MetaTrader clan, it’s okay, a constructor has probably already been written for the trading platform you need. Again, it’s a matter of opportunity and desire. The moral is simple: don’t try to implement something that has already been implemented a long time ago . Ignoring the work of others can be costly; reinventing science is not at all necessary.
Let's move on to the training plan.
Python will be used as the programming language to implement the strategies. This language is cross-platform (which is a mandatory attribute for supporters of Linux and macOS), easy to learn (from my experience of learning Java, I can say that Python is easier), widespread (used in Big Data, web development, test automation, science, systems administration, for prototyping quantum models in hedge funds and “quantum” trading units in banks, etc.)
What are the disadvantages of a cryptocurrency trading bot?
Earning millions just from advisors only seems real. Often these slogans are used by scammers who sell dummies that, at best, will not bring any benefit. Trading robots also have a lot of disadvantages, and let’s list them.
- Advisors should not be used during times of market instability. Any unexpected news can radically change the direction of the price. The robot won’t even know about it, so it will make unprofitable deals. Therefore, at a minimum, you will have to keep an eye on the program.
- Assistant programs use only technical analysis, which is based on effects, not causes.
- The program has no emotions. Yes, this is not a mistake. The lack of emotions in a trading robot is also a disadvantage. If something doesn’t go according to plan, a person will get scared and close the deal, but a robot won’t be able to do that. Of course, unless it has a loss control mechanism, which most advisors do not have.
The ideal way to solve these problems is to enable the advisor in semi-automatic mode. That is, the robot will only give signals, and the trader himself decides whether to listen to this advice. But then some of the advantages simply disappear. In general, a competent trader knows how to deftly balance between the pros and cons of advisors.
Example 1
The graph shows the dependence of the profit (P) of our trading robot trading EURUSD, obtained on the annual segment of the history of hourly price measurements, on the value of the parameter - the period of the “slow” moving average (M). All other parameters are fixed and are not optimized.
The CF (profit) reaches a maximum of 0.27 at point M = 12. To be sure to find the maximum profit value, we will need to conduct 20 iterations of testing. An alternative is to conduct a smaller number of tests of the trading robot with a randomly selected value of the parameter M on the interval [9, 20]. For example, after 5 iterations (20% of the total number of tests, we found a quasi-optimal vector (obviously one-dimensional vector) of parameters: M = 18 with a CF value (M) equal to 0.18:
The remaining values on the graph were hidden from our optimization algorithm by the “fog of war”.
Optimizing one of the four parameters of our trading robot, with fixed values of the other parameters, does not allow us to see the whole picture. Perhaps the maximum CF of 0.27 is not the best value of the indicator if the values of other parameters are varied?
This is how the dependence of profit on the period of the moving average changes for different values of the TakeProfit parameter in the interval [0.2... 0.8].
The amount of permissible monthly drawdown on the deposit
If the deposit reaches drawdown specified in the deposit parameters, all open transactions will be closed and the robot will stop working until the next calendar month according to terminal time. In this case, the drawdown is calculated as the difference between the deposit amount at the beginning of the current month and the current Equity level. When calculating this value, the robot will take into account absolutely all trading operations on a given trading account, i.e. “manual” and “automated” trading will not be distinguishable.
This measure is aimed at preserving the trading deposit and the possibility of continuing work according to the current (or changed) system.