Friday, December 25, 2009

MetaTrader - MQL4 programming - Part 1

Welcome back Zulu-traders and fans of the Forex.

Here's wishing you a Merry Christmas and all the best for a healthy and prosperous New Year!

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. It's typically 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 good place to do 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 most of 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");
return(0);
}

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.

2 comments:

  1. Here's hoping you continue with some tips on writing the MT code. I used to be a programmer (SAS), and have studied some of the open EA code, but can't seem to get the real hang of it, although I've been able to modify one to my partial satisfaction. I'm often just too tired to focus on learning the language after a hard day of trading, in that Forex trading for me can span 16-17 hours (7am to 12pm some days when markets are moving). Why do I do it? Because it's there, and winters are long here in the great white north.

    But I would much rather program an EA to do my trading, and let it run day and night. My trading style is to trade the Eur/Usd or Aud/Usd or Usd/Cad or Gbp/Usd (which are highly correlated) by determining when they are losing trend momentum and then go the other way if I get a trend change signal. I use the CCI (at roughly 200 or -200) to find momentum extremes and Hull moving averages (one lagged) for my cross over signal from one trend to another. The SL is 15 pips, TP is 15 pips also, one minute (or five minute) charts. Works pretty well for me (with a little judgement applied, not totally mechanical), providing lots of trades within a day. Now you can buy Pips Sniper, Pips Snager, or Forex Rebellion, or several other manual type EA's to get very similar signals, but there's no substitute for inventing your own method - this is not brain surgery. And I've tried to modify an open EA which did a similar thing except using Stochastics instead of CCI, and had some success with signals. But there was no money management in the EA, it used a simple, crude method to end and start a trade...trade began by hitting the CCI but only ended when it hit another CCI, ie. was always invested. Really dumb. What I have learned the hard way, this trading game (no matter what you trade) is about money management more than anything else. Of course that implies discipline applied to pretty much every trade, and that is easy to say but not so easy to execute. Programming an EA for money management should take care of this issue.

    Hopefully if I learn something over time about MT4 language I might be able to produce a useful EA so I can walk the beaches of Florida while my EA is hauling in the cash.

    ReplyDelete
  2. Redford-

    I'm with you in terms of taking advantage of what EA's have to offer. I can't spend that much time in front of the computer, so i'm definitely looking to program and EA or use someone else's EA and let it run for weeks and months while I get on with my life.

    I think I understand your logic enough to make an EA out of it - but not far along with my EA programming skills to do so. Let's see if get that far.

    How right you are about money management, risk control etc. Daniel Ferandez has some interesting things to say about lot size, take profit and stop loss characteristics of long-term successful systems.

    Thanks for reading and for the comment.

    Chris

    ReplyDelete

Note: Only a member of this blog may post a comment.