As you may know, the Foreign Exchange (Forex) market is used for trading between currency pairs. But you might not be aware that it’s the most liquid market in the world.

A few years ago, driven by my curiosity, I took my first steps into the world of Forex trading algorithms by creating a demo account and playing out simulations (with fake money) on the Meta Trader 4 trading platform.

After a week of ‘trading’, I’d almost doubled my money. Spurred on by my own success, I dug deeper and eventually signed up for a number of forums. Soon, I was spending hours reading about algorithmic trading systems (rule sets that determine whether you should buy or sell), custom indicators, market moods, and more.

My First Client

Around this time, coincidentally, I heard that someone was trying to find a software developer to automate a simple trading system. This was back in my college days when I was learning about concurrent programming in Java (threads, semaphores, and all that junk). I thought that this automated system this couldn’t be much more complicated than my advanced data science course work, so I inquired about the job and came on-board.

The client wanted the system built with MQL4, a functional programming language used by the Meta Trader 4 platform for performing stock-related actions.

MQL5 has since been released. As you might expect, it addresses some of MQL4's issues and comes with more built-in functions, which makes life easier.

The role of the trading platform (Meta Trader 4, in this case) is to provide a connection to a Forex broker. The broker then provides a platform with real-time information about the market and executes your buy/sell orders. For readers unfamiliar with Forex trading, here’s the information that is provided by the data feed:

This diagram demonstrates the data involved in algorithmic Forex trading.

Through Meta Trader 4, you can access all this data with internal functions, accessible in various timeframes: every minute (M1), every five minutes (M5), M15, M30, every hour (H1), H4, D1, W1, MN.

The movement of the Current Price is called a tick. In other words, a tick is a change in the Bid or Ask price for a currency pair. During active markets, there may be numerous ticks per second. During slow markets, there can be minutes without a tick. The tick is the heartbeat of a Forex robot.

When you place an order through such a platform, you buy or sell a certain volume of a certain currency. You also set stop-loss and take-profit limits. The stop-loss limit is the maximum amount of pips (price variations) that you can afford to lose before giving up on a trade. The take-profit limit is the amount of pips that you’ll accumulate in your favor before cashing out.

If you want to learn more about the basics of trading (e.g., pips, order types, spread, slippage, market orders, and more), see here.

The client’s algorithmic trading specifications were simple: they wanted a robot based on two indicators. For background, indicators are very helpful when trying to define a market state and make trading decisions, as they’re based on past data (e.g., highest price value in the last n days). Many come built-in to Meta Trader 4. However, the indicators that my client was interested in came from a custom trading system.

They wanted to trade every time two of these custom indicators intersected, and only at a certain angle.

This trading algorithm example demonstrates my client’s requirements.

Hands On

As I got my hands dirty, I learned that MQL4 programs have the following structure:

  • [Preprocessor Directives]
  • [External Parameters]
  • [Global Variables]
  • [Init Function]
  • [Deinit Function]
  • [Start Function]
  • [Custom Functions]

The start function is the heart of every MQL4 program since it is executed every time the market moves (ergo, this function will execute once per tick). This is the case regardless of the timeframe you’re using. For example, you could be operating on the H1 (one hour) timeframe, yet the start function would execute many thousands of times per timeframe.

To work around this, I forced the function to execute once per period unit:

int start()
{  if(currentTimeStamp == Time[0]) return (0);
   currentTimeStamp  = Time[0];


Getting the values of the indicators:

// Loading the custom indicator
extern string indName = "SonicR Solid Dragon-Trend (White)";
double dragon_min;
double dragon_max;
double dragon;
double trend;
int start()
  // Updating the variables that hold indicator values

string actInfoIndicadores()
    dragon_max=iCustom(NULL, 0, indName, 0, 1);
    dragon_min=iCustom(NULL, 0, indName, 1, 1);
    dragon=iCustom(NULL, 0, indName, 4, 1);
    trend=iCustom(NULL, 0, indName, 5, 1);

The decision logic, including intersection of the indicators and their angles:

int start()
         if (dragon_min > trend && (ordAbierta== "OP_SELL" || primeraOP == true) && anguloCorrecto("BUY") == true && DiffPrecioActual("BUY")== true ) {
            primeraOP =  false;
            abrirOrden("OP_BUY", false);
         if (dragon_max < trend && (ordAbierta== "OP_BUY" || primeraOP == true) && anguloCorrecto("SELL") == true && DiffPrecioActual("SELL")== true ) {
            primeraOP = false;
            abrirOrden("OP_SELL", false);
           datetime ctm=OrderCloseTime();
           if (ctm>0) { 
          Print("OrderSelect failed error code is",GetLastError());

       if (ordAbierta == "OP_BUY"  && dragon_min <= trend  ) cerrarOrden(false);
       else if (ordAbierta == "OP_SELL" && dragon_max >= trend ) cerrarOrden(false);

Sending the orders:

void abrirOrden(string tipoOrden, bool log)
   double volumen = AccountBalance() * point; 
   double pip     = point * pipAPer;   
   double ticket  = 0;
   while( ticket <= 0)
   {  if (tipoOrden == "OP_BUY")   ticket=OrderSend(simbolo, OP_BUY,  volumen, Ask, 3, 0/*Bid - (point * 100)*/, Ask + (point * 50), "Orden Buy" , 16384, 0, Green);
      if (tipoOrden == "OP_SELL")  ticket=OrderSend(simbolo, OP_SELL, volumen, Bid, 3, 0/*Ask + (point * 100)*/, Bid - (point * 50), "Orden Sell", 16385, 0, Red);
      if (ticket<=0)               Print("Error abriendo orden de ", tipoOrden , " : ", ErrorDescription( GetLastError() ) ); 
   }  ordAbierta = tipoOrden;
   if (log==true) mostrarOrden();

If you’re interested, you can find the complete, runnable code on GitHub.


Once I built my algorithmic trading system, I wanted to know: 1) if it was behaving appropriately, and 2) if it was any good.

Back-testing is the process of testing a particular (automated or not) system under the events of the past. In other words, you test your system using the past as a proxy for the present.

MT4 comes with an acceptable tool for back-testing a Forex trading system (nowadays, there are more professional tools that offer greater functionality). To start, you setup your timeframes and run your program under a simulation; the tool will simulate each tick knowing that for each unit it should open at certain price, close at a certain price and, reach specified highs and lows.

After comparing the actions of the program against historic prices, you’ll have a good sense for whether or not it’s executing correctly.

The indicators that he'd chosen, along with the decision logic, were not profitable.

From back-testing, I’d checked out the robot’s return ratio for some random time intervals; needless to say, I knew that my client wasn’t going to get rich with it—the indicators that he’d chosen, along with the decision logic, were not profitable. As a sample, here are the results of running the program over the M15 window for 164 operations:

These are the results of running the trading algorithm software program I’d developed.

Note that our balance (the blue line) finishes below its starting point.

One caveat: saying that a system is "profitable" or "unprofitable" isn't always genuine. Often, systems are (un)profitable for periods of time based on the market's "mood":

A few trends in our algorithmic trading example.

Parameter Optimization, and its Lies

Although back-testing had made me wary of this robot’s usefulness, I was intrigued when I started playing around with its external parameters and noticed big differences in the overall Return Ratio. This particular science is known as Parameter Optimization.

I did some rough testing to try and infer the significance of the external parameters on the Return Ratio and came up with something like this:

One aspect of a Forex algorithm is Return Ratio.

Or, cleaned up:

The algorithmic trading Return Ratio could look like this when cleaned up.

You may think (as I did) that you should use the Parameter A. But the decision isn’t as straightforward as it may appear. Specifically, note the unpredictability of Parameter A: for small error values, its return changes dramatically. In other words, Parameter A is very likely to over-predict future results since any uncertainty, any shift at all will result in worse performance.

But indeed, the future is uncertain! And so the return of Parameter A is also uncertain. The best choice, in fact, is to rely on unpredictability. Often, a parameter with a lower maximum return but superior predictability (less fluctuation) will be preferable to a parameter with high return but poor predictability.

The only thing you can be sure is that you don’t know the future of the market, and thinking you know how the market is going to perform based on past data is a mistake. In turn, you must acknowledge this unpredictability.

Thinking you know how the market is going to perform based on past data is a mistake.

This does not necessarily mean we should use Parameter B, because even the lower returns of Parameter A performs better than Parameter B; this is just to show you that Optimizing Parameters can result in tests that overstate likely future results, and such thinking is not obvious.

Overall Forex Algorithmic Trading Considerations

Since that first algorithmic Forex trading experience, I’ve built several automated trading systems for clients, and I can tell you that there’s always room to explore. For example, I recently built a system based on finding so-called “Big Fish” movements; that is, huge pips variations in tiny, tiny units of time. This is a subject that fascinates me.

Building your own simulation system is an excellent option to learn more about the Forex market, and the possibilities are endless. For example, you could try to decipher the probability distribution of the price variations as a function of volatility in one market (EUR/USD for example), and maybe make a Montecarlo simulation model using the distribution per volatility state, using whatever degree of accuracy you want. I’ll leave this as an exercise for the eager reader.

The Forex world can be overwhelming at times, but I hope that this write-up has given you some points on how to get going.

Further Reading

Nowadays, there is a vast pool of tools to build, test, and improve Trading System Automations: Trading Blox for testing, NinjaTrader for trading, OCaml for programming, to name a few.

I’ve read extensively about the mysterious world that is the Forex market. Here are a few write-ups that I recommend for programmers and enthusiastic readers:

About the author

Rogelio Nicolas Mengual, Mexico
member since November 19, 2012
Rogelio is a versatile, positive, and self-motivated full-stack engineer with more than 10 years of work experience in many programming languages, frameworks, and platforms. He enjoys taking on new challenges, and constantly strives to learn new skills. [click to continue...]
Hiring? Meet the Top 10 Freelance Data Scientists for Hire in October 2016


I have always wanted to learn about this. Thanks! I studied a bit of market theory in college and learned about channel trading. I always thought that would be a good fit for algo trading since the strategy is recursive. Do you have any pointers on how to implement channel type of strategies (as opposed to Moving Average strategies)? I'm sure you know this, but some (old) research shows that Exponential MA strategies make more and even out perform buy and hold strategies without taking into account tax advantages.
Hi Rismay, thanks for commenting, about this: "Do you have any pointers on how to implement channel type of strategies (as opposed to Moving Average strategies)?" There are many channel indicators out there (ie: Donchian, IREGR, and many more); also you can code your own channel indicator, once you have that you can make the ExpertAdvisor to make decisions based on whatever indicator/s you are using. The values of the indicators are referenced as a reverse zero point array [oo..0] (ie: the most recent data would be in the position 0 of the indicator buffer). Andrew R. Young's book is a good starting point to understand how indicators work.
Awesome article thanks. Curious if you've engaged in the community? Seems like a great way to get your feet wet
Jubin Roy
Thanks for this awesome article
Simanas Venckauskas
Congrats Great post Rogelio! Just wanted to share my experience as well :) Almost every trading book states, that most traders fails because of psychological factor, when they make exceptions from their own strategies, so as an engineer my only tought was that this is a perfect place for a software solution to avoid human inntervention to the trading system once you decide to start using it. I have spend one entire year of my career just by programming, testing and optimizing with past data every single strategy I was able to find online and on variuos different trading books. And you know what - none of them had constant profitability. And after reading a lot of blog posts etc... I came to the conclusion: We are living in a world where everyone can write his own trading robot and big trading corporations, banks etc... they are constantly analyzing all the markets by using not just strategies developed by some trading gurus but also machine learning algorithms deployed on super computers, who tries to find at least some patterns on every market. And here is the result: Once some pattern comes true at least for some period of time it emediatly turns in to no pattern, because everybody on this game are looking for these patterns. Once you see some pattern you place an order to buy or sell, your order pushes the market to the opposite direction you want it to go at least for a bit. But do not be naieve, if you see the pattern most probably a lot of other traders with hudge investmens sees this pattern as well so this time they are doing the same and you all lose your money all together. Think of it before you decide to become a trader with software engineering background.
Hi Simanas, Thanks for the thoughtful comment. In a previous sketch of this article I described who the really smart players in this game are, and I mentioned the guys from Jane Street among others that play the role of middle-man and arbitrageurs in the market. We (The Editor, Charlie Marsh and Me) decided not to include that among another reflections that considered just that you are mentioning in this comment. All that being said, I like to believe that you can find an edge of the market if you use the correct tools and make the correct simulations using the proper variables. Thanks!
Thanks for commenting! I haven't engaged in that community; it looks awesome to start programming and reuse the code offered there!
Good article Rogelio, In further reading, why would you suggest Ocami for programming instead of MQL4 or MQL5 or "R" or whatever?
Stephan Unrau
I enjoyed this article as it is exactly the kinds of important big milestones I ran into. The project which started for a custom formula for several separate clients became a commercial product driven by user submissions. Now users can copy or sell their trades and copy trades from indicators in Meta Trader. It's called the Binary Options Auto Trader (BOAT for short) and only does Binary Options (2 results win or lose only).
Juan Manuel Ramallo
Can you try it whit horses..... Forex robot are like set up a ROBOT in front of roulette. ..
Bullion Invest - Invest $500 Return $350 daily for 50 days Program A: Receive Receive 70% daily for 50 days for every deposit made to the Standard Program. You will get your principal back immediately after your investment term is expired.. Minimum spend ids US$350 Program B Receive 200% daily for 20 days for every deposit made to the Premium Program. You will get your principal back immediately after your investment term is expired.. Minimum spend is US$3500 Program C: Receive 1000% daily for 5 days for every deposit made to the VIP Program. You will get your principal back immediately after your investment term is expired.. Minimum spend is US$20000 and maximum is US$150000 Invest Here Investment Insurance
The Quantopian does not provide any Forex data, right?? The site only provides stock and etf.
menino andrade
the pattern is in the mind of the trader a trader should identify the pattern rather than rely on the machine to identify the trend because the machine will fail as it will be late in identifying the trend (patterns) after all the machines were built by human brain. so the patter is in the brain . watching the screen how the rates behave. there are various patterns in different market bull markets ,bear mkts, range bound mkts.
Escaped Government Slave
Enjoy yourselves......your competition, 2500 state and local government retirement.....have $4 trillion under investment.....and pay zero taxes, because the government doesn't pay taxes....and have their inside people positioned in all the major trading houses and corporations.....worldwide.
Julia Smith
The forex market is the largest, most liquid market in the world with an average traded value that exceeds $1.9 trillion per day and includes all of the currencies in the world. <a href="">Success in Forex</a>
Shan Rose
I like their forex-copy system. You can copy the trades of successful traders and earn money even if you're newbie. And I'd like to say that their trading conditions are very suitable for me. Spreads are good, I choose 1:600 leverage, no requites <a href="">Dealing With Your Losses</a>
Matt Lindsay
Great article; pitched at a great level and I LOVE your diagrams! (any clue on how you produced them?) Simple question you might be able to answer: Do you know anyone that provides a streaming API for share prices of shares listed on LSE and US markets? Any advice appreciated thanks.
I have never seen an automated system that works. The best forex trading system would be semi automated with some manual controls.
Julia Smith
I have been trading with forex since 2010 and never encountered any issue. I made money once and requested withdrawal <a href="">Forex Trading strategies</a>
Hello You can try with penny stocks. You'll find more details on this web site <a href="">penny stocks trading</a> It's a good solution to earn extra money Bye
Interesting article - so Nico, have any of the trading systems you built for clients proved to be consistently profitable? I've toyed with developing one for a while but question whether or not FX price movement is predictable enough to make a consistent profit. Always makes me wonder why 'experts' write trading books - presumably if their systems & approaches actually worked they wouldn't have bothered to write the books!
Totally agree with your belief in the beauty of brain. And would like to suggest here that the use of machine is just to avoid the human limitations. The human body combination (brain, body, hands) cant possibly be as fast as the machine to trade in the market with a latency of under 100 milliseconds. The decision making of the wonderful brain is not independent of time. That's why we put most of the efforts of brain in developing and back testing strategies that normally we would use our brain for. No doubt there will be situations where manual approach might prove to be better than a machine decision. But its as likely as emotions making an impact on the decision making. With machines, the problem of emotions, and feelings do not hinder in making a rational decision. If your brain can think it, you can make a machine do it. No offence.
Martin Oeschler
StrategyQuant Professional is a <a href="">Computer Generated Forex Trading Strategies Platform</a> which is a powerful strategy developer platform that makes use of machine learning techniques and genetic programming for generating new trading systems for any market or timeframe. This trading software includes the most complex strategies performance analytics on the market. It even contains several powerful tools that allow you to test your strategies for robustness to avoid over optimization. The StrategyQuant automatically generates requires new trading strategies in fraction of the second. · It helps you to find new trading strategies that are not only unique but are also not obvious. · It reduces the time that is requires for building strategies from weeks and months to minutes. · It even helps you to improve the existing strategies.
Justin Springer
This is a good feature if you have any issues or need any advice with trading binary options. This also shows that the company attempts to add quality to their service. The trading platform is safe and secure and 100% web-based. Trade binary options in real time if you are a professional trader or an amateur. Get More Info :
Great information, thank you for share <a href="">My Best Trading System</a>
Great information <a href="">Best Trading System</a>
Alan Harper
It is very silly trading in Forex if you don’t have a reliable source of Forex signals as they take out the ‘gamble’ aspect of it and just make it a guaranteed thing you will make profit. After trading Forex for 6 years (to a consistent six figure yearly income I might add) I have tried many different sources of Forex signals but by far the best i have found is fxtradingmethod*com (it won’t let me comment with link so just turn the * into a dot) - Vlad is like a goldmine and will ensure you become a successful trader. Get onboard if you want pretty much guaranteed success from day one without trial & error. Just wanted to share my expertise with fellow traders!
Omar Hernandez Doüx
how do you state the code to define the right angle of the curve?
Serkan Kaptan
Algorithmic trader is good but so hard to use for small account owners but I find good solution, check this system maybe good someone else too. <a href="">best trading software</a>
awesome write up, even if its a couple years old..
This is actually a good information for those people who wanted to know the true meaning of this kind of thing especially if they are not aware of this especially if they will run a certain business. It's really suitable to be known by business people and for engineers.
AC Forex cilent’s service, platforms and funding supports have won the best records around the world.
Trades are mainly completed via computers, allowing retail traders to come into the market, real-time streaming prices have led to better transparency and the peculiarity between dealers and their most complicated customers has largely disappeared. As Forex trading algorithms helps in doing the analysis of currencies for currency trading. As MMF Solutions provide Best Forex tips for trading after doing complete analysis.
As far as my experience of Forex Trading is concerned, I didn’t find it that beneficial. I concur that Forex market is highly flexible but it is also more risky than the binary market. To read more about binary trading visit . Trading on binary options is far easy and convenient than the trading on currency pair.
Thanks for the interesting article..!! Understanding market behavior and strategy is the essential skill that every trader needs to possess to trade smartly. Backtesting is a great approach, which empowers traders to test out their strategies without risking a penny. Besides, backtesting a lot of things are present here which could help you in evaluating whether your strategy is correct or not.
Generally online trading whether its Forex or Options, they are considered as best to make money quickly. You generate earning when the currency you bet has enhanced in value and you will sell it at the suitable time. However, like any money making activity, such trading has also consumed risk. You can't start it without good planning and strategies. You need to learn several things highlighted by financial experts here and make a plan of action to achieve utmost gains from investment.
Great information thank you very much! Too bad I'm not using MT anymore because of bad support specially for developers. A friend recommended me vertexfx platform. Despite the fact that it saved us thousands of dollars for 3rd party features since they are built in with the platform, it saved us the VPS for the EAs we paid hundreds for! Their support were very fast and helpful and they assisted us in converting our strategies to VTL.
Tadas Talaikis
Why so much people so interested in those "algorithms" on MAs making them so undeservedly popular? There are numerous studies showing trading on moving average rules are trading on noise, meaning there is no real information (signal) in those. You can optimize it as much as you can, but when market regime changes, your "algorithm" fails. We see too much of them in FX world.
Elaine Gina
This is the very information blog that is the main thing a lot of interesting and useful. To know more about Forex Algorithmic Trading, you can visit Multi Management & Future Solutions.
Multi Management future Solutions is also the best online trading platform they provide , live equity signals Stock signals, profitable positional Stock Picks, SGX Stock market Signals with all Singapore market trading adviceand this are aliso provide signal in forex and comex
If You are looking for Signal provider with a lot of assets and currencies who will guarantee you safe trading, You will be pleased with FOREX TRENDY, Now they got a special bonus offer.Automated chart analysis :
Thank you for your great post. It's really very informative and really helpful. Please Keep posting. Thanks again. <a href=>23Traders Tutorial</a>
comments powered by Disqus
The #1 Blog for Engineers
Get the latest content first.
No spam. Just great engineering and design posts.
The #1 Blog for Engineers
Get the latest content first.
Thank you for subscribing!
You can edit your subscription preferences here.
Trending articles
Relevant technologies
About the author
Rogelio Nicolas Mengual
PHP Developer
Rogelio is a versatile, positive, and self-motivated full-stack engineer with more than 10 years of work experience in many programming languages, frameworks, and platforms. He enjoys taking on new challenges, and constantly strives to learn new skills.