Robot opening trades in a loop

 

Hello,

//+------------------------------------------------------------------+
//|                                                 MatrixKiller.mq5 |
//|                                     Copyright 2023, MatrixKiller |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MatrixKiller"
#property link      ""
#property version   "1.00"

#include  <Trade/Trade.mqh>

CTrade trade;

input int Nbr_Periods = 14;
input int History_Bars = 20000;
input double Multiplier = 2;

input double M_TakeProfit = 0;
input double M_LostSize = 0;

int handleSuperTrend;
int barsTotal;


int buy_count = 0;
int sell_count = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   handleSuperTrend = iCustom(_Symbol,PERIOD_CURRENT,"KT-SuperTrend-Indicator.ex5",History_Bars,Nbr_Periods,Multiplier);

   barsTotal = iBars(_Symbol,PERIOD_CURRENT);
   if(handleSuperTrend == INVALID_HANDLE)
     {
      return -1;
      Print("There was an error creating the indicator handle: ", GetLastError());
     }
   else
     {
      Print("Indicator handle initialized successfully");
     }

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   int bars = iBars(_Symbol,PERIOD_CURRENT);
   if(barsTotal != bars)
     {
      barsTotal = bars;


      double dpBuy[], dpSell[], dpStopLossSell[], dpStopLossBuy[];
      CopyBuffer(handleSuperTrend,2,1,1,dpBuy);
      CopyBuffer(handleSuperTrend,3,1,1,dpSell);
      CopyBuffer(handleSuperTrend,1,1,1,dpStopLossSell);
      CopyBuffer(handleSuperTrend,0,1,1,dpStopLossBuy);

      double slBuy = dpStopLossBuy[0];
      slBuy = NormalizeDouble(slBuy,_Digits);

      double slSell = dpStopLossSell[0];
      slSell = NormalizeDouble(slSell,_Digits);


      //check for number of positins opened.
      //we close the trade if more than one trade is opened

      Print("Buy Count : ", buy_count,"Sell Count : ", sell_count);

      buy_count = 0;
      sell_count = 0;                  

      for(int i = PositionsTotal() - 1 ; i >= 0 ; i--)   
        {
         PositionGetTicket(i);                            

         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) 
           {
            buy_count++;
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) 
           {
            sell_count++;
           }

        } // for loop end


      // check if buy signal is given and make a trade
      if(dpBuy[0] > 0)
        {
         //close all buys to be able to open buys.  loop through all trades and check for sell orders to close
         for(int i=PositionsTotal()-1; i>=0; i--)
           {
            if(PositionGetSymbol(i)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
              {
               ulong ticketSell = PositionGetTicket(i);
               trade.PositionClose(ticketSell);
              }
              
              Print("All sells closed");
           }

         Print(__FUNCTION__, " New Buy Signal ", dpBuy[0]);

         double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
         ask = NormalizeDouble(ask,_Digits);


         if(ask > 0 && buy_count < 1)
           {
            trade.Buy(M_LostSize,_Symbol,ask,slBuy,M_TakeProfit,"MatrixKiller");
           }
        }

      //Check if sell signal is given and make a trade
      if(dpSell[0] > 0)
        {

         //Close all buy positions to be able to open sells. and check for buy orders to close them
         for(int i=PositionsTotal()-1; i>=0; i--)
           {
            if(PositionGetSymbol(i)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
              {
               ulong ticketBuy = PositionGetTicket(i);
               trade.PositionClose(ticketBuy);
              }
              Print("All buy trades closed");
           }

         Print(__FUNCTION__, " New Sell Signal ", dpSell[0]);
         double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
         bid = NormalizeDouble(bid,_Digits);

         if(bid > 0 && sell_count < 1)
           {
            trade.Sell(M_LostSize,_Symbol,bid,slSell,M_TakeProfit,"MatrixKiller");
           }
        }
     }

  }
//+------------------------------------------------------------------+


//External Functions

//+------------------------------------------------------------------+

I've built a robot based on an indicator but the robot keep opening trades in a loop whenever a new candle is formed. 

It normally supposed to check for either buy or sell, if true closes the previous trade and make the trade accordingly but it will open and close on every candle


Here's the code

 
Fela Fomonyuy:

Hello,

I've built a robot based on an indicator but the robot keep opening trades in a loop whenever a new candle is formed. 

It normally supposed to check for either buy or sell, if true closes the previous trade and make the trade accordingly but it will open and close on every candle

Fela Fomonyuy:
Hello,

I've built a robot based on an indicator but the robot keep opening trades in a loop whenever a new candle is formed. 

It normally supposed to check for either buy or sell, if true closes the previous trade and make the trade accordingly but it will open and close on every candle

void OnTick()
  {
//---
   int bars = iBars(_Symbol,PERIOD_CURRENT);
   if(barsTotal != bars)
     {
      barsTotal = bars;


      double dpBuy[], dpSell[], dpStopLossSell[], dpStopLossBuy[];
      CopyBuffer(handleSuperTrend,2,1,1,dpBuy);
      CopyBuffer(handleSuperTrend,3,1,1,dpSell);
      CopyBuffer(handleSuperTrend,1,1,1,dpStopLossSell);
      CopyBuffer(handleSuperTrend,0,1,1,dpStopLossBuy);

      double slBuy = dpStopLossBuy[0];
      slBuy = NormalizeDouble(slBuy,_Digits);

      double slSell = dpStopLossSell[0];
      slSell = NormalizeDouble(slSell,_Digits);


      //check for number of positins opened.
      //we close the trade if more than one trade is opened

      Print("Buy Count : ", buy_count,"Sell Count : ", sell_count);
/*
      buy_count = 0;
      sell_count = 0;                  

      for(int i = PositionsTotal() - 1 ; i >= 0 ; i--)   
        {
         PositionGetTicket(i);                            

         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) 
           {
            buy_count++;
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) 
           {
            sell_count++;
           }

        } // for loop end

*/
      // check if buy signal is given and make a trade
      if(dpBuy[0] > 0)
        {
         //close all buys to be able to open buys.  loop through all trades and check for sell orders to close
         for(int i=PositionsTotal()-1; i>=0; i--)
           {
            if(PositionGetSymbol(i)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
              {
               ulong ticketSell = PositionGetTicket(i);
               trade.PositionClose(ticketSell);
                sell_count = 0;
              }
              
              Print("All sells closed");
           }

         Print(__FUNCTION__, " New Buy Signal ", dpBuy[0]);

         double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
         ask = NormalizeDouble(ask,_Digits);


         if(ask > 0 && buy_count < 1)
           {
            trade.Buy(M_LostSize,_Symbol,ask,slBuy,M_TakeProfit,"MatrixKiller");
            buy_count++;
           }
        }

      //Check if sell signal is given and make a trade
      if(dpSell[0] > 0)
        {

         //Close all buy positions to be able to open sells. and check for buy orders to close them
         for(int i=PositionsTotal()-1; i>=0; i--)
           {
            if(PositionGetSymbol(i)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
              {
               ulong ticketBuy = PositionGetTicket(i);
               trade.PositionClose(ticketBuy);
               buy_count = 0;
              }
              Print("All buy trades closed");
           }

         Print(__FUNCTION__, " New Sell Signal ", dpSell[0]);
         double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
         bid = NormalizeDouble(bid,_Digits);

         if(bid > 0 && sell_count < 1)
           {
            trade.Sell(M_LostSize,_Symbol,bid,slSell,M_TakeProfit,"MatrixKiller");
            sell_count++;
           }
        }
     }

  }
 
Fela Fomonyuy:

Do not double post!

I have deleted your other topic.

 
nocpinmylf #:

Thank you very much. Ive done the adjustment but It seems like there was no improvement

Here is what the robot is doing 

Files:
 
Keith Watford #:

Do not double post!

I have deleted your other topic.

I'm sorry, I won't repeat it again

 
nocpinmylf #:
   int bars = iBars(_Symbol,PERIOD_CURRENT);
   if(barsTotal != bars)
     {
      barsTotal = bars;

For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
          MT4: New candle - MQL4 programming forum #3 (2014)
          MT5: Accessing variables - MQL4 programming forum #3 (2022)

I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
          Running EA once at the start of each bar - MQL4 programming forum (2011)

 
William Roeder #:

For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
          MT4: New candle - MQL4 programming forum #3 (2014)
          MT5: Accessing variables - MQL4 programming forum #3 (2022)

I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
          Running EA once at the start of each bar - MQL4 programming forum (2011)

Okay let me give that a try. Im writing in mql5
 
nocpinmylf #:

Ive changes most of the code but still the same problem is still there

here is an update

//+------------------------------------------------------------------+
//|                                                 MatrixKiller.mq5 |
//|                                     Copyright 2023, MatrixKiller |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MatrixKiller"
#property link      ""
#property version   "1.00"

#include  <Trade/Trade.mqh>

CTrade trade;

#define  ExpertMagic = 21341;
input int Nbr_Periods = 14;
input int History_Bars = 20000;
input double Multiplier = 2;

input double M_TakeProfit = 0;
input double M_LostSize = 0;

int handleSuperTrend;
int barsTotal;
ulong positionTicket;

datetime    glTimeBarOpen;



//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

glTimeBarOpen = D'1971.01.01 00:00';
   handleSuperTrend = iCustom(_Symbol,PERIOD_CURRENT,"KT-SuperTrend-Indicator.ex5",History_Bars,Nbr_Periods,Multiplier);

   barsTotal = iBars(_Symbol,PERIOD_CURRENT);
   if(handleSuperTrend == INVALID_HANDLE)
     {
      return -1;
      Print("There was an error creating the indicator handle: ", GetLastError());
     }
   else
     {
      Print("Indicator handle initialized successfully");
     }

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
   bool newBar = false;
   
   //Check for New Bar
   if(glTimeBarOpen != iTime(Symbol(),PERIOD_CURRENT,0))
   {
      newBar = true;
      glTimeBarOpen = iTime(Symbol(),PERIOD_CURRENT,0);   
   }   
   
   if(newBar == true)
   { 
   
   
      double close1 = iClose(_Symbol,PERIOD_CURRENT,1);
      double close2 = iClose(_Symbol,PERIOD_CURRENT,2);

      double dpBuy[], dpSell[], dpStopLossSell[], dpStopLossBuy[];
      CopyBuffer(handleSuperTrend,2,1,3,dpBuy);
      CopyBuffer(handleSuperTrend,3,1,3,dpSell);
      CopyBuffer(handleSuperTrend,1,1,1,dpStopLossSell);
      CopyBuffer(handleSuperTrend,0,1,1,dpStopLossBuy);

      double slBuy = dpStopLossBuy[0];
      slBuy = NormalizeDouble(slBuy,_Digits);

      double slSell = dpStopLossSell[0];
      slSell = NormalizeDouble(slSell,_Digits);

      double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      ask = NormalizeDouble(ask,_Digits);

      double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
      bid = NormalizeDouble(bid,_Digits);


      // check if buy signal is given and make a trade
      if(dpBuy[0] > 0)
        {
         Print(__FUNCTION__, " New Buy Signal ", dpBuy[0]);
         //close all buys to be able to open buys.
         if(positionTicket > 0)
           {
            if(PositionSelectByTicket(positionTicket))
              {
               if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                 {
                  if(trade.PositionClose(positionTicket))
                    {
                     Print(__FUNCTION__, " sell trade ", positionTicket, " was closed");
                    }
                 }
              }
           }



         if(trade.Buy(M_LostSize,_Symbol,ask,slBuy,M_TakeProfit,"MatrixKiller"))
           {
            if(trade.ResultRetcode()==TRADE_RETCODE_DONE)
              {
               positionTicket = trade.ResultOrder();
              }
           }
        }

      //Check if sell signal is given and make a trade
      if(dpSell[0] > 0)
        {
         Print(__FUNCTION__, " New Sell Signal ", dpSell[0]);
         //Close all buy positions to be able to open sells.
         if(positionTicket > 0)
           {
            if(PositionSelectByTicket(positionTicket))
              {
               if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                 {
                  if(trade.PositionClose(positionTicket))
                    {
                     Print(__FUNCTION__, " buy trade ", positionTicket, " was closed");
                    }
                 }
              }
           }


         if(trade.Sell(M_LostSize,_Symbol,bid,slSell,M_TakeProfit,"MatrixKiller"))
           {
            if(trade.ResultRetcode()==TRADE_RETCODE_DONE)
              {
               positionTicket = trade.ResultOrder();
              }
           }
        }


     }

  }




//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+


//External Functions

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
 
Fela Fomonyuy #: Ive changes most of the code but still the same problem is still there
    if(dpBuy[0] > 0)

Of course, it does. Your if closes any sell position and opens a new buy. On the next tick, it does the same.

Either check for an open in the correct direction, or act on a change of signal.
          Too many orders - MQL4 programming forum #1 (2017)

Reason: