how to close a position - page 4

 
irinacfd :

***


So what all is wrong with above code?

Thank you!

Your code does not compile - as you showed the snippet of code. I can't read other people's minds (although I try very hard).

 
Vladimir Karputov:

Your code does not compile - as you showed the snippet of code. I can't read other people's minds (although I try very hard).

Sorry, I had edited the code and have added the code for the Buy signal.

I shall repeat, it is generating the signal, but not always at the bar on which the signal in the chart appears.

Files:
GOLDM30.png  33 kb
 
irinacfd :
Sorry, I had edited the code and have added the code for the Buy signal.

Doesn't compile! This is my last post - I will not help you anymore: you may continue to think that you have invented the GRAIL and continue to hide the code.

 
Vladimir Karputov:

Doesn't compile! This is my last post - I will not help you anymore: you may continue to think that you have invented the GRAIL and continue to hide the code.

I dont understand, the entire code is 1000 lines, shall I post 1000 lines of code here?
 

Hey Guys


I'm rookie at MT5 and trying to test Swing Trade Expert. So When I try to run, operation from today is closed on auction (before market is really opened).

May you help me?

//+------------------------------------------------------------------+
//|                                                   Robo Teste.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

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

#include <Trade/Trade.mqh> // Biblioteca padrao CTrade

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

input int V = 1;//-- volume
input int P = 14;
input int RSISELL = 90;
input int RSIBUY = 10;
input int PECRSI = 3;



input int HIA = 9; //HORA INICIO ABERTURA OPERACOES
input int MIA = 00;//MINUTO INICIO ABERTURA OPERACOES
input int HFA = 16;//HORA LIMITE ABERTURA OPERACOES
input int MFA = 30;//MINUTO LIMITE ABERTURA OPERACOES


input ulong  desvPts = 1;//Desvio em Pontos

input double G = 10.0;// GAIN
input double L = 3.0;//LOSS

MqlDateTime    horaAtual;
MqlTick        ultimoTick;
MqlRates       rates[];



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


int rsihandle = INVALID_HANDLE;
int emahandle = INVALID_HANDLE;

//--- vetores de dados


double rsi[];
double ema[];
double ask, bid;


//--- declarar variavel trade

CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
 
   ArraySetAsSeries(rsi,true);
   ArraySetAsSeries(ema,true);
   
//--- atribuir valores de manipulador dos indicadores
 
  
   rsihandle = iRSI(_Symbol,_Period,P,PRICE_MEDIAN);
   emahandle = iMA(_Symbol,_Period,9,0,MODE_EMA,PRICE_MEDIAN);
   
   
   
   if(HIA == HFA && MIA >= MFA)
     {
       Alert("INCONSISTENCIA HORARIOS DE NEGOCIACAO-VERIFICAR MINUTOS HORA NEGOCIACAO");
       return(INIT_FAILED);
     }
   if( HFA < HIA )
     {
       Alert("INCONSISTENCIA HORARIOS DE NEGOCIACAO-HORA FIM MAIOR HORA INICIO");
       return(INIT_FAILED);
     }


//---
   return(INIT_SUCCEEDED);
  }





//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
    if(!SymbolInfoTick(Symbol(),ultimoTick))
         {
            Alert("Erro ao obter informações de Preços: ", GetLastError());
            return;
         }
         
    if(CopyRates(_Symbol, _Period, 0, 3, rates)<0)
         {
            Alert("Erro ao obter as informações de MqlRates: ", GetLastError());
            return;
         }
  
      else if(HoraNegociacao())
         {
            Comment("DENTRO HORARIO NEGOCIACOES");
         }
      else
         {
            Comment("FORA HORARIO NEGOCIACOES");
         }
  
   
  
     
      // execute EXPERT
     
      //+------------------------------------------------------------------+
      //|  COLLECTING DATA                                         |
      //+------------------------------------------------------------------+
     
      int copied1 = CopyBuffer(rsihandle,0,0,3,rsi);
      int copied2 = CopyBuffer(emahandle,0,0,3,ema);
      //---
      
      //---
      bool buySignal = false;
      bool sellSignal = false;
      
      //--- if the data obtained were copied correctly
      if(copied1==3 && copied2==3)
        {
         //--- buySignal
         if( rsi[0] < RSIBUY && ema[0] > ema[1] > ema [2])
           {
            buySignal = true;
           }
         //--- SELL SIGNAL
         if( rsi[0] > RSISELL && ema[0] < ema[1] < ema [2])
           {
            sellSignal = true;
           }
        }
       
      //+------------------------------------------------------------------+
      //| CHECK IF I AM POSITIONED                                   |
      //+------------------------------------------------------------------+
      bool bought = false;
      bool sold = false;
      if(PositionSelect(_Symbol))
        { 
          //--- if the position is bought
          if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY )
            {
             bought = true;
            }
           //--- if the position is SOLD
           if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL )
             {
              sold = true;
             }
         }
     
      //+------------------------------------------------------------------+
      //| LOGICA DE ROTEAMENTO                                             |
      //+------------------------------------------------------------------+
      //--- no operations
      ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);   
      
      if( !sold && !bought )
        {
         //--- sinal de compra
         if( buySignal && HoraNegociacao()  )
          {
           trade.Buy(V,_Symbol,0,ask-L, ask+G ,"Compra a mercado");
          }
         //--- sinal de venda
         if( sellSignal && HoraNegociacao() )
          {
           trade.Sell(V,_Symbol,0 , bid+L,bid-G,"Venda a mercado");
          }
        }
        
       if(HoraFechamento())
          {
            Comment("HORARIO FECHAMENTO MERCADO!");
            FecharPosicao();
          }
    
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

  
//---
//---

//---
//---

bool HoraNegociacao()
   {
      TimeToStruct(TimeCurrent(), horaAtual);
      if(horaAtual.hour >= HIA && horaAtual.hour <= HFA)
         {
            if(horaAtual.hour == HIA)
               {
                  if(horaAtual.min >= MIA)
                     {
                        return true;
                     }
                  else
                     {
                        return false;
                     }
               }
            if(horaAtual.hour == HFA)
               {
                  if(horaAtual.min <= MFA)
                     {
                        return true;
                     }
                  else
                     {
                        return false;
                     }
               }
            return true;
         }
      return false;
   }
//---
//---
bool HoraFechamento()
   {
      TimeToStruct(TimeCurrent(), horaAtual);
      if(horaAtual.hour >= 16)
         {
            if(horaAtual.hour == 16)
               {
                  if(horaAtual.min >= 59)
                     {
                        return true;
                     }
                  else
                     {
                        return false;
                     }
               }
            return true;
         }
      return false;
   }
   
//---
//---


          
          
//---
//---

void FecharPosicao()
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ResetLastError();

      PositionSelectByTicket(PositionGetTicket(i));
      if(PositionGetInteger(POSITION_MAGIC) == 123456 && PositionGetString(POSITION_SYMBOL) == _Symbol)
        {
         if(trade.PositionClose(PositionGetTicket(i)))
           {
            Print("Posições fechadas");
           }
         else
            Print("Erro ao fechar Posição ", GetLastError());
        }
     }
  }
 
irinacfd:
I dont understand, the entire code is 1000 lines, shall I post 1000 lines of code here?

Y.E.S..  :P

And make sure you use the Code (Alt + S) or upload the .mq5 file, unless its proprietary or "for your eyes only type of thing".
 

you can use The Trade Request Structure (MqlTradeRequest)  and  TRADE_ACTION_SLTP


You can put TP near or under/obove price in buy/sell condition 

Reason: