Writing an article on "How to write a TOR for a trading robot" - page 7

 
Andrey F. Zelinsky:

Flowcharting is the most useless, time-consuming and practically unrealizable part of ToR.

To understand this - you can conduct a small and very simple experiment - Freelance service developers should be given a task: "Make a flowchart for drawing MA indicator" - and then evaluate by two criteria: 1) correctness and 2) understandability.

Once it helped me a lot - when I couldn't manage it in my head...

 
Artyom Trishkin:

It really helped me out once - when I couldn't get my head around it...

You just said something like this:"My flowchart has helped me a lot as a developer". Note, for your flowchart a third person who will read and work with your flowchart was not originally intended.

In this thread we are discussing "How to create a TOR for a trading robot".

It's not clear to me for whom and with what goals and objectives this article is written.

Because there are different degrees of detail and from this detail derive: goals/objectives/outcome -- i.e. to talk about TOR -- you must first understand a) what the customer expects and requires from the developer and b) what is expected and required from the customer.

When we talk about a flowchart, it means that the client clearly understands the event model, understands and is able to not only show the required organization of the program, but also be able to check whether everything is implemented as it should be in terms of code. In this case, the customer needs more of a coder. And in this case, it is the customer who is fully responsible for everything, including the correctness of his structure.

This is one scheme. What percentage of orders are in this scenario?

Read the layout of the article:

Rashid Umarov:

A poorly drafted TOR or its actual absence most often indicates that the rules of the trading system are not formulated, they simply do not exist. What the customer calls a trading system, in fact, is just an idea. You can not start working under such conditions, because very soon in the process of programming the algorithm some unrecorded nuances will emerge or simply the lack of an algorithm for certain situations in the market. In this case, the programmer actually starts to think out the options instead of the Client.

Correctly written except for one thing -- the vast majority of tasks are started, executed and completed -- in a fuzzy problem statement. The failure rate due to fuzzy TORs -- easy to check with arbitration agreements. I think it is no more than 5-10%.

And if we talk about the recommendations for the TOR for the vast majority of customers -- in such a TOR -- the recommendation to make a flowchart is reasonable?

 

Current version of the article

What you need to order a trading robot

Trading robots are programs that execute the algorithms embedded in them. Algorithms are a set of actions that must be performed in the event of the occurrence of an event. For example, the most common task in algorithmic trading is the definition of the "New bar" event , upon the appearance of which the robot checks for the appearance of trading signals and performs the necessary actions on them.

But before writing or ordering a trading robot, it is necessary to have a trading system with clear rules for determining favorable moments for making transactions. The development of any, even the most complex, trading system always starts with basic things, namely, with the development of trading signals for buying and selling. Next, you can add various follow-up and closing options to it.

You do not need to spend years behind the monitor of the trading terminal to develop your trading strategy. There are now hundreds of proven ideas published on the Internet and in books that you can try. And even if you are not completely confident in your programming skills, this is not an obstacle. The Freelance service will help you find the right developer and securely pay for the work done.

But before jumping into the fascinating element of algorithmic trading, we recommend that you read useful articles on the topic:

Why is it important to have a good Terms of Reference?

When ordering or developing an Expert Advisor, it is necessary to formulate technical requirements for it - what tasks it should solve, in what conditions it will be operated, what will happen in emergency situations, what kind of control it needs. Trading robots are programs and must work clearly in accordance with the underlying logic. But before programming the necessary algorithm of actions, it must also be clearly described.

The description of the trading strategy must be issued in the form of a Terms of Reference. And the better and clearer it will be, the less misunderstanding will be between you, as a customer, and the programmer, as the executor of your Order.

The most important thing in the Terms of Reference is the presence of formal unambiguous Trading Rules. Even if you are not going to order an expert on the side, but want to write it yourself, start by developing these rules for yourself. Make a Terms of Reference and be sure to include items on testing/optimizing the Expert Advisor. Also add hypotheses to test the quality of your trading strategy - what criteria will you use to select the optimal parameters, why do you consider these criteria important.

Include all the steps for creating a trading robot in the Terms of Reference - this will help to understand the essence of the algorithm not only for the performer, but also for you after weeks, months or years. Remember, algorithmic trading is not a hobby, but the same monotonous research path, during which it is necessary to document the stages passed. For myself, more than for a programmer who will write a robot for you.

Develop the skills of a bureaucrat who likes to sort things out. You will definitely need this. Yes, and programmers love clear-cut orders.

What should be in the terms of reference

trade idea

For a quick introduction to the essence of a trading strategy, dedicate the first paragraph of your Technical Order to the idea / hypothesis that it contains. For example: "If the price approaches the resistance level twice and rolls back each time, then the third time, as a rule, it breaks through it." Here you can attach a chart with plotted resistance/support lines, superimposed indicators and signatures that illustrate the situation. To describe the idea, it is not required to give specific numbers or calculation algorithms - at this stage, it is not required to explain how we determine:

  • resistance level,
  • level breakdown,
  • the concept of "generally".

A small level of abstraction at the initial stage will allow you to focus on the idea itself, and not on the technical details. This method allows you to subsequently generate many more varieties of your trading strategy - you will simply replace one strategy block with another, one indicator with another, add or replace filters. At the same time, the idea itself will not change, only the names and values of the input parameters of your trading robot will change.

Further, it is necessary to give a description of all the terms that are used in the description of the idea. If the trend is important for the strategy, give a clear description of how it will be determined - on the basis of which indicator, how the direction and strength of the trend will be determined. The numerical characteristics of these definitions will form the basis of the input parameters of the Expert Advisor, and it is them that you will then optimize in the strategy tester. So name the first section of your Terms of Reference - Trade idea.

Terms

To describe the terms, we recommend creating a separate section of the Terms of Reference - Terms. In it, a separate paragraph is written for each term, the terms themselves are written in bold to highlight the key concept of your trading strategy. If necessary, add an illustration to the description of the term, in which you need to show the most necessary for understanding.

Trading Signals

Next, you are ready to compile the third most important section - Trading Signals - which describes under what conditions, market conditions, and indicator readings, a purchase occurs. To describe each condition necessary to generate a buy signal, it is necessary to single out a numerical parameter, on which the appearance of a signal depends. For example, for a moving average , this would be the smoothing type and period. These important parameters are taken into the input parameters of the future Expert Advisor. Describe separately the conditions for the sale, even if they are simply the opposite of the conditions for the purchase - sometimes subtleties come out that the programmer can understand differently from you. For example, for a purchase, the condition "Indicator> 0" is set - what to write for a sale? "Score<0" or "Score<=0"?

Even the simplest trading idea very quickly begins to acquire additional conditions and filters that confirm the presence of a trading signal or vice versa - prohibit a deal. Therefore, it is important to make explanatory screenshots for each market situation, which visually show the necessary indicators and setups. This will allow you to quickly deal with the situation when your adviser missed a seemingly obvious trading signal or suddenly made a deal at the wrong time.

Screenshots and flowcharts

There are a lot of free and handy programs on the Internet for creating screenshots and flowcharts. A small selection of tips for working with them is given in the article How to draw up a Terms of Reference when ordering an indicator . There you will also find tips on ordering an indicator that shows with arrows on the chart the moments when buy and sell signals appear. Such an indicator, which works separately from the adviser, makes it easier to check and control the operation of the trading robot both online and during visual testing.

Lifetime of signals/orders/positions

The second important part of the trading strategy is exiting an open position and deleting pending orders. In addition, the trading signals themselves can also be canceled by time or by the occurrence of some events. It is also necessary to clearly describe, as for Trading signals, under what conditions the purchase / sale will be closed, the placed order will be canceled, when the signal itself will be canceled.

Maintenance of open positions and pending orders

If your trading strategy requires setting StopLoss and TakeProfit levels, please provide a calculation algorithm. If it is necessary to flexibly pull up/move these levels, it is also necessary to describe the conditions for such operations. SL/TP levels can be modified both at the opening of a new bar and at each tick. It is necessary to explicitly indicate this moment in the Terms of Reference and understand the difference in the modes of testing trading strategies. We recommend that you read the article Testing trading strategies on real ticks .

Where can I get the Terms of Reference if you can’t compose it yourself

A poorly drawn up Terms of Reference or its actual absence most often indicates that the rules of the trading system are not formulated, they simply do not exist. What in this case the Customer calls a trading system, in fact, as a rule, is just an idea. It is impossible to start work under such conditions, because very soon unaccounted for nuances or simply the absence of an algorithm in certain market situations will come out in the process of programming the algorithm. In this case, the programmer actually begins to come up with options instead of the Customer.

As a result, the Contractor may, at his own peril and risk, complete the work and issue a trading robot to the Customer. But in this case, in addition to wasting time discussing each new issue in an unclear TOR, there is also the possibility of the work getting into Arbitration. Because when accepting and checking such work, the Customer suddenly discovers that transactions are not being made as he expected, but could not describe. And of course, in this case, he will blame the Contractor for violating certain points of the Terms of Reference and incorrectly programming the robot. Arbitration in such cases quickly understands the difference in the competence of both parties and makes its decision based on the Terms of Reference attached to the order. According to the Freelance Rules , no correspondence on the side before and during the execution of the Order is not taken into account:

When considering the subject of the dispute in the Arbitration, only the Terms of Reference serve as the basis for making a decision.

In life, this option is also possible: you have strict trading rules, but for some reason you cannot draw up the Terms of Reference yourself. For example, they are not sure how to describe certain things correctly or they need the help of a specialist in mathematics, neural networks, machine learning, programming, and so on. In this case, you can order the creation of the Terms of Reference also in Freelance, for this, the categories "Programming Consulting" or "Other" are suitable.

Choose one of these two categories, name it "Creating a TOR for ordering a trading robot" and indicate the initial cost of the work, as you imagine. An experienced trading system developer will help you correctly formulate the Rules of your strategy so that they are understandable to another programmer. At the same time, you should be able to work with charts, indicators, and graphical objects in order to show the setups of your trading signals using screenshots.

The programmer will understand your trading system and help you write a description of the trading algorithm, if possible. If you can't formulate some concepts on your own (for example, "impulse" or "rebound from the level"), he can give you ready-made ideas based on his experience. As a rule, any situation in the market can be described logically (and then programmatically) with some freedom of interpretation. And this variation can always be expressed by a certain parameter, which you will then optimize in your Expert Advisor.

There are no ideal patterns, since the market, on the one hand, does not repeat itself, and on the other hand, similar situations can always be found in history. The result of your joint work should be a ready Terms of Reference for ordering a trading robot according to your strategy.

What terms to use

As a rule, in a trading system there are several basic important concepts or terms that describe the state of the market or the nature of the price movement. Even if it seems to you that you are using a generally accepted and simple concept, it is better to describe it clearly. For each term, make one paragraph of description.

For example, according to Bill Williams, an uptrend is when all three Alligator lines are arranged in this order from bottom to top: Blue, Red, Green.


Another classic definition of an uptrend - from Larry Williams - when each new peak is higher than the previous one, and each new bottom is not lower than the previous one.


In the description of the terms, you can use screenshots of the charts, they will not interfere. In the terms of reference itself, highlight the terms in bold - let the performer pay attention to them and ask a question if something is not clear.

When using a certain term in the description of a strategy, it is impossible to refer the Contractor to other sources (websites, books, forums, etc.), arguing that this is already well known. Everything should be described here and now, no "I'll explain later on Skype" is allowed. It will take you no more than half an hour to write down all the terms in the TOR, but then it will save you time that you will spend on correcting errors due to misunderstandings.

What to write in a job description in Freelance

When creating a job, describe in a few paragraphs the general essence of your trade idea so that potential performers understand what you need. The job description does not need to disclose the rules of the trading system or provide details about the indicators used.

Description might look like this:

Write an Expert Advisor for trading on trend reversals. Reversal signals will be Price Action patterns. To determine the trend, the ADX, Alligator and MACD indicators will be used - the choice of the indicator is set by the input parameters of the adviser.

General idea of a trading strategy

Here you can specify on which instruments the robot will trade, whether it is trading with the trend, how it is determined and on what timeframe. If we trade with the trend, then how does the entry occur - on a rollback, on breaking through new extremes, and so on.

By and large, there are only two trading strategies in the financial markets: to continue moving and to return to the average. Your idea should relate to one of these two strategies and explain how you will open trades - in the market, after confirmation, or at a better price.

Description of the setup for waiting for a Signal

... it is necessary to form a flat with a subsequent breakout / or wait for the end of the European session and receive signals only in the direction of its movement

Signal Description

... Technical parameters of the description - trend / pullback / breakdown - everything is strictly formalized

It is better to debug Buy and Sell signals separately first

It would be better if the adviser puts labels / signal objects on the chart

It is better if signal indicators are made separately

Signal lifetime

... how long the signal is valid - in bars / hours / until the end of the session / day

Placing orders and opening positions

... are there any features, for example, we don’t set SL / TP right away,

or how many attempts we make to enter the market,

or setting different oredermagic/ordercomment depending on time/setup/pattern

something else

Maintenance of a trading position/order

... is there a trailing stop or not

when turn on TS

do we move pending orders behind/against the price

track the current profit/loss on an open position

something else

Cancellation of an order and closing a position

... delete orders by time/number of bars/end of period/appearance of opposite signal/loss of setup

... close the position by time/number of bars/end of the period/accumulated profit/appearance of the opposite signal/setup

something else

Lot calculation for placing an order

.... from balance

fixed

from accumulated profit

based on the results of the last N trades

from risk (distance SL)

something else

Handling trading errors and environment state

... detailed logs when sending trade orders

terminal/connect/server restart processing

feedback via messengers/email

The difference between trading at the opening of the bar and inside the bar

... signals can disappear and appear during the life of the bar

Tick/scalping strategies

... you need to have a good idea of what it is, the less TakeProfit/StopLoss in points, the more critical the strategy is to spreads/commissions/network delays/quality of available history/speed of the robot itself.

Any deterioration in conditions can kill the strategy

Grids, martingales, averaging and the downside of these improvements

... What are they, why are they popular, and how much can they help temporarily stretch the strategy. The risk increases, although it may lengthen the life of a bad strategy

What to look for when choosing a contractor

... substantive questions

Doesn't pretend to impress

Gives clear deadlines

Indicates unclear places in the TOR immediately, and not after 2 months of discussion

A good programmer values his time and yours - that's why he loves a well-developed consistent TOR

What a programmer can't do for you

Turn a losing strategy into a profitable robot

Optimize and identify any weaknesses

Write a program without errors - they will still be. Finding them and describing them in an understandable way is your task.


 

The current version of the article, the section Description of the setup for waiting for a Signal continued and further

What you need to order a trading robot

Trading robots are programs that execute the algorithms embedded in them. Algorithms are a set of actions that must be performed in the event of the occurrence of an event. For example, the most common task in algorithmic trading is the definition of the "New bar" event , upon the appearance of which the robot checks for the appearance of trading signals and performs the necessary actions on them.

But before writing or ordering a trading robot, it is necessary to have a trading system with clear rules for determining favorable moments for making transactions. The development of any, even the most complex, trading system always starts with basic things, namely, with the development of trading signals for buying and selling. Next, you can add various follow-up and closing options to it.

You do not need to spend years behind the monitor of the trading terminal to develop your trading strategy. There are now hundreds of proven ideas published on the Internet and in books that you can try. And even if you are not completely confident in your programming skills, this is not an obstacle. The Freelance service will help you find the right developer and securely pay for the work done.

But before jumping into the fascinating element of algorithmic trading, we recommend that you read useful articles on the topic:

Why is it important to have a good Terms of Reference?

When ordering or developing an Expert Advisor, it is necessary to formulate technical requirements for it - what tasks it should solve, in what conditions it will be operated, what will happen in emergency situations, what kind of control it needs. Trading robots are programs and must work clearly in accordance with the underlying logic. But before programming the necessary algorithm of actions, it must also be clearly described.

The description of the trading strategy must be issued in the form of a Terms of Reference. And the more detailed it is, the less misunderstanding will be between you, as a customer, and the programmer, as the executor of your Order.

The most important thing in the Terms of Reference is the existence of unambiguous formal Trading Rules. Even if you are not going to order an expert on the side, but want to write it yourself, start by developing these rules for yourself. Make a Terms of Reference and be sure to include items on testing/optimizing the Expert Advisor. Also add hypotheses, on the basis of which you will check the quality and stability of your trading strategy - what criteria will you use to select the optimal parameters, why do you consider these criteria important.

Include all the steps for creating a trading robot in the Terms of Reference - this will help to understand the essence of the algorithm not only for the performer, but also for you after weeks, months or years. Remember, algorithmic trading is not a hobby, but the same monotonous research path, during which it is necessary to document the stages passed. And you need this even more than for a programmer who will write a robot for you.

Develop the skills of a bureaucrat who likes to sort things out. A development diary of each trading system is sure to come in handy when you want to test a new idea. Yes, and programmers love clear-cut orders.

Examples of Terms of Reference

Let's give examples of how Technical Specifications for Expert Advisors included in the delivery of the MetaTrader 5 terminal could be designed.


What should be in the terms of reference

trade idea

In the first section of your Terms of Reference, describe the general idea behind your trading strategy. For example: "If the price approaches the resistance level twice and rolls back each time, then the third time, as a rule, it breaks through it." Here you can attach a chart with plotted resistance / support lines, indicators and explanatory captions. To describe the idea, you do not need to go into specific numbers or calculation algorithms - in this example, you do not need to immediately explain how we determine:

  • resistance level,
  • level breakdown,
  • the concept of "generally".

A small level of abstraction at the initial stage will allow you to focus on the idea itself, and not on the technical details. This method allows you to subsequently generate many more varieties of your trading strategy - you will simply replace one strategy block with another, one indicator with another, add or replace filters. At the same time, the idea itself will not change, only the names and values of the input parameters of your trading robot will change.

Further, it is necessary to give a description of all the terms that are used in the description of the idea. If the trend is important for the strategy, give a clear definition - on the basis of which indicator the direction and strength of the trend will be determined. The numerical characteristics of these definitions will form the basis of the input parameters of the Expert Advisor, and it is them that you will then optimize in the strategy tester. So name the first section of your Terms of Reference - Trade idea.

Terms

To describe the terms, we recommend creating a separate section of the Terms of Reference - Terms. In it, a separate paragraph is written for each term, the terms themselves are written in bold to highlight the key concept of your trading strategy. If necessary, add an illustration to the description of the term, in which you need to show the most necessary for understanding. The input parameters of the future Expert Advisor can be italicized.

Trading Signals

The next section of the Terms of Reference is the third most important section - Trading Signals - which describes under what conditions, market conditions, and indicator readings, a purchase occurs. To describe each condition necessary to generate a buy signal, it is necessary to single out a numerical parameter, on which the appearance of a signal depends. For example, for a moving average , this would be the smoothing type and period. These important parameters are taken into the input parameters of the future Expert Advisor. The input parameters of the future Expert Advisor can be italicized.

Describe separately the conditions for the sale, even if they are simply the opposite of the conditions for the purchase - sometimes subtleties come out that the programmer can understand differently from you. For example, for a purchase, the condition "Indicator> 0" is set - what to write for a sale? "Score<0" or "Score<=0"?

Even the simplest trading idea very quickly begins to acquire additional conditions and filters that confirm the trading signal or, on the contrary, cancel it. Therefore, it is important to make explanatory screenshots for each market situation, in which to visually show the indicators and setups used. This will allow you to quickly deal with the situation when your adviser missed a seemingly obvious trading signal or suddenly made a deal at the wrong time.

Screenshots and flowcharts

There are a lot of free and handy programs on the Internet for creating screenshots and flowcharts. A small selection of tips for working with them is given in the article How to draw up a Terms of Reference when ordering an indicator . There you will also find tips on ordering an indicator that shows with arrows on the chart the moments when buy and sell signals appear. Such an indicator, which works separately from the adviser, makes it easier to check and control the operation of the trading robot both online and during visual testing.

Lifetime of signals/orders/positions

The second important part of the trading strategy is exiting an open position and deleting pending orders. In addition, the trading signals themselves can also be canceled in time or when some events occur. It is necessary, as for Trading signals, to describe - under what conditions the purchase / sale will be closed, the placed order will be removed, when the signal itself will be canceled.

Maintenance of open positions and pending orders

If your trading strategy uses closing by StopLoss and TakeProfit levels, please give the calculation algorithm. For flexible pulling/moving of these levels, describe the conditions and the trailing algorithm. SL/TP levels can be modified both at the opening of a new bar and at each tick. It is necessary to explicitly indicate this point in the Terms of Reference and understand the difference between the modes of testing trading strategies. Be sure to read the article Testing trading strategies on real ticks .

Where can I get the Terms of Reference if you can’t compose it yourself

A poorly drawn up Terms of Reference or its actual absence most often indicates that the rules of the trading system are not formulated, they simply do not exist. What in this case the Customer calls a trading system is actually just an idea. It is impossible to start work under such conditions, because very soon unaccounted for nuances or the absence of an algorithm for unforeseen situations on the market will come out in the process of writing code. In this case, the programmer actually begins to come up with options instead of the Customer.

As a result, the Contractor may, at his own peril and risk, complete the work and issue a trading robot to the Customer. But this is accompanied by a loss of time to discuss each new issue, and the likelihood of getting the work to Arbitration increases. Because when accepting and checking the work performed, the Customer suddenly discovers that transactions are not being made as he expected, he just could not describe it correctly. And of course, the Customer will blame the Contractor in this case for violating certain points of the Terms of Reference and incorrectly programming the robot. Arbitration in such cases quickly understands the difference in the competence of both parties and makes its decision based on the Terms of Reference attached to the order. According to the Freelance Rules , no correspondence on the side when considering disputable situations is not taken into account:

When considering the subject of the dispute in the Arbitration, only the Terms of Reference serve as the basis for making a decision.

In life, this option is also possible: you have strict trading rules, but for some reason you cannot draw up the Terms of Reference yourself. For example, you are not sure how to describe certain things correctly, or you need the help of a specialist in mathematics, neural networks, machine learning, programming, and so on. In this case, you can also order the creation of a Terms of Reference, in Freelance there are such categories as "Programming Consulting" and "Other" for this.

Choose one of these two categories, name the work "Creating a TOR for ordering a trading robot" and indicate the initial cost of the work, as you imagine. An experienced trading system developer will help you correctly formulate the Rules of your strategy so that they are understandable to another programmer. At the same time, you should be able to work with charts, indicators, and graphical objects in order to show the setups of your trading signals using screenshots.

The programmer will understand your trading system and help you write a description of the trading algorithm, if possible. If you can't formulate some concepts on your own (for example, "impulse" or "rebound from the level"), he can give you ready-made ideas based on his experience. As a rule, any market situation can be described logically (and then programmatically) with some simple model with variation parameters. And this variation can be expressed by a certain parameter, which you will then optimize in your Expert Advisor.

There are no ideal patterns, since the market, on the one hand, does not repeat itself, and on the other hand, similar situations can always be found in history. The result of your joint work should be a ready Terms of Reference for ordering a trading robot according to your strategy.

What terms to use

As a rule, in a trading system there are several basic important concepts or terms that describe the state of the market or the nature of the price movement. Even if it seems to you that you are using a generally accepted and simple concept in the Terms of Reference, it is better to describe it clearly. For each term, make one paragraph of description.

For example, according to Bill Williams, an uptrend is when all three Alligator lines are arranged in this order from bottom to top: Blue, Red, Green.


Another classic definition of an uptrend - from Larry Williams - when each new peak is higher than the previous one, and each new bottom is not lower than the previous one.


In the description of the terms, you can use screenshots of the charts, they will not interfere. In the Terms of Reference itself, we recommend highlighting the terms you enter in bold - so that later the Contractor can immediately find it in the text if in doubt.

When describing the term, the Contractor cannot be referred to other sources (websites, books, forums, etc.), justifying that this is already well known. Everything should be described here and now, no crutches in the form of "I'll explain later on Skype" are not allowed in the TOR. It will take you no more than half an hour to write down all the terms in the Terms of Reference, but it will save time that you spend on correcting errors due to misunderstandings.

What to write in a job description in Freelance

When creating a job, describe in a few paragraphs the general essence of your trade idea so that potential performers understand what you need. The job description does not need to disclose the rules of the trading system or provide details about the indicators used.

Description might look like this:

Write an Expert Advisor for trading on trend reversals. Reversal signals will be Price Action patterns. To determine the trend, the ADX, Alligator and MACD indicators will be used - the choice of the indicator is set by the input parameters of the adviser.

General idea of a trading strategy

Here you can specify on which instruments the robot will trade, whether it is trading with the trend, how it is determined and on what timeframe. If we trade with the trend, then somehow the entry occurs - on a rollback, on a breakout of the level, and so on.

By and large, there are only two trading strategies in the financial markets: to continue moving and to return to the average. Your trade idea should relate to one of these two strategies, and it should explain how trades will be opened - in the market, after confirmation of a break / pullback, or at a better price.

Description of the setup for waiting for a Signal

The signals themselves can be simple and can be easily described using algorithms. For example, such patterns as "Absorption" and "Pin bar" are well known and popular. But as a rule, it is impossible to build a profitable strategy on such well-formalized figures alone; such patterns are used to determine a trend reversal. This means that the setup for waiting for the "Bearish engulfing" pattern will be the presence of an uptrend.

Therefore, in the Terms of Reference it is necessary to describe not only the Trading Signal itself, but also formalize the setup required for it.

Signal Description

A signal to buy or sell appears when a certain condition is met. For example, a classic buy signal is when the price crosses the moving average from below. When describing such a signal, you must specify the following parameters:

  • moving average type - SMA, EMA, VIDYA and so on
  • moving average period
  • additional parameters for some averages, for example - for AMA .

In addition, the concept of "price crosses the average" also needs to be clarified. The signal may appear immediately at the moment of crossing the average, or it is still necessary to wait for the candle not only to break through the average level, but also to close above it. Not only how the code will be written depends on this, but also the tick generation mode, which must be used when testing the Expert Advisor in the Strategy Tester.

Therefore, it is necessary to clearly describe such concepts as "Trend", "Level", "Breakout", "Kickback" and "Intersection" - whether it means working with ticks, bars and closing prices. All these concepts must have a formal description with numerical parameters, which you will then optimize in the strategy tester. For example, the strength of a trend can be measured using the ADX indicator, while the Ichimoku Kinko Hyo indicator is not suitable for this.

The more conditions and filters used in a trading system, the more complex the trading program becomes. Not to mention the fact that such strategies have a lot of input parameters, which then require a huge number of optimization passes. And although the strategy tester in MetaTrader 5 allows you to speed up the optimization time of parameters by tens and thousands of times due to the genetic algorithm and the MQL5 Cloud Network , the amount of data received in this case grows like an avalanche.

Therefore, we recommend following a few rules when developing and debugging a trading robot:

  • To debug and check the signals visually, the Expert Advisor must place labels/objects on the chart at the moment of the Signal occurrence. This will allow not only to debug on history , but also to visually observe the Signals on the chart. Often, the algorithm becomes so complex that it becomes difficult to understand its work even for the trader who formulated the Rules of the system. And with the visual display of Signals, you can immediately see the moments for opening deals on the chart.
  • It is possible that an even more correct solution would be to first create an indicator that marks buy/sell signals on the chart using arrows . This will simplify the writing of an Expert Advisor, since it is easier to create and debug two programs separately than one complex one. Let the robot only trade, and the indicator only draw. In this case, the adviser code will be spared from unnecessary functionality. In addition, there may be much more Signals than there are trades made on them. For example, when a signal to buy is received, the market is usually entered, and further, according to the algorithm, signals to buy are no longer checked. And if there is a separate indicator, it will show all Buy Signals, because it has the logic to show ALL Signals, regardless of the presence of an open position.
  • Buy and sell signals should not only be described separately in the Terms of Reference, but it is also desirable to debug them separately in the strategy tester. Often buying and selling are interconnected - that is, as long as there is an open buy position, all Sell Signals are ignored (of course, if the long position is not closed by a Sell Signal). If you first test Buy Signals separately and then Sell Signals, you will be able to check the correctness of the underlying logic in its purest form.

You can even optimize the strategy parameters separately for buying and separately for selling, so that later you can combine the algorithms into a single trading robot. So you spend less time searching for optimal parameters and make fewer mistakes. Although in this case you will have to pay extra for the creation of the indicator/indicators and intermediate Expert Advisors. But a good trading idea is worth it. Is not it?

Signal lifetime

In some trading systems, the appearance of a signal does not mean an immediate opening of a position. As a rule, in such strategies confirmation/permission from an additional signal is required. For example, after a breakout of a resistance level, it is necessary to wait for the price to roll back to the broken level in order to enter on the best conditions. In this case, the time factor arises - how long or for how many bars the "Level is broken and waiting for a rollback" signal is valid. Perhaps it makes sense to wait for a pullback within 5 bars or until the end of the trading session, and then the signal is cancelled.

Adding the "Time to Live" parameter allows you to introduce additional filters that can improve the quality of trading signals.

Placing orders and opening positions

When writing functions responsible for sending trade orders, it makes sense to think about additional functionality in advance. For example, you can specify different MagicNumbers and comments in your trading robot for further analysis of trading results and optimization results. In MagicNumber, you can enter the hour and day of entry, the number of the trading pattern and other important information that will allow you to conduct additional analysis in the context of the data included in MagicNumber. Thus, you can implement several trading strategies in the Expert Advisor and perform one optimization for all at once. To then weed out an unsuccessful entry time or a losing pattern/Signal. If you want to get such functionality in an Expert Advisor, you must clearly define the MagicNumber calculation algorithm for each pattern/setup/Signal.

In addition, a trade order is not always executed successfully the first time. It is necessary to foresee situations when it was not possible to open/close a position the first time. What should the adviser do in this case - pause or wait for a new tick to arrive? How many attempts are allowed to complete a trade operation? What information should the EA log in these cases? What format should the entry be in? Is it necessary to send a message about problems to a trader and how to do it in order not to create a DDoS attack?

To quickly analyze the trading history in the terminal, use comments that can be written in trading requests. But do not forget that in some cases the trade server writes its own information in this field. Therefore, it will not be superfluous if your robot writes its own daily trading log, which will help you sort out incomprehensible situations.

If your trading strategy uses StopLoss and TakeProfit protective levels, please provide the algorithm for their calculation and the procedure for setting them. For example, it may turn out that StopLoss needs to be set only when the price moves in a favorable direction by a given number of points. If SL and TP levels are set only after a successful opening of a position, specify how the opening of a position will be checked - immediately after sending a trade request or on the next tick.

Maintenance of a trading position/order

The classic rule is "Let profits flow and cut losses." Translated into algorithmic trading, this means "Set a protective StopLoss for each open position and limit the potential profit using TakeProfit orders."

The size of the stop can significantly affect the results of trading, and traders try to find such optimal distances for placing SL / TP orders in order to maximize profits. But a rough enumeration of all possible SL / TP sizes will be the same fit on history. Try to use distance calculation algorithms that take into account market volatility, trend direction and proximity of support/resistance levels.

If you have no idea what the SL/TP sizing should be, you can look into existing trading systems. Many algorithmic traders have their own ready-made libraries that can be used to create a trading robot according to your idea.

Think over and describe the following points in the Terms of Reference:

  • using StopLoss and TakeProfit levels, the algorithm for calculating the distance for them:
  • whether it is necessary to use Trailing Stop, when it is turned on, with what step it is pulled up, step calculation algorithm;
  • if pending orders are used to enter a position, do they need to be rearranged and by what algorithm;
  • whether it is necessary to track the floating profit/loss on an open position, whether it is necessary to close the position when the specified level of profit/loss is reached;
  • something else.

Cancellation of an order and closing a position

Another way of managing positions and orders is also possible - by time and by the appearance of an opposite Signal. You can add additional deletion and closing options to the Terms of Reference:

  • by a given value of floating profit or loss on an open position;
  • when the price moves a specified distance from the current level of opening a pending order (in fact, this means that the moment has already been lost);
  • at the specified point in time;
  • through a given number of bars;
  • at the end of the specified time interval;
  • when a Signal of the opposite direction appears;
  • when a favorable setup/pattern disappears.

Lot calculation for placing an order

Some traders, when creating a trading robot, immediately add position size control functions. It is still not recommended to include money management algorithms in the EA for calculating the lot at the initial stage, since additional input parameters when optimizing the EA can lead to adjustment to a specific section of the history.

If you are creating the first version of the robot according to your trading system, then it is better to test and optimize it with a constant lot. Only after forward tests on history and in real trading for several months, when you see the strengths and weaknesses of your algorithm, can we think about money management.

Here are some approaches to calculate the lot size when opening a position:

  • fixed volume, regardless of profit or loss;
  • the volume depends on the size of the balance or equity;
  • according to the results of the received profit/losses;
  • based on the results of the last N trades (different variants of martingale and anti-martingale);
  • depending on the % risk when a protective StopLoss order is triggered;
  • other options for risk-based calculation, for example, according to the Vince method .

In any case, before adding a lot size calculation to an EA, you must be sure that your trading system has an advantage over random trading. Otherwise, you will only deceive yourself for a while. A losing system cannot be turned into a profitable one only through money management.

Handling trading errors and environment state

Since the trading robot is an autonomous program that operates 24 hours a day, it is necessary to provide means of monitoring and checking its work. The "Black Box" of your Expert Advisor will be the "Experts" log, where all messages are displayed using the Print() function. In general, it is recommended to record the appearance of Signals, patterns and setups, the current market price and trade request parameters in it before sending an order for execution.

In case of unsuccessful execution of a trade request, its results should be logged. Analysis of the trade server response codes will allow you to understand the cause of a trading error and correct it. Describe in the Terms of Reference:

  • all situations in which log entries are made;
  • parameters to be reflected in each case;
  • desired recording format, e.g. to indicate time, numeric data, separators, and so on.

Detailed logs when sending trade orders and processing the results of their execution will save you time and money.

An important point that novice algorithmic traders often forget about is the situation of restarting the terminal, losing the Internet or connecting to the trade server. In such cases, it does not hurt to think about feedback with the robot through instant messengers or email.

The difference between trading at the opening of the bar and inside the bar

... signals can disappear and appear during the life of the bar

Tick/scalping strategies

... you need to have a good idea of what it is, the less TakeProfit/StopLoss in points, the more critical the strategy is to spreads/commissions/network delays/quality of available history/speed of the robot itself.

Any deterioration in conditions can kill the strategy

Grids, martingales, averaging and the downside of these improvements

... What are they, why are they popular, and how much can they help temporarily stretch the strategy. The risk increases, although it may lengthen the life of a bad strategy

What to look for when choosing a contractor

... substantive questions

Doesn't pretend to impress

Gives clear deadlines

Indicates unclear places in the TOR immediately, and not after 2 months of discussion

A good programmer values his and your time - that's why he loves a well-developed consistent TOR

What a programmer can't do for you

Turn a losing strategy into a profitable robot

Optimize and identify any shortcomings

Write a program without errors - they will still be. Finding them and describing them in an understandable way is your task.


Reason: