MQL4 helper functions for calculating bar sizes

February 21st, 2010

Here are some more MQL4 helper functions for MetaTrader. You can use them in your expert advisors and custom indicators. The three functions will allow you to quickly get the size of the upper and lower wicks of the candle stick, and also the size of the candle stick body. To use them you will also need some of the code I gave you in my simple MetaTrader MQL4 helper functions post.

If you use these functions in your code please give a reference to this blog post.

double UpperWickSize(int bar)
   if (UpBar(bar))
      return (High[bar]-Close[bar]);
   if (DownBar(bar))
      return (High[bar]-Open[bar]);
   return (0);
double LowerWickSize(int bar)
   if (UpBar(bar))
      return (Open[bar]-Low[bar]);
   if (DownBar(bar))
      return (Close[bar]-Low[bar]);
   return (0);
double BarBodySize(int bar)
  if (UpBar(bar))
    return (Close[bar]-Open[bar]);
  if (DownBar(bar))
    return (Open[bar]-Close[bar]);
  return (0);

Simple MetaTrader MQL4 helper functions

January 30th, 2010

Here are some simple functions that you can use in your forex expert advisors and custom indicators written in MQL4 for MetaTrader.

If you split out commonly used functionality into separate functions with logical names (as I’ve done here) then you should find that your MQL4 code becomes more readable.

If you use these functions in your own code please reference this blog.

// returns the value of the top of the bar
double TopOfBar(int bar)
   return (MathMax(Open[bar], Close[bar]));
// returns the value of the bottom of the bar
double BottomOfBar(int bar)
   return (MathMin(Open[bar], Close[bar]));
// true if this is a down bar
bool DownBar(int bar)
  return (Close[bar]<Open[bar]);
// true if this is an up bar
bool UpBar(int bar)
  return (Close[bar]>Open[bar]);
// size of whole bar including the wicks
double HighLowSpread(int bar)
   return (High[bar]-Low[bar]);
// gives you the result of subtracting the lowest input value from the highest
double HighMinusLow(double value1, double value2)
   double high = MathMax(value1, value2);
   double low = MathMin(value1, value2);
   return (high-low);

Hope you find these useful.

Disadvantages of expert advisors

January 15th, 2010

Following on from my advantages of expert advisors post here are some disadvantages of trying to write and use expert advisors.

Curve fitting

Because it is easy to backtest expert advisors many times with different parameters it is very easy for them to suffer from curve fitting.

Curve fitting means that the EAs are highly optimised for the specific period of time for which they have been tested against, but may turn out to be loss making if run on actual live data.

A good expert advisor will not need to be micro-optimised in order to make a profit. There may well be certain values that perform better than others, but a range of values around the optimal ones should also be profitable to prove that the expert advisor isn’t just working because of some very specific circumstances that are unlikely to occur again in future.

As well as curve fitting the parameters it is very tempting to add new code branches into the expert advisor to filter out bad trades and allow though good trades. Again this is likely to produce an expert advisor which is highly optimised only for the historic data on which you are testing it.

Curve fitting over-optimisation is a very easy trap to fall into when writing expert advisors. It is a waste of time, as you won’t end up with a profitable expert advisor. Spend that time on writing quality expert advisors which can handle whatever data you throw at them.

Unrealistic backtests

Many pieces of trading software that allow you to backtest EAs do not allow you do it in a way that realistically simulates the real market. Doing so would be very difficult because there is a lot more information you need to know other than the price. E.g. you need to know about the spread, execution delay, slippage, and liquidity.

Backtesting data does not tend to give you access to this kind of information. In addition the granularity of backtest data is often much less fine than what you would get if you were trading live.

Most backtesting data is only available for 1 minute and above timeframes. This means that you miss out on the tick-level information that could be essential, especially if your trading strategy works on shorter timeframes.

Many backtesting software packages compensate for this by ‘filling in the gaps’, and create simulated ticks. This can be dangerous, as the algorithm used may well not generate ticks in a way that is realistic enough for your strategy.

It is quite possible (in fact easy) to create an expert advisor that works brilliantly on historical data using a backtest but consistently loses when used for real.

Difficult to write

Translating a working strategy from your brain into an expert advisor can be very difficult.

When you trade manually you can interpret huge amounts of data and news in a way which can be very difficult for a computer program to do. Interpreting simple facts such as the value of an indicator is easy for an EA to do. However interpreting something such as the current economic climate or the latest news that has just been released is extremely difficult.

Getting EAs to recognise complex chart shapes and patterns can be very difficult. It is all to easy to program the EA to recognise specific patterns that occurred in the past rather than getting it to understand the meaning of the chart patterns in the way that your brain will.

Expert advisor bugs

All software beyond trivial code snippets will contain bugs. For most pieces of software the consequences won’t be too bad. Maybe the program will crash, get stuck, or if you are unlucky perhaps you will lose some work.

Expert advisors for forex and CFDs are somewhat different as they have the power to make decisions that affect your bank balance! If your EA has a bug then it could make the wrong decision resulting in a loss of money. If the bug is bad then maybe you’ll lose a lot of money!

Would you trust a piece of computer software to buy and sell on your behalf? Even if you have done large amounts of testing how can you be sure that your EA won’t trip up when it is left to run by itself?

As EAs are often left to trade by themselves, any bug or defect in the code could be very costly. You might not spot that anything is wrong until you find your account has been emptied of all its money.

Think carefully before you let an EA lose on your live account. Make sure it is well tested, and keep a careful eye on what it is doing. To avoid it losing too much in the event that it doesn’t work as expected make its trade sizes small to start with and don’t keep to much money in your account.


Before you spend time creating an expert advisor make sure you don’t fall into any of the problems listed above. Doing so could cost you serious money.

Forex New Year’s resolutions for 2010

December 24th, 2009

1. Write down my plan for each trade before pressing the buy/sell button. The plan will include the reason for why I am doing the trade, the expected profit, the initial stop loss and the expected duration of the trade.

2. Double-check the order quantity before executing the trade. It is too easy to lose money by buying or selling the wrong amount of currency.

3. Ensure that all trades have an explicit stop loss added to them.

4. Spend more time working on my expert advisor framework in MetaTrader MQL4.

5. Contribute more to the forums at Trade2Win and babypips.

6. Spend less time reading trivial financial news – it does not help! But be more aware of major currency related announcements.

7. Read more quality trading books and review them here.

8. Add more content to this blog – Will be adding more posts about writing expert advisors using MetaTrader MQL4, more on risk management, and more general trading advice.

Do you have any forex New Year’s resolutions? If you do, let me know by using the comment box below.

Merry Christmas and a Happy New Year!

The Expert Advisor advantage

December 21st, 2009

For most people trading in forex is a very manual process. It involves watching charts, indicators, and the news. They then have to work out in their head whether it is a good time to buy or sell.

For some strategies this makes a lot of sense. For example if you trade based on news events then you need to be there to interpret how the news will affect the price. This is fundamental analysis.

Many forex trading strategies rely on much simpler decisions. If you are basing your trading decisions on the shape of the chart, or on the values of your indicators then you are using technical analysis.

Many technical analysis strategies work by making decisions purely on indicators or price.

For example a strategy might be to buy if the price moves above a certain moving average line and sell if the price falls below the line.
Another strategy might involve buying or selling based on one or more technical indicators such as MACD, parabolic SAR, or RSI.

If your strategy is based on simple rules such as certain technical indicator values being reached then you may find that your trading is very robotic. You wait for a specified event to happen and then you act on it in a predefined way.

If you have a strategy that sounds like this then it could be a very good candidate for automating – i.e. creating an expert advisor to do the trading for you so you don’t have to do it yourself.

metatrader mql4

Expert advisor code in MetaTrader

This post will look at the advantages of expert advisors.

Expert advisors don’t get tired

If you are trading manually then the amount of time you can spend trading will be limited by how long you can concentrate or stay awake.

Forex is a 24 hour game with trading opportunities right around the clock. If you are trading manually then you are limiting yourself to only taking advantage of a fraction of these opportunities.

Throughout the day you will also need to take breaks for food, drink, to answer the telephone, etc. During one of these breaks something might happen which you don’t see until it is too late. This could cause you to buy or sell at a bad time, or miss out on a great trade altogether.

An expert advisor will be able to trade for you right through the night, through your lunch break, and when you are out of the house. It will never get tired and so will be able to capture all the trading opportunities that it is programmed to capture.

Of course if the expert advisor is doing your trading for you, then you will have more free time to do more important things like reading a book, or seeing your friends. Who wants to spend their life staring at a moving line on a screen, or watching numbers going up and down?


A lot of people have sound trading strategies but they fail to stick to them. You may find that your emotions get in the way and cause you to sell too early, or buy too late, because you don’t have the confidence to stick to your trading plan.

It is also possible for you to get stressed when trading which could lead to you making mistakes in your trading. How many of us have sold when we meant to buy, or entered the wrong amount into our trading ticket and then had to accept a loss in order to get out of the trade?

Once it is correctly programmed an expert advisor will have no such problems. It will follow your simple set of rules (or maybe a complicated set of rules!) without ever hesitating or letting its emotions cloud its judgement. Obviously an expert advisor is just a computer program so it will just do what it is told to.

This consistency means that it will stick perfectly to your trading plan and will never diverge from the rules that it has been given. The expert advisor won’t make mistakes – if it is supposed to buy then it will buy – it won’t press the wrong button and sell!

Speed of analysis

Human brains are great for many things, especially ‘fuzzy’ processing like thinking, and interpreting inputs from complex senses such as sight and sound. What they aren’t so good at is number crunching, or making decisions based on large amounts of data that are coming in at the same time.

If you are a manual forex trader then you will probably limit yourself to trading one or two currencies simultaneously. Trading more than this can get confusing. For one thing keeping an eye on multiple charts can be difficult, and if significant events start happening with multiple currencies at the same time (as they often do) you may not be able to keep up.

An expert advisor has no such problems. It can handle trading simultaneously in 10 different currency pairs just as easily as it can handle trading with one currency pair. Computers are able to process information so fast that they have no trouble keeping up with what is going on with multiple price feeds.

If you have a strategy that is applicable to multiple currencies then an expert advisor could allow you to trade more currencies simultaneously than you are able to using manual methods. Alternatively it can watch multiple currencies and then pick the best one to trade in. Imagine how fried your mind would get if you were trading in a short time frame and trying to keep your eyes on 10 charts!


Coming up with a manual trading strategy may involve eyeballing many charts and evolving the parameters you use over time.

If you write an expert advisor then you can very quickly test your strategy over many years worth of data in just a few minutes. This will give you a much better idea of how well your strategy will perform than just eyeballing the charts.

Trying to gauge how well the strategy will work using your eyes and brain is very dangerous because of hindsight bias. You may be feeling optimistic about your strategy and without realising it your brain will focus on areas of the chart where your strategy would work and will filter out parts of the chart where you would make a loss.

An automated backtest will get you much more accurate and consistent information on the performance of your strategy.

And because you can quickly test your strategy over many years worth of data you can also re-test your strategy using different parameters. You may think your strategy works best using a 11 day moving average, but some simple testing could reveal that a 13 day moving average is in fact the most profitable.

Are automated expert advisor the answer?

Expert advisors sound great don’t they? For many strategies then can prove to be much better at trading than a real person would be. They aren’t perfect though.

In a future post I’ll be looking at the disadvantages of expert advisors, and I’ll also be writing further about other issues to do with expert advisor.

If you want to have a go writing your own expert advisor you can get a MetaTrader forex account for free.

Five tips for winning at forex trading

December 17th, 2009

1. Exits are more important than entries

Forex traders often over think about when they should enter a trade. Huge amounts of time can be spent looking at indicators, reading news, and drawing lines on charts to try and figure out if now is the perfect time to open a trade.

Unfortunately for them they should be focusing some of that energy elsewhere.

It is true that a good entry into a trade is important. For example opening a new ‘long’ trade when the price has massively spiked is probably a bad thing, as the price will probably reverse just as quickly.

What is more important is when you exit the trade. It is at the time of exit that your trade becomes either profitable, non-profitable, or breaks even. It doesn’t matter if you were up 10% one hour ago. If you close the trade when you are down 2% then that is the final result. Being right about the price direction for the much of the trade duration gets you no profit if you closed the trade after a large reversal.

japanese currency yen

By all means spend time working out when to enter a trade – this is an important thing to do. But do also spend time thinking about when to exit. Don’t just exit in a panic. You should have a plan and then stick to it.

Which brings us onto…

2. Have your trade lifecycle planned out before you enter

Some people treat trading like a computer game, just clicking on the buy and sell buttons in the hope that they will make money. These people will probably find that their account balance goes down very quickly.

Blindly entering and exiting trades without having any real plan in place is only going to lead to one thing – a smaller bank account balance!

Before entering a trade you should know:

  1. Why you are opening this trade?
  2. How long you expect the trade to go on for?
  3. At what level would you either take profit or tighten your stops?
  4. At what price would you accept that your initial analysis was wrong and exit the trade?

Many traders find that small losses become large losses because they haven’t planned their trade in advance. They just entered the trade without thinking it through. The trade goes against them, and rather than exiting they stay in the trade hoping that it will turn around. Does this sound familiar?

If you are unable to trade in a disciplined way then you will consistently lose money to those traders who are able to trade with a disciplined methodology.

Trading with a disciplined methodology means trading with a plan. A plan means having answers to the four questions above – and then sticking to the plan!

The 4th question is about knowing when the trade has gone wrong so you can exit. The next tip covers an important aspect of planning your exit.

3. Have a stop loss in place in case it all goes wrong

As covered in my previous blog post about stop losses, a well thought out stop loss can be worth its weight in gold. It can stop you from losing large amounts of money, and enable you to ‘lock in’ your profit.

A stop loss should initially be the record of your trading plan’s worst-case exit price. Placing a physical stop loss is much better than using a ‘mental stop loss’ as the physical stop loss isn’t affected by your emotions.

As the trade progresses then you should tighten the stop loss according to your trading plan. What you should not do is decide to loosen your stop loss because you want to stay in the trade for longer.

Loosening a stop loss, or removing it altogether after it has been placed is a sign of not having control over your trading.

4. Monitor your trade appropriate to the timeframe

Unless your trade’s exit points are always determined by a stop loss and limit order that you placed your trade will require monitoring whilst it is in progress.

You should monitor your trade in a way that is appropriate to the timeframe in which you are trading.

If you are trading a small timeframe such as 1m, 2m, etc, then you obviously can’t afford to leave the screen or room for a few minutes as you might miss an important exit signal and end the trade in a loss. At very small timeframes even going to the toilet can cost you real money!

If trading longer timeframes such as 1h, 4h, 1 day, 1 week, etc, then you really shouldn’t be spending large amounts of time staring at the screen watching your trade. Doing this will turn you into a nervous wreck as the price continually moves up and down. Trading at a longer time frame should mean you don’t need to know about such micro-movements of the price.

5. Understand how much money is ‘on the table’

No matter what you are trading you should always have a thorough understanding of just how much money you have at risk.

Don’t just think about the potential profit. Think about the potential loss. Think about the worst case scenario. How much money could you lose? If you are not comfortable with the figure then you are trading with positions that are too large for you.

You should always be able to withstand all your positions going against you at the same time, no matter how unlikely it may seem. If you can handle it (note – just handle it – you don’t have to be happy about it!) then you are trading at an acceptable level.

Book review roundup – Forex, Turtles, LTCM, Stock market and Randomness

December 9th, 2009

I’ve been reading finance and trading books faster that I’ve been able to review them! Here is a roundup of the last five finance and trading related books that I’ve read.

Currency Trading for Dummies by Mark Galant and Brian Dolan

Mark Galan and Brian Dolan both work at which is one of the largest forex retail brokers in the world.

They’ve put their knowledge into this book, packaged in the familiar ‘dummies’ style.

Even though this is marketed as a ‘dummies’ book there is a surprisingly large amount of detail in the book which makes it worth reading even if you have been trading in forex for a while.

They explain the differences between the major currencies. They talk about how the world economies interact. They provide a good slice of standard trading advice (strategies, stops, trade size, etc). And they cover other topics such as technical analysis, trading from the news, and trading do’s and don’ts.

Way of the Turtle: The Secret Methods that Turned Ordinary People into Legendary Traders by Curtis Faith

Curtis Faith was one of the original ‘Turtles’. The turtles were ordinary people who were taught how to be professional traders by Richard Dennis as part of a bet as to whether successful traders are made or just born.

Curtis gives a brief account of how he was selected to be a turtle (which to me would seem to invalidate the idea of the bet – it they wanted to see if anyone could become a successful investor then shouldn’t they have randomly selected people?). And he gives a brief account of his time as a turtle trader.

Most of the book is however about writing and testing trading systems. He covers topics such as how to do a good backtest – important to make sure you don’t bias the results. And he talks about rules that a good trading system should use.

If you are interesting in writing trading systems then this book gives plenty to think about. A quick read and very interesting.

When Genius Failed: The Rise and Fall of Long Term Capital Management by Roger Lowenstein

When Genius Failed tells the story of the mighty rise, and then mighty fall of Long Term Capital Management.

This is the account of how ex-Salomon Brothers trader John Meriwether created LTCM and how it became one of the largest arbitrage hedge funds in the world in a few short years.

When Genius Failed continues parts of the events that were covered in the book Liar’s Poker by Michael Lewis – another recommended read.

John Meriwether managed to recruit some of his old team from Salomon Brothers and added two Nobel Prize winners – Robert Merton and Myron Scholes for good measure. To add further credibility to the fund he recruited David Mullins, the ex-Federal Reserve Vice-Chairman.

With his prestigious team in place he was able to obtain billions of dollars of capital, and get highly advantageous terms from the brokers and clients they dealt with.

They thought they were invincible, and for a time they produced amazing returns.

However things went wrong when they got too big and started diversifying into new areas. They were stung by the Asian currency crisis of 1997 and then in 1998 their downfall was cemented when Russia defaulted on its debt.

This is a fascinating read of how huge success can lead to spectacular failure. This book is a warning for anyone who takes on risk beyond his or her means.

How the Stock Market Works: A Beginner’s Guide to Investment by Michael Becket and Yvette Essen

How the Stock Market Works is a small book that does as its title suggests. It tells you in brief how the stock market works.

It tells you what shares are, how you research them, and how you can buy them.

It explains how you can read the financial pages in newspapers and how you can understand a company report. If you want quick descriptions of what all those financial rations mean then this could be the book for you.

It is not what I’d call a ‘fun or interesting’ read, however there is a lot of useful information in here.

This book is pitched towards people who are investing for the long term. It does not cover shorter term trading.

Fooled by Randomness: The Hidden Role of Chance in Life and in the Markets by Nassim Nicholas Taleb

Fooled by Randomness is a fascinating book that explains how much our lives are affected by pure randomness.

There are a lot of examples of how this relates to the trading world (Nassim is an options trader), but there are plenty of non-trading examples as well.

Fooled by Randomness flits from one topic to another at speed and is one of those books that makes you think.

One of the most important messages that he tries to get across to traders is that just because you win many trades don’t assume you are a good trader. It could just be you are benefiting from random luck. Sample size is all important – winning trades over a number of months or even years may not be enough to tell you anything about your trading skills.

The author is clearly very intelligent and has put together a highly readable and interesting work, but sometimes he does come across as a bit arrogant – he could do with toning some of his personal insults down.

Nether the less – a fun read – and I’ve already got his follow up book The Black Swan: The Impact of the Highly Improbable, on order.

Can trading forex make me rich?

December 2nd, 2009

Many people are attracted to the idea of trading in forex (or other financial instruments such as CFDs, shares, or spread betting) because they think it is an easy way to make money.

In theory it is very easy. All you have to do is to predict whether a price is going to go up or down. If you are right then you get make money. The degree to which you are right or wrong will determine how much money you make or lose.

pound sterling bank notes

It can seem all too easy when the papers or the TV news are running stories day after day about how a currency or a stock is going up or a currency or stock is going down. You may look at these stories and think that if only you had placed a bet a few days ago you’d be ‘in the money’.

Forex in particular seems to have a certain mystique about it. The major currencies are highly liquid, there is often a good amount of volatility, and the retail brokers will let you trade with large amounts of leverage.

It can also be enticing because rather than having to look at boring company reports and exotic financial ratios, you can read about how the economy is doing and make guesses on where economic policy is going to go.

So do people get rich from forex?

Of course they do. People can get rich from anything. People can get rich from winning the lottery or from betting on horse racing. That doesn’t however mean that *you* can get rich from doing these though.

Some people make a very good living from forex and win consistently week in, week out.

Some people trade forex for a few months and double or triple their money. Does this mean that they will become rich? Not necessarily. In fact if they are making money very quickly then it is extremely likely that they will lose it all even quicker.

Trying to become rich from doing a few trades in forex over a short period of time will not make you successful as pretty much the only way you can achieve very high percentage wins is by taking unmanageable risks. If you are taking unmanageable risks then the one thing which is almost certain is that you will get burnt – and probably badly. There is even a big chance that you will lose a lot more than you put in.

If you look at the forex bulletin boards then you can find many sorry accounts from people who make a large amount of money very quickly but then lost it all in a fraction of the time. Did they become rich? Even thought their account may for a few days have had $20,000 of winnings in it, they never got to enjoy the money as it was all lost too soon.

The odds are stacked against you from the start

Remember that as forex is a game of currency pairs, for one currency to go up, the opposing currency must go down. This means that where people are making money, others are losing money.

This is very different to trading in stocks and shares where it is possible for all the shares to go up in value at the same time if the economy is doing great, and for them all to go down at the same time if some major economic upset occurs.

Unfortunately the split of winners to losers is not an even 50:50. For starters for every trade that is made the broker is taking a small commission. This means that there is less money to win, than has been put into the ‘forex pot’.

On top of that professional forex traders, banks and other financial institutions will be taking an uneven percentage of the winnings.

This means that you as a beginner forex trader have the odds very much stacked against you.

As some people get rich from forex, can’t I?

I hope you can see that most people won’t be getting rich from forex. But some do – so could you be one of them?

Let’s think about this another way.

Private dentists can make lots of money. However it isn’t easy. You need to study for many years, practice all the various techniques, pass exams, and have the time and money to be able to go through all of this.

You can’t just become rich overnight by starting a dentist practice.

So why do you think it is any different for trading?

I think the reason for this perception is due to how easy it is to trade. No one (who is sane anyway) would think about having a go at doing a root canal procedure. Where would you even start! However anyone can make a trade on forex. You just have to open an account, press a few buttons, and you are making a trade!

The fact that it is easy to make a trade does not mean it is easy to consistently make winning trades every day, year after year.

To be a winning trader you will need to do large amounts of study, practice regularly, and have the right attributes to place and manage your forex trades.

In conclusion

Forex can indeed make you rich. It just probably won’t.

Always have a stop, and ideally a limit

November 26th, 2009

When trading financial derivatives such as forex, CFDs should you always use a stop?

Short answer: Yes!

Long answer: Yes you should always have a stop in place – even if you think you really don’t need one.

Note that I’m only referring to financial derivatives such as forex and CFDs where you trade on margin. If you are trading or investing in instruments where you pay the full price up front (as you will usually do with shares) then this doesn’t apply to the same extent.

Leveraged price moves

A stop is very important with derivatives because when you are trading on margin any moves in the market price is magnified (often by huge multiples –1:400 leveraged forex – are you insane!). A move in the wrong direction can easily wipe you out – along with any other unrelated positions that you currently have open. In the worst case you could even end up owing your broker money – and that is not a good place to be.

forex trading screen 4

Stops are for wimps!

If you talk to people or read the trading bulletin boards there is often a certain amount of bravado about trading without a stop. Some people seem to think that stops are for wimps or are irrelevant for the strategy they are using (“I don’t need a stop because if the market moves against me I manually close out the position in time”).

Emotional decision making

Some people may be disciplined enough to close out at a sensible price but most aren’t. When the numbers on your screen start moving against you it is all to tempting to think – “I’ll stay in a bit longer – the price might go in my favour again”. The chances are that it will just keep going against you making your loss bigger. If you have a stop then you remove your emotions from exiting at the right time.

You should decide your worst exit price when you place the trade when you are thinking more rationally. You of course always have the option to exit earlier if you realise you are wrong before you stop gets hit. Just whatever you do don’t start loosening your stop. Remember the reason you set it at that value in the first place.

My strategy doesn’t require stops

Some people (for our example we’ll call our trader ‘MrNoStop’) will argue that the strategy they are trading does not require stops. They talk about never leaving the screen when a trade is open. If something happens there are always at hand – and cool headed enough – to close that trade.

So what happens then if some huge incident occurs which has a massive impact on prices. For example an unprecedented terrorist attack. Imagine that due to the incident the internet grinds to a halt – as it did on 9/11.

Suddenly MrNoStop’s trading platform stops responding, his previously fast internet connection grinds to a slow trickle. Now MrNoStop can’t exit his trade using his computer. Never mind thinks MrNoStop – I’ll telephone my broker. I always have their number to hand.

MrNoStop calls the number. It is engaged. He keeps trying. Eventually the number rings but no one answers. What is going on? Well of course MrNoStop isn’t the only one affected by the internet outage – all the broker’s customers are affected and they are now phoning the company on mass to either find out what is going on or close their positions. If only MrNoStop had used a stop.

Even if his normal strategy didn’t need a stop he still should have used an ‘emergency contingency’ stop to prevent this kind of thing from happening. It could have saved him a lot of money.

It can be good to have a limit order in place

In the title for this post I mentioned that you should always have a limit as well. Why is this?

Well let’s go back to MrNoStop’s bad situation. It is entirely possible that the terrorist attack could have had a massive positive effect on MrNoStop’s position. The price could have spiked up and then headed back down whilst MrNoStop was unable to use the internet or get though on the phone. If he’d used a limit order as well for this trade then it is possible that he may have made it out with a profit.

Some caution suggested

Maybe I’ve convinced you that always having a stop and a limit order is a good idea.

Well I’ll give you some warnings as well. If your trading platform implements stops and limits as separate tickets from the main trade then you need to be very careful to make sure you know exactly what tickets you have open! Make sure that you don’t accidentally get into trades that you didn’t mean to. If you close your trade ticket then close any associated stops and limit orders as well. Ideally you should have a blotter listing all your open tickets permanently on screen. If you have enough monitors then using one of them for account information can be worthwhile.

If your trading platform implements the stops and limits as part of the same order (and automatically cancels the stop and limit when the trade is closed) then things are much easier. This is because you can’t end up with forgotten stops and limits that are waiting to trigger when you least expect them!

Implementing an assert in MetaTrader MQL4

November 25th, 2009

MQL4 is a very useful programming language for creating expert advisors to automatically trade FOREX. However the language does have many omissions which you will soon notice if you are used to programming a more complete language such as Java or C++.

One of the big omissions is that there is no built in way to do an ‘assert’ when running an expert advisor. If some kind of exceptional condition occurs that would make any further running of the expert meaningless there is nothing you can do as you can’t exit the current run programmatically.

This can waste a lot of time while you wait for the expert to complete. Something could have gone wrong in the depths of your code and you might not even realise it until the expert has completed – if at all!

On one website I did see the suggestion to implement an MQL4 assert by printing out the word ‘ASSERT’ along with your debugging message and then searching for it in the logs after the run has complete.

This is very unsatisfactory as it requires you to manually search for the tag, and you will only know if the assert has happened if you actually look for it.

My solution won’t stop the expert from running immediately (there is no way to do this in MQL4). But what it will do is to stop any further parts of your code from being executed by stopping the start() function from doing anything. This will mean that if an assert happens your expert will finish executing very quickly and the ‘assert’ message will be near the top of the log – so you don’t have to hunt for it.

Here are the code snippets you need.

// This goes near the top of your .mq4 file
bool iASSERT = false;
// Assert if the condition is true
void ASSERT_IF(bool condition, string message, string function)
   if (condition)
      ASSERT(message, function);
// Unconditional assert
void ASSERT(string message, string function)
   Alert("*** ASSERT: ", message, ", function=" + function + " ***");
   iASSERT = true;
// Rest of your code goes here…
// You add one line to the beginning of your start function. The rest of your
// start function is unaffected.
void start()
   if (iASSERT) return;
   // rest of your start function

How do you use these asserts? The first example is using the unconditional assert. Your expert will stop executing when the next tick is passed to the expert (via the start function).

if (type == StopTypeFast || type == StopTypeSlow)
      ASSERT("Stop type not valid here: " + type, "UpdateStops");

The next example is using the condition assert. The ‘assert’ only fires (and the expert execution is halted) if fractionalPips is bigger than 1.

int ToIntPips(double fractionalPips)
   ASSERT_IF(fractionalPips>1, "fractionalPips>1", "ToIntPips");
   return (fractionalPips*10000);

You can see from the code that the ASSERT function is not strictly necessary as both behaviour can be implemented in terms of ASSERT_IF. However having both versions gives you more flexibility in how your code works.