NavigationUser loginWho's new
Who's onlineThere are currently 0 users and 60 guests online.
|
Lesson 13 - Your First Expert Advisor (Part 1)In the previous lesson we created our first indicator. Although this indicator wasn’t useful for us as trader, but it was very useful for us as programmers. The indicators –in general- are very important for the technical analysis of the market in trying to predict the future prices. But with the indicators we observe the chart then use our hands to sell, buy and modify our orders manually. You have to set in front of your terminal, and keep your eyes widely open. If you get tired, want to drink a cup of tea or even take a short vacation. You have to consider one of these solutions: You may rent someone to observe the terminal for you and calling your mobile phone every five minutes to tell you what’s going on. If this employee is an expert, he will cost you the pips you earn. And if he is novice one, he will cost you your capital. The second solution is using a program to automate your trades. That’s what the Expert Advisor is for. The Expert advisor is a program wrote in MQL4 (we are studying MQL4 huh?) uses your favorite indicators and trade methods to automate your orders. It can buy, sell and modify the orders for you. It enables you to drink a cup of tea and save the salary you gave out to your employee or the bunch of flowers you bring to your assistant wife. Today we are going to create our first expert advisor so let’s go. First two steps: Step1: If you didn’t open your MetaEditor yet, I think it’s the time to run it. From the MetaEditor File menu click New (you can use CTRL+N hotkey or click the New icon in the standard toolbar). That will pop up the new program wizard which you have seen when you created your first indicator (Figure 1). This time we will choose the first option “Expert Advisor program” then click Next button. Figure 1 – the first step wizard Step2: When you clicked Next, you have got the general properties wizard (Figure 2). This wizard enables you to set the properties of your expert advisor and to set the external variables you will use in your expert advisor. In this step you can set these properties: 1- Name of your expert advisor, in our sample we will use My_First_EA. 2- Author name of the program, type your name (I typed mine in the sample). 3- Link to your web site. 4- External variables list: This is the list of the external variables you allow the user of your expert advisor to change them from the Expert properties window. To add a new variable you click the Add button, clicking it will add a new record to the external variables list. Every record has three fields: Name: double click this field to set the name (identifier) of the variable. Type: double click this field to set the data type of the variable. Initial value: double click this field to give your variable initialization value. This field is optional which means you can leave it without setting In our sample we have added three variables: Varaible _ Type _ initial value --------------------------------------- TakeProfit _ double _ 350 Lots _ double _ 0.1 TrailingStop _ double _ 35 Figure 2 – the second step wizard Now click the Finish button to close the wizard, and MetaEditor will bring to you the code created by the wizard and saves the file My_First_EA.mq4 in the MetaTrader 4 \experts path. Note: you have to put the expert advisors in MetaTrader 4\experts path and the indicators in MetaTrader 4\experts\indicators path, otherwise they will not work. This is the code we have got from the wizard: //+------------------------------------------------------------------+ //| My_First_EA.mq4 | //| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- //---- return(0); } //+------------------------------------------------------------------+ As you see above, the code generated by the wizard is a template for you to add your code without bothering you by typing the main functions from scratch. Now let’s add our own code: //+------------------------------------------------------------------+ //| My_First_EA.mq4 | //| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- //---- return(0); } int Crossed (double line1 , double line2) { static int last_direction = 0; static int current_dirction = 0; if(line1>line2)current_dirction = 1; //up if(line1<line2)current_dirction = 2; //down if(current_dirction != last_direction) //changed { last_direction = current_dirction; return (last_direction); } else { return (0); } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---- int cnt, ticket, total; double shortEma, longEma; if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit } shortEma = iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0); longEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0); int isCrossed = Crossed (shortEma,longEma); total = OrdersTotal(); if(total < 1) { if(isCrossed == 1) { ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point, "My EA",12345,0,Green); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice()); } else Print("Error opening BUY order : ",GetLastError()); return(0); } if(isCrossed == 2) { ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0, Bid-TakeProfit*Point,"My EA",12345,0,Red); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice()); } else Print("Error opening SELL order : ",GetLastError()); return(0); } return(0); } for(cnt=0;cnt<total;cnt++) { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(isCrossed == 2) { OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),OrderOpenPrice(),Bid- Point*TrailingStop,OrderTakeProfit(),0,Green); return(0); } } } } else // go to short position { // should it be closed? if(isCrossed == 1) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop, OrderTakeProfit(),0,Red); return(0); } } } } } } return(0); } //+------------------------------------------------------------------+ Note: don’t copy and paste the code above because it warped and will not work for you, use the code provided with lesson in www.forex-tsd.com . Scared? Don’t be scared of the 160 lines you have seen above, we will know everything about this code line by line, I promise it’s an easy task. Test the Expert Advisor: Before studying our expert advisor code we have to be check is it profitable one or not. Note: Our expert advisor will work with EURUSD pairs in 4 Hours timeframe. So compile the expert advisor by pressing F5 and load it in MetaTrader. You can test your expert advisor using two methods: 1- Live trading In live trading testing the results are more accurate but you have to spend days (and maybe months) to know is the expert advisor profitable or not. You have to enable the expert advisor to automate your trades. To enable it click Tools _ Option menu (or use CTRL+O hotkey), that’s will bring the Options windows (figure 3), click Expert Advisors tab and enable these options: Enable Expert Advisors Allow live trading And click Ok button Figure 3 – Enabling expert advisor auto trade You will see the Smile symbol beside the expert advisor name which means your expert advisor is working and ready to trade for you (Figure 4). Figure 4 – Expert advisor is enabled 2- Strategy Tester: The second method of testing your expert advisor which is less accurate but will not take time is the Strategy tester. We will know everything about Strategy tester later, let’s now bring its window by pressing F6 (Figure 5). When you get the window enter these options: Symbol: EURUSD. Period: H4 (4 Hours). Model: Open price only. Figure 5 – Strategy tester window Now click Start button to start testing the expert advisor. You will see a progress bar and the two tabs (Settings and Journal) became five tabs. We interested in Report tab (Figure 6); click it to see your profit. We have a lot to say and to do in the next lesson; I hope you are ready for the challenge. I welcome very much the questions and the suggestions._ See you Coders’ Guru |