How to Write a Trading Robot | A Guide for Beginners

Share this:
Editorial Note: While we adhere to strict Editorial Integrity, this post may contain references to products from our partners. Here's an explanation for How We Make Money. None of the data and information on this webpage constitutes investment advice according to our Disclaimer.

How to write a trading robot — a guide for beginners:

define your strategy;

choose your programming language;

learn the basics of MQL4;

write your code;

optimize your robot;

test your robot.

Programming your own algorithmic trading bot seems like science fiction, but with the right know-how it's entirely possible. Just imagine: while you sleep, an automated system diligently monitors markets for your predefined signals and executes lucrative opportunities around the clock. No more worrying about missing trades or letting emotions impede discipline. This guide provides the blueprint to turn this vision into reality.

We'll explain how to define a strategy, choose a programming language like MQL4, conduct backtesting and optimization, and launch the robot on a demo account for live market testing. For those committed to learning, this process can yield valuable programming skills while pursuing the goal of creating an effective algorithmic trading system.

Do you want to start automated trading Forex? Open an account on Roboforex!
58.42% of retail investor accounts lose money when trading CFDs with this provider.
  • How do I get historical market data for backtesting?

    You can download historical data from broker websites or paid data providers like Dukascopy.

  • How long does it take to develop a working robot?

    Time required varies greatly depending on experience and strategy complexity, but plan for weeks or months of testing.

  • What is the best way to optimize a robot's parameters?

    Using a walk-forward optimization approach where parameters are optimized on one data set and tested on another.

  • Is it easy to learn MQL4 from tutorials online?

    MQL4 basics like variables, indicators etc. are reasonably easy to pickup from online sources. Advanced coding requires hands-on practice.

What is a trading robot?

A trading robot or an expert advisor is a computer program that contains instructions in its code:

when to open a position (buy/sell);

when to correct/close the position;

what size is the position?

The following information can be used as inputs for forming the conditions of opening/closing/correcting a position:

Indicator and oscillator signals (volumes, RSI, MACD)

trader position data

other statistics

Below is a fragment of a trading robot, the code is written in C#.

Example of an excerpt of code for a trading robot

Example of an excerpt of code for a trading robot

This robot opens a long position if the fast SMA crosses the slow SMA upwards. When the fast SMA crosses the slow SMA downwards the robot closes a long position and opens a short position.

How to create a Forex trading robot

You should start by looking for ideas. For example:

  • you notice that the market often makes false breakdowns of round levels;

  • you found dependencies in the interaction of price and trading volumes;

  • you read a description of a trading strategy in a book.

If an idea can be described in the form of unambiguous instructions, it can be implemented in program code.

How to write code for a trading robot

The ball is in your court. Three options are available:

Option 1: Contact a specialist

Programmers who are ready to write a trading robot can be found on MQL5, freelancer sites.

The advantages:

  • the idea will be implemented quickly,

  • you can select the executor.

Option 2. Write the code independently

We recommend taking the second variant as a priority. You can write the simplest bot soon after you start learning. However, the value of the knowledge you get is much higher. There are plenty of training resources, and source codes on the web to figure out and become a developer of a trading robot code.

Advantages:

  • There are loads of ideas and you'll be able to implement them one by one such as create a bot from scratch, edit other robots, combine pieces of code. While writing code for one trading robot, you will get ideas for several other robots.

  • You don't have to share your idea with anyone.

  • You will know exactly how the robot works, and you will be able to understand why it works this way and not that way.

Option 3. Generate code

For example, the MetaTrader 4 terminal is so popular that there are special sites on the internet where you can generate simple trading robots in ex4 format specifically for MT4.

For example, here are some findings from Google's top (we are not responsible for the content of third-party sites):

  • eabuilderpro.com

  • Forexeadvisor.com

Creating a trading robot online for free

Creating a trading robot online for free

The creation of a trading robot, in this case, will be carried out according to the scheme:

  • 1

    Add indicators

  • 2

    Create condition

  • 3

    Add money management strategy

  • 4

    Export trading robot to a file

Advantages:

  • You will get your robot quickly if it can be implemented through the available functionality in the constructor

  • Free of charge, if not provided in the constructor

You can also be interested in information about Free Download Trading Bots For MT4 read the Traders Union article.

History Testing and Optimization

Ok, you got a robot in one of the 3 options outlined above; so what's next?

Next, you need to test (backtesting) and optimize the robot’s parameters.

Backtesting means testing the robot on historical data. That means you take the data for, say, 2017-2019 and look at the trades that the robot would have conducted by the rules in this period from the past. Then the data on the trades are processed and provided in the form of a report that shows:

  • how many trades were made;

  • how much the robot has earned/lost;

  • what is the ratio of earnings to losses;

  • other data allows you to assess the robot's quality.

Here’s ↓ how it looks in Metatrader 4.

Testing panel in MT4

Testing panel in MT4

To open the testing panel, press Ctrl+T.

Afterwards, you:

  • select the robot you will test. The robot's ex4 file should be located in the MQL4Experts folder. In the example above, we have selected a robot that trades on moving averages. It comes with the MT4 terminal.

  • select the trading pair. that you will test. For example, you may select EUR/USD.

  • select the testing accuracy (the more accurate it is, the longer it takes to test it).

  • select the period of testing. The more historical data is processed, the more reliable the result will be.

  • select the timeframe (5).

  • specify the spread value (difference between buy and sell price). Current means that the spread value will be loaded automatically.

  • select the parameters of the robot. For example, the periods of the moving averages used the amount of the initial deposit.

  • run the test.

The Results tab will show the trades made by the robot during testing.

As a result, if you have done everything correctly, with a high probability you will get the following picture on the Graph tab:

Example of testing a trading robot

Example of testing a trading robot

It means that the trading robot is slowly losing the deposit because:

  • the mathematical probability of profit = 50/50;

  • the final loss comes at the expense of the spread (commission) which is paid on each trade.

To try to correct this result, you can try "playing around" with moving average periods, timeframe, currency pairs. But all these "games" will not give the desired result over a long distance, most likely.

But it is possible that after numerous experiments with strategies and optimization (searching for the best settings of a trading robot) you will see an impressive curve like in the picture below.

Robot results

Robot results

The Report tab gives you the more detailed information.

Testing information

Testing information

In the example above, the report states that:

  • Test accuracy = 99.9% and test errors = 0. This is high confidence, it can be achieved by a quality database of prices.

  • By making 9395 trades, the robot managed to ramp up the initial $20,000 to $1.1 million between February 2019 and January 2023.

  • The relative drawdown = 40% is of course high. And in real conditions, it would seriously fray your nerves.

We'll come back to this million-dollar income robot later, but for now...

Sound advice. Conduct optimization so that you find parameters on one period (for example, on data for 2015-2018), and test them on another (on 2019-2023). This is called forward testing.

Expert opinion. Whatever testing you do, you can't rely on it 100%. The thing is that you will not be able to simulate real conditions completely and take into account slippages, changing spreads. The big problem is the detailing of data within one minute, which is the smallest timeframe in the MetaTrader environment. But how the price changes within a minute can determine whether a trade will close on a take or a stop. In fact, MT4 simplifies what happens within a minute to optimize the database and the terminal runs faster.

Timeframe testing

Timeframe testing

But a professional needs to achieve maximum accuracy, so he buys big tick databases for almost 20 years, which your broker will not provide you, most likely. "Smoothed" historical data from your broker can be the reason why the robot shows profits on history and suffers losses in real-time.

Testing on a demo account

Once your robot has undergone rigorous testing and optimization, there's no hurry to bet on the real account.

Try the demo version first. At least for a few months so that the Forex trading bot can "survive" some important news. You will also check:

The quality of your equipment and internet connection. Whether they will interfere with the robot working the way you intend it to work. To minimize the impact of this factor, it will be advisable to use a VPS service.

The quality of your code. Observing the demo, you will probably want to make some changes in your code to account for more market situations.

The quality of your broker. Use demo accounts from different brokers to see if your choice of broker affects your performance.

Let's assume that the trading robot was running a demo or paper trading account in real-time from January 1st till May 1st, executed 40 trades, and increased the deposit by 7.45% with a 6% drawdown.

Now run the robot in a historical test using data from those four months. You will see that the results are different. How could that be? Same robot/market/period, all the “input” data is identical, but the results from demo and backtesting are very likely to be different? Yes, that's normal. The main thing is to check whether this difference is critical. If the differences are too great, find the reason. The differences must be minimal, then your test results on the history for previous years can be considered reliable.

Launching on a real account

If you did everything correctly and got to this step, then objectively you are great. Because beginners are usually too zippy in putting hastily obtained trading robots into a real account just to make a profit as quickly as possible. Unfortunately, this method is fraught with losing deposits.

“Measure seven times, cut once” — is the proverb that should be followed by beginner traders.

The main thing is caution and protection of your capital. If you are trading a robot on a real account, start by devoting only a small amount of money to your early test trades.

Then see if the results on the real account deviate from the results obtained on the demo account and the history. Perhaps you will get a situation such as the following:

Here are the comparative results of the demo versus the real account.

Here are the comparative results of the demo versus the real account.

The two accounts — demo and real — from one reputable broker are running in parallel. But the demo account shows a profit, and the real account shows a loss, even though everything is identical there.

The is typical for scalper robots that make deals during impulse price movements. The duration of transactions is counted in seconds, and the quality of execution becomes critical. It is different between the real and demo accounts. So when developing your robot, strongly favor ideas that do not involve scalping trades.

How to Create Mt4 Robot - 6 Steps From Mt4 Developer

Trading robots, also known as expert advisors, are automated systems that execute trades on behalf of traders. These systems can be created using the popular MetaTrader 4 (MT4) platform, which offers powerful programming capabilities for developers. This article will guide you through the six steps to creating an MT4 robot.

Define Your Strategy

When creating an MT4 trading robot, defining your strategy is one of the most important steps. It involves determining which assets you’ll trade on and when - two key decisions that’ll significantly influence your robot's performance. To help you identify a strategy that’s best suited for you, consider both fundamental and technical analysis. Fundamental analysis involves examining economic, financial, and other data related to the asset, while technical analysis uses historical patterns and price movements to analyze market behavior.

Choose Your Programming Language

Once you have defined your strategy, you need to choose a programming language to create your robot. MT4 offers two languages for programming: MetaQuotes Language 4 (MQL4) and MetaQuotes Language 5 (MQL5). MQL4 is the most commonly used language for creating MT4 robots, and it’s relatively easy to learn, especially if you have a background in programming. MQL5, on the other hand, is more powerful, and you can use it to create robots for not just MT4 but MT5 platforms.

Learn the Basics of MQL4

To begin, familiarize yourself with the concept of variables and how they are used to store data or manipulate logical operations or statistical calculations; this will give you a good foundation for writing basic scripts. Once that is clear, delve into the syntax of each language so that you understand instructions withinTrade functions and how events such as orders or changes in price can trigger their execution. Finally, practice! MQL4 and 5 require a hands-on approach if you want to be able to make complex trading programs. The best way to gain experience is to try creating your own scripts and optimizing them as needed.

Write Your Code

Writing code for an MT4 robot requires synthesizing your trading strategy into executable commands the platform can understand. The code should encompass all aspects and parameters of your strategy, such as when to enter and exit trades, and any money management constraints you wish to incorporate. Use adjustable variables as you’ll have greater flexibility when optimizing the robot in the future.

Optimize Your Robot

Creating an MT4 trading robot optimized for success requires special care at each step of the way. From the initial idea or concept, to the blueprint for the algorithm and its implementation, every detail is important for achieving excellence in outcomes. You should clearly define performance metrics, lest the resulting robot performs less than desired.Next up is backtesting: it allows you to assess program performance in a simulated environment before venturing onto live markets.

Test Your Robot

Testing your robot is essential to ensuring that you have a functional program. The first thing to do is to backtest the robot against historical data. This allows you to see how well it would have performed if it had actually traded during those times and can help find any flaws in its strategy before going live.

You can then move onto demo-trading with a virtual account, where you’ll test your robot using current market data. This will give you greater insight into how the robot is likely to perform under real-time conditions and makes it much simpler to diagnose any issues that arise. Once satisfied with the results from your demo tests, you can use the same parameters in a real account and begin taking advantage of automated trading benefits. You can also be interested in information about Can ChatGPT Create A Forex Trading Bot? read the Traders Union article.

How much money can I earn?

Be realistic, don’t build castles in the sky and reckon that a simple strategy can enrich you. Here's the data from a reputable website that sells strategies developed by experts for asset management in the stock market. The Performance column shows yields, ranging from 6% to 18% per year. That's what's real.

Robot profitability

Robot profitability

Can your robot outperform that kind of profitability over the long term while showing a drawdown of no more than 20%?

Great. You can think about how to:

  • Use the robot by selling its protected copies to other traders

  • Build a long-term financial plan

  • Making investments

A frequent question — Can a trading robot run in automatic mode?

Theoretically, yes. But leaving it unattended is risky. It is advisable to test and optimize it on updated historical data as time passes so that the robot settings are relevant to the current market conditions. Markets change following global macroeconomic cycles.

Mistakes of algo traders

Let us finish this topic by giving a brief overview of the most common mistakes made by beginners who build trading robots:

  • Neophytes underestimate the concept: "Past results do not guarantee future profitability".

  • Rookies launch robots on real accounts without having solid proof of their profitability on history and demo.

  • Freshmen robot makers put their capital at risk by using unpredictable "secret" strategies. They are soi-disant "black boxes".

  • Newbie robot builders over-optimize their trading robots and thus simply "tweak" the settings.

  • They work with brokers on accounts that are not designed for algorithmic trading.

  • Many get addicted to scalper robots for a quick profit.

  • Novice robot designers leave robots on during news releases.

Another common mistake, the use of the martingale strategy, deserves separate paragraphs. Remember the fascinating picture above, where the robot is breaking $20k to $1.1m in 2.5 years? That's a martingale. After each unsuccessful trade, this martingale robot enters a new trade with increased size. The calculation is that the profits on subsequent trades will outweigh the disadvantages of the previous ones.

Fundamentally, the martingale is a negative progression system that involves increasing your position size following a loss.

The martingale has two disadvantages:

  • such a robot needs a large initial deposit to have enough liquidity in case the streak of unsuccessful trades drags on;

  • there is a risk that the deposit will be enough if the robot opens against a strong trend. In that case, the deposit will be drained.

You can, of course, count on a trading robot that uses a martingale to make enough profit before it gets wiped out... If you're willing to be responsible for that decision, that's your choice. We don't recommend playing with fire.

Best Forex brokers for trading with bots

RoboForex - best free bot builder

Open an account
Your capital is at risk.

RoboForex has one of the best Forex advisor builders for novice traders. The broker has developed a special platform for building and testing Forex EAs, which the traders without advanced knowledge of programming can use.

EA Wizard is a platform especially designed for beginners. It features tools for building trading robots. Traders with basic programming skills can develop an unlimited number of trading robots here. It is also easy to transfer your EA to MT4 after you finish.

R StocksTrader is an application designed for development of trading robots for stocks and other markets. Most of its functions are automated. The platform provides access to 12,000 trading instruments.

IC Markets - best for active traders

Open an account
Your capital is at risk.
Up to 75.93% of the broker’s non-professional clients incur losses when trading CFDs.

IC Markets is the biggest Forex broker by trading volume, it has one of the lowest spreads from 0.1 pips and the lowest fees starts from $3 per lot on the market. Because of its cutting-edge technology, direct access to liquidity, high trade volume, and absence of a dealing desk, the broker is able to provide tight spreads. So, this is one of the best options for bot builders.

For more than ten years, IC Markets Trading Company has been active in the forex market. The broker wants to give its clients the best possible market conditions, and in order to do so, they are constantly improving their tools and technology to give traders the most accurate analytical tools, updated trading platforms, and the best possible connection.

The Financial Services Authority of Seychelles, the Cyprus Securities and Exchange Commission, and the Australian Securities and Investments Commission all oversee IC Markets Global.

Summary

Trading on the exchange is not a cash cow that leads to easy money. Algo trading is no exception.

The greater the apparent profit, the higher the risks are, in fact.

If you want your experience with the development of Forex trading robots to be more valuable than disappointing, base your work on the information presented above. This article was written taking into account the recommendations of professional traders cooperating with Traders Union.

Team that worked on the article

Oleg Tkachenko
Author and expert at Traders Union

Oleg Tkachenko is an economic analyst and risk manager having more than 14 years of experience in working with systemically important banks, investment companies, and analytical platforms. He has been a Traders Union analyst since 2018. His primary specialties are analysis and prediction of price tendencies in the Forex, stock, commodity, and cryptocurrency markets, as well as the development of trading strategies and individual risk management systems. He also analyzes nonstandard investing markets and studies trading psychology.

Dr. BJ Johnson
Dr. BJ Johnson
Developmental English Editor

Dr. BJ Johnson is a PhD in English Language and an editor with over 15 years of experience. He earned his degree in English Language in the U.S and the UK. In 2020, Dr. Johnson joined the Traders Union team. Since then, he has created over 100 exclusive articles and edited over 300 articles of other authors.

The topics he covers include trading signals, cryptocurrencies, Forex brokers, stock brokers, expert advisors, binary options. He has also worked on the ratings of brokers and many other materials.

Dr. BJ Johnson’s motto: It always seems impossible until it’s done. You can do it.

Mirjan Hipolito
Cryptocurrency and stock expert

Mirjan Hipolito is a journalist and news editor at Traders Union. She is an expert crypto writer with five years of experience in the financial markets. Her specialties are daily market news, price predictions, and Initial Coin Offerings (ICO). Mirjan is a cryptocurrency and stock trader. This deep understanding of the finance sector allows her to create informative and engaging content that helps readers easily navigate the complexities of the crypto world.