Saturday, January 30, 2010

Weekly Update - More on the 'Droid

Welcome back fans of the Forex.

I'm coming to you today from lovely Skytop, PA in the heart of the Pennsylvania Poconos.

Here's a quick update on this week's action. My favorite robot - Forex Megadroid - did nothing nearly the entire week and finally sprung into action on Thursday evening at about 5PM EST. It pulled in 16 pips in 2 trades which was just over 1% of the account. This is consistent with my new "1 percent a week" mantra, and i'm perfectly happy with that.

The "God's Gift" robots from Daniel Fernandez swung between narrow gains and losses for the week and are both down marginally for the year. According to Daniel, this is perfectly normal behavior and the robots can have flat to downish performance for months on end, then suddenly make 70% of the account in equity in a single winning trade. This is a characteristic of trend following systems - they loose on the majority of trades, but make it all back on a single big winner. This makes the God's Gift robots much harder to trade psychologically.

We humans need regular encouragement, and that's why the 'Droid is much easier to trade, since it has about a 95% win rate. But with a handful of trades a week at best, it takes patience.

The other robot i'm following is a free evaluation from Forex PipZen that anyone can download and trial for free at This robot so far has 2 winners, although they relatively small. I've been running about 2 weeks now, and its up just under 1%. At $149 per year, I don't like it as much as the 'Droid. Many thanks to my good buddy Redford for the tip on this one.

So let's dip a bit deeper into the Megadroid to get some insight into how it works.

First of all, it trades only the EUR/USD pair on a one-hour timeframe. Once you get it loaded up in the right timeframe, the manual says that you can change the timeframe on the chart with no harm done. It very often gets in and out of trades in under an hour's time, so its pretty clear the analysis its doing has minimal relationship to the chart timeframe.

One of the most interesting things about the 'Droid is that it trades only Monday through Thursday in a 2 hour window - from about 5PM to about 7PM EST. Taking a look at the graphic below (courtesy of, this corresponds to the least busy time of the Forex trading day. At this point, New York, London and Toyko are in off-hours mode and the only active market is Sydney.

That's interesting since the web site where I got the graphic advises the exact opposite! The page advises to avoid trading unless the market is active, and all the big boys are at the trading desk.

Megadroid take the opposite tact and only trades when the big boys are away.

I'm not sure what to make of this other than the fact that this the time slice of the day where markets are least subject to manipulation. It seems a bit counter-intuitive - you would think that the markets are more likely to be manipulated at lower volume times. But according to the logic of the 'Droid, its the other way around. When all the daylight traders are away from the desk, that's when markets are most likely to follow their natural up and down rhythms.

One reassuring thing about the 'Droid is that I can go to sleep Sunday evening and not wake up to a loss Monday morning (as so often happened with Zulu). Also, I can go into Friday and not have to worry about being blown up by the Non-Farm Payroll report which comes out at 8:30 AM EST and is the 800-pound gorilla of news releases in the forex market.

I suppose there are some other good reasons for trading in the 5-7PM EST timeframe (lack of news releases affecting EUR/USD?) but I suppose the point has been made.

I've a few more interesting observations about the 'Driod, but i'll save those for next time. Good luck and good trading,


Friday, January 22, 2010

Megadroid Backtesting - 1% a week

Welcome back Forex Fans. Hope everyone had a great week of trading and is ready for the weekend.

To your left please find back-test results for the Forex Megadroid for the past 10 years tested one year at a time. I tested with a $1000 account resetting back to $1000 at the start of each year. I don't think the account size matters much since the EA calculates bet size based on the size of the account and a risk setting.

For my tests, I used a 0.1 risk setting which risks about 10% of the account value on each trade. That doesn't mean that it will loose 10% on a trade, but that's that starting size for each trade. 10% is a relatively conservative setting. I believe I read on a prior version of the site that they used a 0.3 risk setting to produce the outrageous returns shown on the web site.

So do I believe the historical returns are really possible? Looking at a few of the years, 2000 and 2001 to be specific, its hard to believe this robot is going to return 500% in one year. I don't think MetaTrader was even in existence at that time, and its possible the EA has been optimized to show good back testing results. We know from our earlier coding exercises that the EA knows is in demo mode and its very possible that the results prior to 2005 are just a sham.

So what do I think is a reasonable return? We'll, I've come upon a figure of 1% per week. My forward testing with Megadroid appears that this is possible and some other commercial EA's might also be up to the challenge. So is 1% a week a big deal and should we be excited about that type of return?

Well I put a spreadsheet together and did some compounding. Starting with a $1000 initial investment, over 10 years trading 50 weeks a year, that comes to $144,000. Not bad, but not much of a nest-egg for retirement. If we change that initial investment to $10,000, than it grows to $1,447,728 at the end of 10 years. Now we are talking about some serious dollars and enough to act as the anchor for a nice retirement fund.

Now let's ask ourselves, are these returns really possible? There are whole bunch of reasons why things may not work out this way. Some I can think of:

  • The EA stops working as is has historically because the FCM's figure out how to defeat it
  • The Forex market is somehow legislated out of existence. The NFA is making some moves in this direction such as reducing leverage to 10% forcing US-based clients to move their accounts to the UK.
  • Taxes. If we reduce the yearly take by 30% to cover the capital-gains tax, our $1.4 million is reduced to only $56,000. How's that for depressing? I don't have a solution for that other than to run the process in a Tax-deferred account such as an IRA. I don't think that's possible with a forex account. Let me know if you guys are aware of such an arrangement.

So the taxes are a real drag and kill the compounding potential. Even so, I think 1% a week is a pretty darn good return, about 60% for year with compounding. This beats any other type of investment I'm aware of, but given the drawdown potential (as high as 50%), you can't throw too much money at it and still be able to handle the drawdown.

That's enough for now. I'm looking for some good EA ideas to start coding and I have some leads. Let me know if you have any good ideas and want me to code them.

Thanks and enjoy your weekend,


Monday, January 18, 2010

MetaTrader - Donchian EA

Welcome back Forex Fans.

In this post, let's take a quick look at trading functions and then my first fully-functioning Expert Advisor.

Trading functions are described in the MQL programming book here at Trading Functions. New orders are opened using the OrderSend() function. Here's a typical function call:

iTicket = OrderSend(Symbol(), OP_BUY, dLots, NormalizeDouble(Ask,Digits), Slippage, dStopLossPrice, dTakeProfitPrice, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);

A few key points here:

  • Don't trade a fixed lot size, calculate lots ahead of time using the money management algorithm described in my previous post here MetaTrader Account and Position Sizing
  • For market orders, buy and the Ask and sell at the Bid using the built-in keywords.
  • Round the price to the correct number of digits by calling the NormalizeDouble() function with the Ask (or Bid) and Digits built-in keywords. Otherwise, you will get OrderSend 4107 error.
  • Specify the StopLoss and TakeProfits prices if you have them or set them to zero to exit on the reverse of our entry condition.
  • Once your order is submitted, you can review each of the open orders with a loop structure which is too much trouble to include here, but can be found in my first EA described below.
Let's move on to our first full-functioning EA called Donchian. This EA is named after Richard Donchian who popularized a simple method of trend-following that takes a position when a bar closes above the highest high or lowest low for a given lookback period.

You can find the complete code for the Donchian EA on my new Yahoo group You will also find the code for each of the learning EA's i've created so far as part of the blog. To get access to the Yahoo group, you can leave me your e-mail address as a comment, or send your e-mail address to me via direct message using Twitter at: I'll invite you to the group and you can download the EA's and upload your own.

So how does the EA perform? I tested it with a 6-bar lookback against an hourly chart of EUR/USD. The good news is that the system never fails to catch a big trend. The bad news is that it gets chopped up on sideways or ranging markets, which the markets do most of the time. So its clearly not a profitable EA, but a good learning exercise.

So what I have learned from this exercise?
  • Don't try to write your own EA from scratch, use someone else's as a model and modify it
  • Parameters add a lot of complexity to EA testing, and the ideal EA should have as few parameters as possbile.

  • My sample EA has parameters for Lookback (# of bars breakout), Risk, Slippage, and Boolean for TakeProfit, StopLoss and Trailing Stop modes as well as values for those items
  • I added those parameters so I can use this EA as a model and move forward to test other ideas.

Overall, finding a profitable EA isn't going to be easy, but i'm off the ground now as an EA coder a ready to start testing some ideas. Leave me a comment if you have any ideas and i'll code it and review the results here.

Thanks for reading and drop me a line if you want access to the Yahoo group.


Tuesday, January 12, 2010

MetaTrader - Driven2Success

Welcome back Forex fans.

With all the hype and misinformation out there about Forex robots, don't you wish somebody would just buy all the robots, test them independently and publish the results? Well, someone has and you can get the results for free at

You have to submit your name and e-mail address to be allowed access to the site. But that's a small price (no price really) to pay to see the real-live behavior of all the leading robots tested on demo accounts over an extended period of time.

Once you get the URL, you will receive daily e-mails with overnight results and updates on the robots being tested. I find this helpful and its let's you know whose making and loosing money on almost a daily basis.

How does this guy make any money? He acts an affiliate seller for these robots. So if you click on the link to a robot website, the URL has a special code that allows the publisher of this site to make a bit of the sales revenue. I don't know how much money he can make with that approach, but either way its a great service! Check it out!

I'm working on building up an EA for my next post, but its slow going due some commitments. So take a look the site above, your more likely to make money with those robots than anything I'm writing here anyway. Enjoy.

Friday, January 8, 2010

MetaTrader - Account and Position Sizing

Welcome back, Forex fans.

Let's talk about account and position sizing.

We all know that Forex is risky and we stand a higher-than-normal chance of blowing up an account versus most other types of investments.

From a personal perspective, I want to keep my forex exposure to less than 5% of my entire portfolio. So assuming I have a 100K portfolio, I'm looking allocating no more than $5000 to Forex. For testing purposes, i'm planning a $1000 account size for any given trading strategy. This way if the account goes into 50% drawdown, I've lost only one half of 1% of my entire portfolio. Besides, we can always increase the account size if things work out.

Once I have the account setup and Expert selected, how much do I allocate to each trade?

The great thing about MetaTrader accounts (that I didn't have with FXCM) is the ability to trade in fractions of a lot. With FXCM, if I had a 10K account, I could only trade in 10K lots. With a 100K account, I could only trade in 100K lots. No so with MetaTrader where I can trade all the way down to 0.01 lots. So for a $1000 account, I can trade 0.01 of the full 100K size which is $1000 worth of currency. Or I can trade 0.10 of the full 100K which is 10,000 worth of currency. So this means I can be much more granular in term of how much I want allocate to each position.

With my forex account at only 5% of my total portfolio, I can safely allocate between 5% and 10% of my account to each position. Any more than that and we stand the risk of blowing our account up with just a few loosing trades. Any less than that, and we aren't getting the most of the account as is possible. It doesn't mean I need to risk the entire 5% on each trade, but its a starting point.

Ideally, we also want to lower our bet size as the account shrinks and increase it as the account grows to take advantage of compounding.

In the original Turtle Trader Rules Richard Dennis and William Ekhard calculate their exposure to each position based on the dollar volatility of the contract as measure by the ATR or Average True Range. They also calculated their stops as a percentage of account equity based on the ATR.

So each position size is a function of account size, volatility of the pair and amount we want to risk. Let's paste the following code into the Start() function of the EA called AccountStuff that we created in the last post:

int start()
double dContractSize = 100000.0;
double dRisk = 0.05;
double dATR = iATR(Symbol(), 1440, 14, 0);

Print("ATR is: ", dATR);
if (dATR > 0.1) dATR = dATR / 100.0;

// Calculate how much contract value represented by one ATR
double dUnits = dContractSize * dATR;

// Calculate how much account we want to risk
double dAccountPct = AccountBalance() * dRisk;

// Calcuate lots
double dLots = dAccountPct / dUnits;

// Normalize double
dNormalLots = NormalizeDouble(dLots,2);
Print("Units is: ", dUnits);
Print("AccountPct: ", dAccountPct);
Print("Lots: ", dNormalLots);


This code starts by setting some constants for risk and contract size. Then it calculates the Average True Range for the pair 14 days. The 1440 parameter means daily and the period is 14. For more information, see Meta Trader development course.

Next the code calculates the value change in the contract for one movement of ATR into the variable dUnits. Then it calculates the amount of the account that represents 5% into dAccountPct. Finally we divide the amount to risk (dAccountPct) by one ATR if contract value (dUnits) to and round to 2 decimal places to come up with the number of lots.

Now save and compile that code and fix any syntax errors. Then drag the EA onto various currency pairs and examine the output on the Experts tab. For EUR/USD and a $1000 account, the lots come to 0.03 representing about 3K worth of currency per position.

If you get a divide by 0 error, then you probably don't have enough history to calculate the ATR. Select Tools, History center and add more data for the tradable and timeframe.

Now assume you have a good year with your EA and your account grows to 1,600. Now replace the AccountBalance() function about with a constant of 1600.0 and you'll see the lots now calculate to 0.06. Now change account balance to 10000.0 and the lots will re-calculate to 0.38. There you have it, automatic lot size adjusted for account size and underlying volatility of the pair!

Daniel Hernandez takes it one step further and calculates stop loss and take profit values based on ATR in a similar way. Take a look at his e-book for details. We'll take a look at exit and take profit strategies when we get to talking about specific EA's.

That's all for now, enjoy your weekend.

Thursday, January 7, 2010

MetaTrader - Account Functions

Welcome back, fans of Automated Forex trading.

In this post, let's take a look at account related functions in MetaTrader programming. Take a look Account Functions and scroll down to Functions Accessing to the Information about the Active Account.

Go ahead and fire up MetaTrader. Right-click on Expert Advisors and select New. Go through the wizard and create a new Expert Advisor called AccountStuff. Go ahead and paste the following code into the Init() function:

int init()
Print("Account Balance: ", AccountBalance());
Print("Account Credit ", AccountCredit());
Print("Account Currency: ", AccountCurrency());
Print("Account Equity: ", AccountEquity());
Print("AccountFreeMargin: ", AccountFreeMarginCheck());
Print("AccountFreeMarginMode: ", AccountFreeMarginMode());
Print("AccountLeverage: ", AccountLeverage());
Print("AccountMargin: ", AccountMargin());
Print("AccountName: ", AccountName());
Print("AccountNumber: ", AccountName());
Print("AccountProfit: ", AccountProfit());
Print("AccountServer: ", AccountServer());
Print("AccountStopoutLevel: ", AccountStopoutLevel());
Print("AccountStopoutMode: ", AccountStopoutMode());


Most of these functions are pretty self explanatory, so I'm not going to go through all of them here. You can step through them one at a time by clicking AccountBalance() then click on the next function name to scroll ahead.

One interesting distinction is between AccountBalance() which returns the amount of actual cash in the account. AccountEquity() returns the cash value of the account plus or minus any gains or losses from open positions and is the value to watch in terms of whether you are up or down. AccountMargin() returns the Account value remaining in the account which can be used to add new positions.

So what does the account balance have to do with trading? A lot as it turns out and since money management is one of the most important factors in all trading and can make the difference between success and failure.

I was hoping to include the code for position sizing in this post, but I ran out of time. Please check back over the weekend for that.

Thanks for reading and come back soon.

Tuesday, January 5, 2010

MetaTrader - MQL4 programming - Terminal functions

Welcome back fans of automated forex trading.

In this post, let's take a look at the terminal status functions found in the MQL4 programming language described here Terminal Functions.

These functions don't have much to do with trading, but they let you know the status of the Terminal which is important for a few reasons.

While it seems like we are pretty far from making any money here, we are deepening our understanding of the terminal and how it works on the inside which will benefit us later.

Anyway, open up MetaTrader and create a new Expert Advisor called Terminal. Paste the following code into the Init() function:

int init()
Print("Terminal Info follows");
Print("Company: ", TerminalCompany());
Print("Name: ", TerminalName());
Print("Path: ", TerminalPath());

/* Terminal info */
Print("Terminal Status follows");
if (IsDemo()) {
Print("Status: Demo Account");
} else {
Print("Status: Live Account"); }

/* Terminal info */
if (IsConnected()) {
Print("Connection Status: Connected");
} else {
Print("Connection Status: Not Connected");

Print("Details of Terminal Config follow");
Print("IsDllsAllowed: ", IsDllsAllowed());
Print("IsExpertEnabled: ", IsExpertEnabled());
Print("IsLibrariesAllowed:", IsLibrariesAllowed());

Print("Testing Status follows");
Print("IsOptimization: ", IsOptimization());
Print("IsStopped: ", IsStopped());
Print("IsTesting: ", IsTesting());
Print("IsTradeAllowed: ", IsTradeAllowed());
Print("IsTradeContextBusy:", IsTradeContextBusy());
Print("IsVisualMode: ", IsVisualMode());

Now compile the EA and correct any syntax errors.

Now exit the MetaEditor and drag the new EA onto a chart. The print output will appear under the Experts tab. You can also play around with the 'Allow Live Trading' and 'Allow DLL Imports' check boxes and see their affect on the output.

Now remove the EA from the live chart and open up the Strategy Tester window. Now run a test with your new expert over a short time period. The print output will appear under the Journal tab when testing.

Key take aways here are:

  • An expert can be active on a chart without live trading being enabled
  • An expert can tell whether its being run in demo mode or against a live account. This allows developers of commercial EA's to allow unlimited testing on a demo account, but require some type of user authentication on a live account.
  • An expert can be programmed to behave differently when being tested!
This last one is pretty important because it shows that back-testing is not substitute for live, forward testing on a demo account.

2 other tidbits I picked up about the back-tester that are key:

1) The back tester does not test on tick data. The backtester only has 1-minute data and its simulates the ticks arriving at the terminal during a backtest to form the bar. This sometimes causes EA's that have very small take profit values to look great in a backtest, but test lousy in reality.

2) Many an EA is programmed improperly by taking action on price[0] which is the current bar in the making, rather than testing on price[1] which is the most recent completed bar. We all know that bars can change in during formation and a very bullish bar (bullish engulfing) can turn into a indecisive bar (spinning top) based on the value of the close alone. So your EA should always take action on the price action in bar [1] rather than bar [0].

That's all for now, check back later for information on Account functions.

Monday, January 4, 2010

MetaTrader - MQL4 programming - Part 3

Welcome back Forex fans.

Here's my 3rd installment on programming MetaTrader. In case you missed my prior posts, you can find them MetaTrader programming part 1 and MetaTrader programming part 2.

In this post, we'll take a look at the MarketInfo() function. This function pulls some necessary information from the broker about the symbol in question. Go ahead and create a new EA file called MarketInfo. Paste the following code above the init() function:

string sSymbol;

Now paste this code into the init() function:

int init()
// Grab current symbol
Print("Marketinfo Startup");

// Grab current symbol
sSymbol = Symbol();

// Print it out and finish up
Print("Symbol: ", sSymbol);


Now setup your Start() function as follows:

int start()
double dRetval;

dRetval = MarketInfo(sSymbol,MODE_LOW);
Print("Days high: ", dRetval);

dRetval = MarketInfo(sSymbol,MODE_HIGH);
Print("Day low : ", dRetval);

/* Skip Bid, Ask, Point, Digits, they pre-defined variables */

dRetval = MarketInfo(sSymbol,MODE_SPREAD);
Print("Spread: ", dRetval);

dRetval = MarketInfo(sSymbol,MODE_STOPLEVEL);
Print("Stop Level: ", dRetval);

dRetval = MarketInfo(sSymbol,MODE_LOTSIZE);
Print("Lot Size: ", dRetval);


/* Skip these
MODE_LOTSIZE 15 Lot size in the base currency.
MODE_TICKVALUE 16 Minimal tick value in the deposit currency.
MODE_TICKSIZE 17 Minimal tick size in the quote currency.
MODE_SWAPLONG 18 Swap of a long position.
MODE_SWAPSHORT 19 Swap of a short position.
MODE_STARTING 20 Trade starting date (usually used for futures).
MODE_EXPIRATION 21 Trade expiration date (usually used for futures).
MODE_TRADEALLOWED 22 Trade is allowed for the symbol.
MODE_MINLOT 23 Minimal permitted lot size.
MODE_LOTSTEP 24 Step for changing lots.
MODE_MAXLOT 25 Maximal permitted lot size.
MODE_SWAPTYPE 26 Swap calculation method. 0 - in points; 1 - in the symbol base currency; 2 - by interest; 3 - in the margin currency.
MODE_PROFITCALCMODE 27 Profit calculation mode. 0 - Forex; 1 - CFD; 2 - Futures.
MODE_MARGINCALCMODE 28 Margin calculation mode. 0 - Forex; 1 - CFD; 2 - Futures; 3 - CFD for indexes.
MODE_MARGININIT 29 Initial margin requirements for 1 lot.
MODE_MARGINMAINTENANCE 30 Margin to maintain open positions calculated for 1 lot.
MODE_MARGINHEDGED 31 Hedged margin calculated for 1 lot.
MODE_MARGINREQUIRED 32 Free margin required to open 1 lot for buying.
MODE_FREEZELEVEL 33 Order freeze level in points. If the execution price lies within the range defined by the freeze level, the order cannot be modified, canceled or closed.

As we can see from the code, the MarketInfo() function allows us to pull the day's high and low when using the MODE_HIGH and MODE_LOW parameters. This could be useful when coding an Expert Advisor. The daily high/low counters reset when the daily interest rate roll occurs which is at 5PM EST.

Calling MarketInfo() with the MODE_SPREAD parameter pulls the current spread for the pair which you can get just as easily by subtracting the Bid from the Ask and dividing by Point.

The MODE_STOPLEVEL parameter returns the number of pips away from the current price at which you are allowed to place the a stop order or take profit order. In the above example, the Stop level value is 4 so if we went long the market at an Ask price of 1.4340, the closest that we could place a take-profit order would be 1.4344. If the current Bid price were 1.4338, the closest we could place a stop-loss order would be 1.4334.

When I first found out about this, I thought was kind of unfair. I suppose it prevents the market maker from constantly getting scalped and ensures that on trades that go against the customer, they make at least the spread plus the stop level. Of course, there's nothing preventing you from entering market orders to close a position within the StopLevel.

The MODE_FREEZELEVEL parameter returns the number of pips away from the current price at which limit orders are "frozen" and cannot be changed. For example, if the FREEZELEVEL were 5 and the current Bid/Ask was 1.4356 x 1.4358 and you had a limit sell order at 1.4360, you would not be allowed to modify or cancel your limit order since it was within 5 pips of the Bid price.

On my terminal FREEZELEVEL came back at zero, so i'm not sure its enforced with FXDD on their Metatrader platform.

Now save and compile the EA and drag it onto a chart of EUR/USD. Now drag it onto a few other charts such as GBP/USD and GBP/JPY to get a feel for the different Spread and Stoplevel values.

That's it, tomorrow we will take a look at Account and Terminal related functions.

Sunday, January 3, 2010

MetaTrader - MQL4 programming - Part 2

Welcome back, fans of forex and automated forex trading.

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);


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);

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.

Saturday, January 2, 2010

MetaTrader - MQL4 Programming Part 1

Welcome back Zulu-traders and fans of the Forex.

Let's take a look at programming in MQL4 - the language of MetaTrader 4.

Even if you don't plan to write your own Expert Advisers, its good to understand how they work. So how do you go about learning MQL4? You read the book, of course, which is found here.

I got through about half of the book and the author spends a lot of time on programming basics. If you've ever done any programming, the language looks pretty familiar and is probably closest to the C language. I'm not going to attempt to teach you programming here, so I'll just extract the most important concepts to get you started.

Anyway, there are 3 basic things you can program and execute inside the MetaTrader platform. To execute one of these items, simply drag it from the navigator on the left and drop it onto a price chart. Here are the 3 things you can program:

1) Expert Advisor (EA) - An MQL4 program used for automated execution of trading strategies. The EA is called automatically by the MQL platform at every "tick" or change in price from the quote server.Only one EA can be attached to a given chart, but you can apply multiple EA's to a given currency pair by opening multiple windows for that pair and dragging a different EA onto each window.

Its advisable to run only one EA on a given account at a time, otherwise it becomes too much to keep track of. Most MT4 users address this issue by installing MetaTrader into different folders (you get prompted for the folder at install time) and running multiple instances of MT4 on your computer. This would allow you to run 3 different EA's against 3 different demo accounts all at the same time.

Expert files get placed into the Experts folder under the folder where you installed MetaTrader.

2) Script - An MQL4 program to automate a series of operations involving price or trading. Scripts are allowed to call trading functions. A good use for a script would be to close all open trades. Scripts are executed only once on the chart at the time it script is dragged onto the chart.
Script files get places into the Scripts folder under the folder where you installed MetaTrader.

3) Custom indicator - An MQL4 program to calculate technical indicators on the current price chart. Custom indicators calculate values to be drawn on the price chart (such as a moving average) or in a separate windows such as an oscillator. Indicator scripts are called automatically by the MT4 platform at each tick. Trading functions cannot be called from inside indicators. Multiple indicators can be applied to a chart at a given time which distinguishes them from EA's and Scripts.

Script files get placed into the Scripts folder under the folder where you installed MetaTrader.

Each of the above types of program contain 3 pre-defined functions:

init() - called only once when the Indicator, Script or EA first starts. This is a the place for any first time operations in your programs.

deinit() - called only once when the Indicator, Script or EA ends. This is a good place for clean up operations.

start() - called each time a new tick arrives at the platform for both EA's and Indicators. This is where the action is. I believe start() is called only once for scripts. Now that we have that behind us, let's write our first program in MQL4.

From inside the platform, click on 'Custom Indicators' on the left side and press the Insert key.

At the wizard which appears, select 'Custom Indicator' and click Next.

For the name, call it First.

Complete the rest of the screen with your name, copyright and blog if you have one and click Next.

Leave the following screen unchanged and click next.

Once the program appears on the screen, setup the init function as follows:

int init()
Alert("Hello MetaTrader");

Alert() is a simple function that pops up a message on the screen. Once you are done coding, click the Compile icon at the top and fix any syntax errors which appear. Once the compile is clean, select File, Exit and notice that the file will be saved in your indicators folder.

Now exit the MetaEditor window and return the MT4 platform window. Now select File, Exit to exit Metatrader.

Now start MetaTrader again and your new indicator (called first) should appear under the Indicators folder now. Now simply drag the new indicator onto a price chart and you should see the alert.

Congratulations, you just wrote your first MetaTrader program!

That's enough for now, check back later for Part 2.