Konstantin Boykachev

CEO Proforexea LLC

Honest Coder

Professional Trader


No products in the cart.

Konstantin Boykachev

CEO Proforexea LLC

Honest Coder

Professional Trader

Blog Post

Protection against false positives of the trading robot


this article focuses on improving the stability of trading robot by eliminating possible repeat positives (bounce) in different ways: as separately in algorithms of entrance and exit, and the linkage of these algorithms.

The crux of the problem, the problem of false positives, especially evident when the market surges and sudden collapses when the amplitude of the current candle is big, and the algorithm of robot is not provided for special measures against the bounce. This causes consecutive multiple discoveries and closings on the current candle.

the financial implications can be varied and depend on the specific algorithms accounting market parameters laid down by the developer of the robot. But in any case the costs increase the spread trader is directly proportional to the number of positives in drebezge.

in this article, I’m not going to consider the analysis of financial instruments (technical and fundamental nature) that may affect the stability of the work of an expert advisor and help you avoid flickering (this is a separate issue-I am the author of the theory of equilibrium and systems based on it). Here we will talk about policy measures, directly from the analysis methods of financial markets.

so, shall proceed to deal with the problem. As a template for an example I will use expert from the standard kit, available in the client terminal Metatrader 4, titled “the MACD Sample”.

here is how visually looks the problem bounce for example EURUSD prices surge on October 2 this year (the timeframe is M15, expert MACD Sample “with default settings):

on the screenshot you can see that there are 8 serial positives (inputs Buy) on one candle. One of them is correct (in terms of normal market logic) only the first entry, the remaining 7 are drebezgom.

Causes false positives in this case:

  • is a small value of TakeProfit in the default settings (and this release algorithm), which each position is closing fast;
  • as well as algorithm entry expert “MACD Sample”, which operates immediately after closing the previous position by allowing re-entry, regardless of the number of inputs on the candle.

we agreed that questions of filtration market fluctuations, we deliberately did not take into account (because each trader your algorithm of entry and exit), so to solve the problem, with a view to universal application, consider the following factors general character:

  • time (duration of candles),
  • the number of positives (counter)
  • the range of motion (the scope of the candle).

Decision algorithm

the most simple, but at the same time, and most reliable option for fixing the entry point is the time factor, causes the following:

  • a counter of the number of positives implies the creation of cycle the program, which not only complicate the algorithm, but will reduce the performance of an expert advisor.
  • the amplitude and associated control levels prices can be repeated due to return when prices spreads within the candles, which makes the criterion price level is ambiguous.
  • and here is time irreversible moves in only one direction (rise), and hence is the most accurate and unambiguous criterion for resolving the tasks of a single operation, and eliminate bounce.

Thus, the main factor is the moment of triggering entry algorithm, rather, time of execution to open position (OrderSend), because these two things may not match if there are no special algorithm delay Open an order.

so you can remember the time (current time) when opening a position. But how to use this parameter in the algorithm to prevent second and subsequent entries for the candle? Because we do not know in advance the time (its absolute value), therefore can’t “enter” sign algorithm in advance. The algorithm must take into account (include) a common condition, which will allow the first entry on the candle, but will prevent all subsequent entries for the candle, without counting the positives (version with counter we rejected previously).

decision is pretty simple. First write the code with some comments, and then I will explain in more detail. Here is the additional code (marked with yellow background) that you want to insert in the algorithm of an expert Advisor (see file MACD_Sample_plus1.mq4):

#property copyright   2005-2014, MetaQuotes Software Corp. "
#property link        "https://www.mql4.com"

input  double TakeProfit =50;
input  double Lots =0.1;
input double Level =30;
input double MACDOpenLevel =3;
input double =MACDCloseLevel 2;
input int    MATrendPeriod =26;

datetime Time_open =900;

datetime Time_bar = 0;

 void OnTick(void) {
    double MacdCurrent, MacdPrevious;
    double SignalCurrent, SignalPrevious;
    double MaCurrent, MaPrevious;
       int cnt, ticket, total;
   if(Bars< 100) {
      Print("bars less than 100");
   if(< TakeProfit 10) {
      Print(TakeProfit less than 10 ");
     MacdCurrent} =iMACD(NULL,012269PRICE_CLOSE, MODE_MAIN,0);
   MacdPrevious =iMACD(NULL,012269PRICE_CLOSE, MODE_MAIN,1);
   SignalCurrent =iMACD(NULL,012269PRICE_CLOSE MODE_SIGNAL0);
   SignalPrevious =iMACD(NULL,012269PRICE_CLOSE MODE_SIGNAL1);
   MaCurrent =iMA(NULL,0MATrendPeriod,0MODE_EMAPRICE_CLOSE0);
   MaPrevious =iMA(NULL,0MATrendPeriod,0MODE_EMAPRICE_CLOSE1);

   total =OrdersTotal ();
   if(total< 1) {
      if(AccountFreeMargin () < (1000* Lots)) {
         Print(' We have no money. Free Margin = "AccountFreeMargin ());
      if((TimeCurrent()-Time_bar) > 900 ) Time_open = 900; 
      if(MacdCurrent <0 & & MacdCurrent > SignalCurrent & & MacdPrevious < SignalPrevious & & 
         MathAbs (MacdCurrent) > (MACDOpenLevel *Point) & & MaCurrent > MaPrevious & & 
         (TimeCurrent()-Time[0]) < Time_open) 
        {ticket =OrderSend(Symbol() , OP_BUY, Lots, Ask,30 Ask + TakeProfit *Point"macd sample"163840 Green);
         if(ticket> 0) {
            if(OrderSelect (ticket, SELECT_BY_TICKET, MODE_TRADES)) {
              Print("BUY order opened State:"OrderOpenPrice ());
              = Time_open TimeCurrent()-Time[0]; 
              Time_bar = Time[0]; 
            Print("Error opening a BUY order:"GetLastError ());

more info:

do not Use absolute time (time entry), and the relative is the time interval from the moment of opening of the current candle before the moment of entry. Continue this amount compare with predefined large enough amount of time (the duration of the entire candle) that allows you to work the first entrance. At the moment of opening a position we change (reduce) the amount of the variable Time_openrecording time interval value in it since the beginning of the candles until actual discovery. As well as any later time value (timecurrent()-Time[0]) will be higher than recorded by us in the time of entrance, the condition (timecurrent()-Time[0]) < Time_open becomes unenforceable, and the lock is achieved the second and the following entries on the candle.

like this, without any counter inputs and amplitude analysis of price movements, we have solved the problem of false positives.

here is the result of a simple refinement of the original logon algorithm expert (“MACD Sample_plus1”):

we find that the candle only one false positives there, chattering entirely eliminated. With the default settings you saved, to make it clear that the problem is solved without the aid of expert configuration changes.

now when the problem is solved on the input of bounce will modify the output algorithm, to exclude possible bounce, appearing with the rapid closing of the position, that in this particular case will increase profit (pulse output was good and quick, premature).

The decision in the algorithm output

since the primary problem is the Elimination of possible robot bounce rather than increasing profits, then I will not address the issues of the analysis of the dynamics of financial instruments in relation to the topic and I will limit myself to commit the selected option without consideration of these dynamics.

we used the Previously reliable parameter is the time factor, again, let’s use them — tightly regulate the time of position closing on time, namely at the time of the opening of the next (after login). This time the algorithm output will reflect this:

if (!OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES))
      if (ordertype() < = OP_SELL & & OrderSymbol () ==Symbol()) {
         if (ordertype() == OP_BUY) {
               Bid > OrderOpenPrice ()   
               & & TimeCurrent() == Time[0] ) {
               if (! OrderClose (orderticket(), OrderLots (), Bid,3Violet))
                  Print("OrderClose error"GetLastError ());


such a small modification will “work” algorithm entry (a position opened, conditions to close not) position lasts until timecurrent() == Time[0] and closed simultaneously at the beginning of a new momentum after the candles. As a result, in addition to protection against bounce well earned (see photo, “MACD Sample_plus2”):

When this had to be removed from the algorithm output operation on the MACD, otherwise the desired condition could not be realized.

so we can see how you can solve the problem of bounce is a separate entry in the algorithm, the algorithm output separately. Now let’s talk about solving problems by reconciling these algorithms for opening and closing positions.

Alignment algorithms for input and output

Linking is a preliminary simulation of the entire process: opening position — support — closing of a position. This is reflected, inter alia, in the choice of indicators and a shift in functions used in the algorithms of entry and exit.

for example, if you use the algorithm output condition timecurrent() = Time[0]i.e. exit point set strictly starting current candle, the algorithm must work in the previous entry, closed bars, that condition could execute. That is to close the position on the condition the timecurrent() = Time[0] without additional conditions, it is necessary that all the comparison algorithm (inlet) was implemented (completed) on the previous bar. For this indicator in the settings involved in comparing values must be equal to 1 shift. In this case, comparisons would be correct, but the beginning of a current candle is logical completion algorithm output.

Thus, linking entry and exit algorithms is also related to the time factor.


the problem of false positives is solved effectively use trade experts of the time factor in the entrance. Additionally you can provide expert resiliency detent exit point (such as time), as well as linking algorithms entry and exit through the preliminary modelling not only the basic logic of positives, but also the accounting shift (bars, where the indicator will be calculated or function).

the following are codes experts: in the initial form (MACD_Sample.mq4), with a modified input (MACD_Sample_plus1.mq4), with modified output (MACD_Sample_plus2.mq4). And finalized only feeds Buy and Sell channels is intentionally left without changes, so that you can compare the original and the modified algorithms.

and of course, all of these experts are demonstration and are not intended for trading on financial markets.

  • IngaTrade 6:30 pm December 21, 2018 Reply

    The article is useful just for a novice like me. More experienced colleagues, it already seems dry and boring

  • Trader2022 7:40 am December 24, 2018 Reply

    The topic clearly does not pull on the article. So take a note.

    Each programmer and even a trader with experience have several ways to deal with this “trouble”. Yes, and it does not matter at all. So, routine.

    • Konstantin Boykachev 4:57 pm December 28, 2018 Reply

      Here I write articles that I consider useful for beginner traders and programmers.
      If I write material only for professionals, which are few here, then it does not make sense.

Write a comment