Closing position on the opposite signal. My code just keeps accepting new signals and doesn't close them.

 

//+------------------------------------------------------------------+
//|                                                TrendFollower.mq5 |
//|                                            Raphael Malburg, 2021 |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

#include <Trade\TradeAlt.mqh>
CTradeAlt Trade;

//+------------------------------------------------------------------+
//| PARAMETROS DE ENTRADA                                            |
//+------------------------------------------------------------------+

 input double Lote                      = 0.02;
 input bool RPAtivo                     = true;
 input string               HoraInicial    = "00:00";   // Horário de Início para novas operações
 input string               HoraFinal      = "18:15";   // Horário de Término para novas operações
 input string               HoraFechamento = "18:45";   // Horário de Fechamento para posições abertas
 
 input group " DADOS MÉDIA MOVEL LONGA FILTRO"
 
 input int MédiaLongaPeriodo            = 200;
 input ENUM_MA_METHOD  MédiaLongaMétodo = MODE_SMMA;
 
input group " DADOS MÉDIA MOVEL CURTA FILTRO"

 input int MédiaCurtaPeriodo            = 20;
 input ENUM_MA_METHOD  MédiaCurtaMétodo = MODE_EMA;
 
 input group " DADOS HILO"
 
 input int HiloPeriodo            = 9;
 input ENUM_MA_METHOD  HiloMétodo = MODE_SMMA;
 
input group " DADOS ATR"

 input int PeriodoAtr                   = 14;
 
//+------------------------------------------------------------------+
//| VARIAVEIS GLOBAIS,HANDLES E ARRAYS                               |
//+------------------------------------------------------------------+

 int i_MediaLongaHandle;
 int i_MediaCurtaHandle;
 int i_AtrHandle;
 int i_HiloHandle;
 
 double i_MediaLonga [];
 double i_MediaCurta[];
 double i_Hilo[];
 double i_Atr[];
 MqlRates Rates[];
 ulong posTicket;
 int totalbars;
 
 MqlDateTime hora_inicial, hora_final, hora_fechamento;
  
int OnInit()
  {
   ArraySetAsSeries (Rates,true);
   ArraySetAsSeries (i_MediaLonga,true);
   ArraySetAsSeries(i_MediaCurta,true);
   ArraySetAsSeries(i_Hilo,true);
   ArraySetAsSeries(i_Atr,true);
   
   totalbars = iBars(_Symbol,_Period);
   i_MediaLongaHandle = iMA(_Symbol,_Period,MédiaLongaPeriodo,0,MédiaLongaMétodo,PRICE_CLOSE);
   i_MediaCurtaHandle = iMA(_Symbol,_Period,MédiaCurtaPeriodo,0,MédiaCurtaMétodo,PRICE_CLOSE);
   i_AtrHandle = iATR(_Symbol,_Period,PeriodoAtr);
   i_HiloHandle = iCustom(_Symbol,_Period,"gann_hi_lo_activator_ssl.ex5",HiloPeriodo,HiloMétodo);
   
   TimeToStruct(StringToTime(HoraInicial),hora_inicial);
   TimeToStruct(StringToTime(HoraFinal), hora_final);
   TimeToStruct(StringToTime(HoraFechamento), hora_fechamento);
   
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  { 
     
     CopyBuffer(i_MediaLongaHandle,0,0,3,i_MediaLonga);
     CopyBuffer(i_MediaCurtaHandle,0,0,3,i_MediaCurta);
     CopyBuffer(i_AtrHandle,0,0,3,i_Atr);
     CopyBuffer(i_HiloHandle,0,0,3,i_Hilo);
     
     CopyRates(_Symbol,PERIOD_CURRENT,0,3,Rates);
     
      int bars = iBars(_Symbol,_Period);
       if(totalbars != bars){
          totalbars = bars;
//+------------------------------------------------------------------+
//| Parametros de Compra                                             |
//+------------------------------------------------------------------+     
     
      if (i_MediaCurta[1] >=i_MediaLonga[1] && Rates[1].close > i_Hilo[1] && Rates[2].close < i_Hilo[2]){
      Print("sinal de compra");

       if(posTicket > 0){
        if (PositionSelectByTicket(posTicket)){
          if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL){       
            if(Trade.PositionClose(posTicket)){          
                    Print(__FUNCTION__," > Pos#", posTicket, "was closed...");
            }
           }
         }
       } 
       
     double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
     ask = NormalizeDouble(ask,_Digits);  
     
        if(Trade.Buy(Lote,_Symbol,ask,0,0)){
         if(Trade.ResultRetcode() == TRADE_RETCODE_DONE){
            posTicket = Trade.ResultOrder();  
            
    } 
   }               
  }else if (i_MediaCurta[1] <=i_MediaLonga[1] && Rates[1].close < i_Hilo[1] && Rates[2].close > i_Hilo[2]){
      Print("sinal de venda");
      
     if(posTicket > 0){
       if (PositionSelectByTicket(posTicket)){
        if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY){
         if(Trade.PositionClose(posTicket)){
           Print(__FUNCTION__," > Pos#", posTicket, "was closed...");
      
          }
         }     
       }
     }
     
    double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
    bid = NormalizeDouble(bid,_Digits);
    
     if(Trade.Sell(Lote,_Symbol,bid,0,0)){
        if(Trade.ResultRetcode() == TRADE_RETCODE_DONE){
          posTicket = Trade.ResultOrder();

          
    }
   }        
             ResetLastError();
            return;
      
     }
    }
   }

There are many things to finish in this EA, I'm new on programming also. 

As you see its a trend following system, with filter and , after I fix the closing positions issue, a partial close at 1 atr distance.

Thing is, as I searched and learned, I set the code to store to information about the position on "posTicket" so that i could identify it when there is a open position, then close when the confirmation indicator(hilo) gives the opposite signal.

If some of you could point out where is the error on this, I would really appreciate it. It does not recognize any open positions, because it keeps opening new positions when the criteria is meet.

I followed until where the code was going and it jumps the yellow part that I put there.

Thanks reading and the MQL5 forum support.

 
Raphael malburg:

There are many things to finish in this EA, I'm new on programming also. 

As you see its a trend following system, with filter and , after I fix the closing positions issue, a partial close at 1 atr distance.

Thing is, as I searched and learned, I set the code to store to information about the position on "posTicket" so that i could identify it when there is a open position, then close when the confirmation indicator(hilo) gives the opposite signal.

If some of you could point out where is the error on this, I would really appreciate it. It does not recognize any open positions, because it keeps opening new positions when the criteria is meet.

I followed until where the code was going and it jumps the yellow part that I put there.

Thanks reading and the MQL5 forum support.

You need to go through the existing Positions in a for/while loop.
The EA will only check positions by ticket if you give it the position ticket numbers to check for.
Give them to the EA by means of a loop.


void OnTick()
  {
//---
   total_positions=PositionsTotal();
   if((total_positions>0) && (/*media corta condition*/) && (/*rates etc. condition*/))
      for(int position_ticket=total_positions-1 ; i>=0 ; i++) //it looks more complicated but it makes the oldest positions
                                                              //come first, latest has zero index
        {
         //enter code here (position type to check). BTW why are you making posTicket>0 a condition?
         //because the latest posTicket will always be 0 and you don't want to exclude that from processing
         //after all necessary checks enter PositionClose statement here.
        }
    // and the same for the other direction. 
  }
//+------------------------------------------------------------------+

   // Later you can simplify the code by reusing the functions and only changing
   // the parameters you feed them with. Then you can have only one function that 
   // is depending on different input conditions which you can store inside bool variables
I hope you can work with that although it will take some time to understand loops and if you have some questions do not hesitate to ask.
 
pennyhunter #:
You need to go through the existing Positions in a for/while loop.
The EA will only check positions by ticket if you give it the position ticket numbers to check for.
Give them to the EA by means of a loop.


I hope you can work with that although it will take some time to understand loops and if you have some questions do not hesitate to ask.
void OnTick()
  {
//---
   total_positions=PositionsTotal();
   if((total_positions>0) && (/*media corta condition*/) && (/*rates etc. condition*/))
      for(int position_ticket=total_positions-1 ; i>=0 ; i++) //it looks more complicated but it makes the oldest positions
                                                              //come first, latest has zero index
        {
         //enter code here (position type to check). BTW why are you making posTicket>0 a condition?
         //because the latest posTicket will always be 0 and you don't want to exclude that from processing
         //after all necessary checks enter PositionClose statement here.
        }
    // and the same for the other direction. 
  }
//+------------------------------------------------------------------+

   // Later you can simplify the code by reusing the functions and only changing
   // the parameters you feed them with. Then you can have only one function that 
   // is depending on different input conditions which you can store inside bool variables

Ok, Sorry if I'm kind of dummie on it, but in trying to get it as max as I can. Bought some MQL5 courses on Udemy, doing all the free tutorial and classes I can find on YouTube and etc. But god damn, it's  far from easy. OK, know that I stopped whining about it, LOL.

In purple I store the information about the any open position on the variable total_position, right?

Then on yellow its checked if there is any open one and the criteria to be checked on the direction that i want to close the trade. ( sell criteria to be met in order to close a buy position)

On green is the for loop, to keep repeating the the process until "i" is 0.

The blue part I organize that logic of getting the ticket and closing it.

Please, correct me if my assumption was wrong.

Questions;

what value and how will i give ''i''? something just like int i =0; ?

I thought about using "posTicket >0" to send the information that I have a open position.

BDW. a SUPER HUGE thanks for reading and taking the effort and patience to read and reply with your knowledge. 

Have a great week.

 
Raphael malburg #:

Ok, Sorry if I'm kind of dummie on it, but in trying to get it as max as I can. Bought some MQL5 courses on Udemy, doing all the free tutorial and classes I can find on YouTube and etc. But god damn, it's  far from easy. OK, know that I stopped whining about it, LOL.

In purple I store the information about the any open position on the variable total_position, right?

Then on yellow its checked if there is any open one and the criteria to be checked on the direction that i want to close the trade. ( sell criteria to be met in order to close a buy position)

On green is the for loop, to keep repeating the the process until "i" is 0.

The blue part I organize that logic of getting the ticket and closing it.

Please, correct me if my assumption was wrong.

Questions;

what value and how will i give ''i''? something just like int i =0; ?

I thought about using "posTicket >0" to send the information that I have a open position.

BDW. a SUPER HUGE thanks for reading and taking the effort and patience to read and reply with your knowledge. 

Have a great week.

Alright, as for the purple, I am not sure if this is good practice to introduce a variable to store the value instead of getting the value via  PositionsTotal() each time, it might do just that.

Yellow, Green and Blue: yes, yes and yes. The thought was to have as few as possible steps repeated in the loop.

Green: Of course you might be expecting to find like i=4 or something, but it is handy to introduce position_ticket (or "pos" would be shorter and you don't mix it up with posTicket) as index variable instead of i because it is self explanatory.

For the definition of the loops starting index value we are using a variable like total_position which is updated from PositionsTotal() dynamically at every Tick.

Thanks have a great week as well.
Reason: