как написать советник для mt4

Trading different financial markets requires different approaches. Therefore, strategies and trading algorithms based on them should be developed considering these factors.

Every trader needs to build their own effective strategy that will generate stable profits. Mastering this skill will be a solid base for creating a personal expert advisor.

In this article, we will give you an insight on how to write a trading algorithm for the MT4 platform as well as how to test, optimize, and set it up.

Find out more about expert advisors, their functions, types, and all pros and cons in our article about Forex eas.

EA for different markets

Trading bots for currency or stock markets require the use of different algorithms. Let’s figure out what is the main difference between the two markets.

One of the key differences is the instrument to trade. The stock market offers companies’ shares and derivatives whereas Forex is all about foreign currencies and currency pairs.

The amount of money needed to enter the market also differs. On Forex, you can start trading with as much as 1 US dollar. Meanwhile, the entry sum for the stock market starts at 1,000 dollars and above.

Some stock exchanges allow you to enter the market with 100 dollars. However, you need to keep in mind that high-yielding shares have a higher price.

на иллюстрации демонстрируются ключевые отличия между фондовым рынком и рынком Форекс

On Forex, the trading volume starts at 0.01 lots, meaning that you can divide the invested sum into smaller parts and trade with a fractional lot. By contrast, on the stock market, you can’t just buy a half or quarter of a share. You need to buy the whole share or several of them.

The potential return from the forex and stock markets is also different. When trading Forex, you can have a monthly gain of 10%-30%. Meanwhile, the return on the stock market is calculated per year, making it a 3% gain every month.

Such a high return on Forex is the result of higher leverage conditions. However, high leverage can magnify both profits and losses.

In addition, each market requires different trading platforms. Usually, FX platforms are more intuitive and easier to use even for beginners.

Platforms for trading stocks are more sophisticated, and it may take more time and effort to learn how to use them.

Basic features of stock trading

Below, we will discuss what strategies should be used to trade on the stock exchange market.

First of all, you need to keep in mind that stock markets have specific daily trading hours which means they do not operate around the clock.

However, given that stock exchanges operate in different parts of the world, traders can enter global exchanges day and night, taking advantage of different time zones.

When buying a stock, investors actually get a share in the company. This type of ownership allows investors to receive distributed profit in the form of dividends.

Besides, equities are rarely used for active trading. The most popular strategy for shares is called “buy and hold” which makes them a perfect instrument for investing.

на изображении демонстрируются алгоритм инвестирования средств в ценные бумаги

This is typically a long-term investment that is supposed to bring a return thanks to a steady upside dynamic of shares. As a rule, equities gain value slowly and may even decline in price.

Therefore, it is crucial to build a balanced investment portfolio. For this, you should pay attention to those shares that have high upside potential.

In addition, you need to constantly monitor news regarding the companies you picked, especially focusing on their earnings reports. This data can significantly impact the value of shares and move them either up or down.

Basic features of Forex trading

Importantly, currencies and fluctuations in their rates are not considered assets in their traditional meaning. So, these trading instruments should not be used as long-term investments.

Unlike the stock market, Forex is open 24 hours 5 days a week and has no centralized location. At the same time, its trading volume is much higher than that of the stock exchange.

This is why currencies are considered instruments with higher liquidity compared to equities. This makes Forex so appealing to many traders worldwide.

The stocks of some major companies can also be called highly liquid as they are easy to buy and sell and can be traded in the short term. However, less popular shares are not suitable for trading.

To predict a trajectory of a currency pair, a trader needs to analyze several factors, including global macroeconomic data and the economic state of separate countries.

The leverage available for forex trading can be up to 1:500, which allows users to get hefty profits from a winning trade. On the other hand, higher leverage means more risks.

на изображении демонстрируются воплощение краткосрочной торговой стратегии, то есть открытия нескольких коротких сделок в течение одного дня

Depending on personality traits and preferences, traders can choose strategies that fit them best. As for FX trading, scalping is the most widely used strategy along with intraday trading. Medium-term and long-term strategies are less popular on Forex.

Expert Advisors for stock market

When creating a trading robot on MT4, defining your strategy is one of the most important steps.

Since currency and stock markets have their specific features, so do the trading strategies that apply to them. Let’s look at what trading algorithms are best to use in each market.

The preferred strategy for the stock market is investing, that is, buying securities and holding them for long periods of time.

An important factor to consider when buying stocks is the right choice of shares with high upside potential. Beginners may find it difficult to navigate numerous companies and their stocks traded on the exchange.

One way out is to seek advice from an investment counselor, an individual or organization that specializes in the stock market and provides advice to retail investors.

Another option is a robo-advisor, an automated investment service or application that picks shares for the user’s investment portfolio.

на изображении демонстрируется принцип работы робоэдвайзера по подбору активов для составления инвестиционного портфеля

The program operates using a special algorithm and parameters defined by an investor.

Apart from searching for suitable stocks, robo-advisors can also calculate the expected return of the portfolio: they present a list of several portfolios with various investment terms and profitability rates.

What is more, these algorithms can manage your portfolio for you by buying or selling assets to keep the balance.

Expert Advisors for Forex market

Forex trading can be very exhausting as the currency market is open around the clock. In the pursuit of huge profits, some traders work non-stop.

This can finally lead to fatigue and lack of focus, resulting in more mistakes and trading losses.

Expert advisors and trading robots were created to make the life of a trader easier. They do all the routine work, leaving more time for other important things.

Advisors based on medium- or long-term strategies are not the best option for FX trading. In this case, the frequency of trading is very low. On the bright side, you have enough time to analyze the market and open a position in no rush.

на изображении демонстрируется работа советника, основанная на двух индикаторах: MACD и Moving Average

When trading intraday or scalping, the time for analysis and decision-making is very limited. And this is when trading advisors come in handy.

Computer algorithms can analyze the market and show results in a matter of seconds, far outpacing the human brain.

However, some professional traders do not fully trust trading advisors. They rely on them for analysis and trading signals but prefer to make trading decisions themselves.

Should you download EA or create one yourself?

A trader who already has a working strategy may start looking into how to create their own trading advisor for MT4. Indeed, a tailor-made robot based on personal preferences of a trader promises to be more effective.

There are several ways to find yourself a perfect trading advisor:

1. Download a ready-made trading bot. There are plenty of expert advisors available online. Just download it, set it up, and start trading.

However, please keep in mind that none of the existing programs will be 100% perfect for a particular trader. Besides, free trading robots are often useless, outdated, or represent a demo version of a paid advisor.

2. Order your personal expert advisor that will run on a specific trading strategy.

However, it might be difficult to find a good developer. If a programmer knows nothing about trading, he/she may not understand the task in full and may miss some nuances. What is worse, there is a big risk of being scammed.

3. Create an expert advisor yourself. This is one of the most reliable yet challenging options. On the one hand, you know exactly what you want to see in a trading robot and which features are less important.

On the other hand, you will need some coding skills to write a trading program. See some recommendations below.

How to create EA for MT4

Sometimes we need to take up new roles to explore something new.

The same is true about creating a trading advisor for MT4. Instead of trying hard to explain your ideal trading program to a developer, take some time and explore the matter yourself.

Nowadays, trading platforms offer traders all the necessary tools for developing automated advisors.

As for MetaTrader, it has a special MetaEditor section. This editor features ready-made templates for creating trading assistants along with built-in guidelines and training resources.

на иллюстрации демонстрируется, как выглядит рабочее окно редактора MetaEditor торговой платформы МетаТрейдер

Expert advisors for MT4 are written in a special programming language - MetaQuotes Language 4 (MQL4). MQL4 syntax is similar to the syntax of C++ and this makes it easy to work with.

This language allows a trader to build a program with various useful functions, including market analysis, trades management, technical indicators, and so on.

In addition to this, MetaEditor has a guide with all the functions in MQL4 and their description.

Step-by-step guide to writing a trading robot

Now that you have a general understanding of how to create an MT4 trading robot, let’s dive deeper into the topic. Below are some simple steps to start off with creating your EA.

  1. The first stage of preparation includes establishing the main principles of the trading system. Before moving on with an EA, a trader needs to have a viable strategy that has proven to be effective in manual trading.
  2. Next, it is necessary to learn the functions of MetaEditor and study the basics of the MQL4 programming language. The section offers ready-made templates that can be used for creating a program as well as guidelines and training materials.
  3. The main stage of the EA development is code writing. Make sure that the code is correct and functions properly.
  4. The simpler the trading program, the easier the code. A more complex trading robot will require more lines of code, meaning it might be difficult to configure in the future.
  5. Then comes code debugging, the process of finding problems and fixing them. This stage can be more time-consuming than the whole process of code writing.
  6. Backtesting is the last important part of EA creation. It is done to make sure that the automated trading with the new EA shows the same or better results compared to manual trading. Let’s look at this stage in more detail.

EA backtesting and optimization

Backtesting is a crucial step that comes before running an expert advisor in real time.

на изображении демонстрируется, как выглядит тестер стратегий на платформе МетаТрейдер и отчет о проведенном тестировании

Every trading platform, including MetaTrader4, has a built-in strategy tester. To test your strategy, you need to set the following parameters:

  1. Choose your expert advisor for MT4 from the list;
  2. Choose an asset and a time frame;
  3. Set the testing mode;
  4. Set the time period required for testing.

Backtesting should be done on a demo account.

It is important to note that MT4 does not save quotes. So, to ensure high-accuracy testing and bring it closer to real trading conditions, you should use tick quotes that are downloaded separately.

To get a better understanding of the EA efficiency, you need to test it several times applying different parameters such as lots, stop levels, and so on.

No matter whether you created an EA yourself or bought it, a trading robot may become outdated with time, meaning it may work incorrectly.

In this case, optimization is a useful tool as it helps reconfigure the program and adjust it to new market conditions. This needs to be done from time to time to “refresh” an expert advisor.

In the case of custom or purchased advisors, such updates can be bought separately when available. If a trading bot was created by a trader, then they need to keep it updated themselves.

Final thoughts

In this article, we have discussed the key differences between trading strategies in various financial markets. Given that the FX and stock markets differ greatly, they require different trading approaches.

In the stock market, the best strategy is investing, or holding assets for the long term. On the contrary, the FX market implies active trading such as intraday strategy or scalping.

Both markets can be traded with the help of expert advisors. For stock trading, use robo-advisors that will help you build a balanced portfolio.

As for the forex market, trading robots can be much more efficient compared to humans. FX trading robots are mainly used in short-term trading strategies as they can analyze the market and make decisions in a matter of seconds.

Every trader needs to develop their own trading strategy to maximize trading results. It will serve as a basis for a personal trading advisor for MT4 in the future.

Writing an EA for MT4 is easy as the platform offers all the necessary tools for creating your trading program. On MT4, MetaEditor is used for this. It features ready-made templates and useful tips to create a trading bot on your own.

Debugging is the next, more difficult stage where you need to detect errors and fix them. When the program is ready, it needs to be tested with the strategy tester so that you can find the best parameters for the EA.

You may also like:


Best Forex advisors


Profitable Forex advisors


Arrow indicator advisor


WOC adviser


Forex expert advisors reviews


Creating expert advisor


Pair trading advisor