Let's continue our look at programming Expert Advisors in the MetaTrader platform. At this point, you should know the basics of MetaTrader and how create an apply an Expert Advisor. If you need a refresher, see my prior post MQL Programming Part 1.
Now open up MetaTrader and create a new EA called welcome.mq4 and save it in the Experts folder under your MetaTrader install folder. Then exit MT4, and restart it and you should see your new Expert Advisor called Welcome on the left side under the Expert Advisors folder.
Now open up the Welcome.mq4 folder and add these 2 new variables in the header section before the init() function:
// Total bars on the chart
int nTotalBars;
// Number of bars to look back
int nLookBack = 5;
Now complete the Init() function as follows:
int init()
{
datetime dNow;
string sDate;
string sTime;
dNow = TimeCurrent();
sDate = TimeToStr(dNow, TIME_DATE);
sTime = TimeToStr(dNow, TIME_MINUTES);
Print("Initializing Welcome EA");
Print("Server time: ", sDate, " ", sTime);
// Grab total bars
nTotalBars = Bars;
Print("Point: ", Point);
Print("Digits: ", Digits);
return(0);
}
In the Init() function, we grab the server time using the TimeCurrent() function and use TimeToStr() to convert it to its date and time components and print them out. The print output appears on the "Experts" tab and are a convenient way to interact with the user.
We also grab the values of the Bars pre-defined variable which return the total number of bars on the current chart. We also print out the value of Point variable which shows the point size of the current pair. With FXDD and the EUR/USD pair, the Point equals 0.0001. and Digits equals 4.
With that behind us, we know all the real action takes place in the start() function
which gets called each time a new tick arrives at the terminal. Let's take a look at now to access price data from inside the Start() function.
Pre-defined variables Bid and Ask return the current market prices for the pair.
Pre-defined variables Time High, Low, Close and Volume return the values of the bars on the chart. Each variable is really an array, and the 0th array value (High[0] for example) shows the High for the current price bar currently being formed. High[1] refers next oldest bar. Close[10] would return the closing bar value 10-bars back from the current bar.
With that, let's code a Start function that prints a message to the Experts tab each time the pair makes a new n-bar high. For the purposes of this example, let's use 5 for the bars to look back.
Now let's code the start() function as follows:
int start()
{
// Use to index into price array
int i = 0;
bool bNewHiLo = false;
// Zero's bar is the bar current in the making
double dAvgPrice0 = (High[0] + Low[0]) / 2.0;
Print("Avg/High[0]/Low[0]", dAvgPrice0, ",", High[0], ",", Low[0]);
double dAvgPriceN;
double dAvgPriceHi = 0.0;
double dAvgPriceLo = 999999999.0;
// Calculate N bar high and low for this bar
for (i=nLookBack; i>0; i--)
{
// Calculate average price for this bar
dAvgPriceN = (High[i] + Low[i]) / 2.0;
// Save new high and lo
if (dAvgPriceN < davgpricelo =" dAvgPriceN;"> dAvgPriceHi) dAvgPriceHi = dAvgPriceN;
}
if (dAvgPrice0 > dAvgPriceHi) {
Print("New ", nLookBack, " bar high at: ", dAvgPrice0);
bNewHiLo = true;
}
if (dAvgPrice0 <>
Print("New ", nLookBack, " bar low at: ", dAvgPrice0);
bNewHiLo = true;
}
if (bNewHiLo == false) {
Print("No signal ", nLookBack, "-Bar Hi/Lo/Current: ", dAvgPriceHi, ",",dAvgPriceLo, ",",dAvgPrice0);
}
return(0);
}
There's a lot going on here, so let's go through it one line at a time. At the top of the start() function, we calculate the average price for the 0th bar - the bar currently in the making. I decided to go with average price for the bar so I don't give any additional credit to the opening or closing price for the bar.
Next, I declare variables dAvgPriceHi and dAvgPriceLo to hold the high and low prices for a given lookback. I initialize dAvgPriceHi to 0.0 and dAvgPriceLo to a high value so that first real price that comes along will get saved as the high or the low.
After that, the for loop is used to step through the price bars starting with 5 bars back and stepping forward until we reach bar 1. I calculate the average price for each bar and compare it with the previously saved high or low. When that loop finishes, dAvgPriceHi has the highest average price for that 5 bars and dAvgPriceLo as the lowest average price for that 5 bars.
Finally, I see if the average price for the currently forming bar (bar 0) is higher than the highest high (or lower than the lowest low) across the lookback period. If so, I print an alert out to the Results tab.
You can probably see where I'm going here. I'm working toward an expert that buys on breakouts of a n-bar high or sells on breakdowns from the n-bar low. I can make the value of N a variable and use the back-testing and optimization feature of Meta-trader to find good values of N for a given tradeable and bar pair.
Now compile the EA and fix any syntax issues. Now drag the EA onto a 1 minute chart of EUR/USD and watch it go to work.
That will form the basis of my first EA which is based on Donchian channels.
Finally, I realize there are limits to including the code itself in the blog. I'll figure out a place where I can publicly post the EA code as its developed and just highlight the interesting parts in the blog.
Hey Ya'll,
ReplyDeleteI've included a list of the most recommended forex brokers:
1. Best Forex Broker
2. eToro - $50 min. deposit.
Here is a list of the best forex instruments:
1. ForexTrendy - Recommended Odds Software.
2. EA Builder - Custom Indicators Autotrading.
3. Fast FX Profit - Secret Forex Strategy.
Hopefully these lists are benificial to you.