Como posso checar o status de negociação? Normal ou em leilão - página 2

 

Se BID >= ASK, significa que o pregão não está casando as ordens de compra com as ordens de venda e que, portanto, a negociação daquele ativo foi interrompida.

Se isso acontecer durante o horário de negociação daquele ativo, certamente é porque o ativo está em leilão.

ps: talvez BID >= ASK possa acontecer também em situações excepcionais (durante um "circuit break", por exemplo) ou por causa de algum problema técnico. Pra tirar a dúvida é só olhar se outros ativos continuam sendo negociados ou se também pararam.

 

Olá,

No meu caso, o expert está abrindo ordens e fechando no início do pregão (leilão). Como evitar isso?


//+------------------------------------------------------------------+
//|                                                   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 LOTE = 1;
input int P = 14;
input int MMC = 9;// MEDIA MOVEL CURTA


input ulong  magicNum = 123456;//Magic Number


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;
double dif;


//--- declarar variavel trade

CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
 
   ArraySetAsSeries(rsi,true);
   ArraySetAsSeries(ema,true);
   
    trade.SetDeviationInPoints(desvPts);
    trade.SetExpertMagicNumber(magicNum);
      
   
//--- atribuir valores de manipulador dos indicadores
 
 
   rsihandle = iRSI(_Symbol,_Period,P,PRICE_MEDIAN);
   emahandle = iMA(_Symbol,_Period,MMC,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;
         }
    if(HoraFechamento())
             {
              Comment("HORARIO FECHAMENTO MERCADO!");
              FechaPosicao();
             }
    else if(HoraNegociacao())
         {
            Comment("DENTRO HORARIO NEGOCIACOES");
         }
    else
         {
            Comment("FORA HORARIO NEGOCIACOES");
         }
 
     
 
     
      // execute a operacao do robô
     
      //+------------------------------------------------------------------+
      //|  OBTENCAO DE DADOS                                               |
      //+------------------------------------------------------------------+
 
      int copied1 = CopyBuffer(rsihandle,0,0,3,rsi);
      int copied2 = CopyBuffer(emahandle,0,0,3,ema);
      //---
      
      //---
      bool sinalCompra = false;
      bool sinalVenda = false;
      //--- se os dados tiverem sido copiados corretamente
      if(copied1==3 && copied2==3)
        {
         //--- sinal de compra
         if( rsi[0] <10 && ema[0]  > ema[1])
           {
            sinalCompra = true;
           }
         //--- sinal de venda
         if( rsi[0] > 90 && ema[0] <  ema[1])
           {
            sinalVenda = true;
           }
        }
       
      //+------------------------------------------------------------------+
      //| VERIFICAR SE ESTOU POSICIONADO                                   |
      //+------------------------------------------------------------------+
      bool comprado = false;
      bool vendido = false;
      if(PositionSelect(_Symbol))
        {
          //--- se a posicao for comprada
          if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY )
            {
             comprado = true;
            }
           //--- se a posicao for vendida
           if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL )
             {
              vendido = true;
             }
          
         }
     
      //+------------------------------------------------------------------+
      //| LOGICA DE ROTEAMENTO                                             |
      //+------------------------------------------------------------------+
      //--- zerado
      ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);   
      
      if( !comprado && !vendido )
        {
         //--- sinal de compra
         if( sinalCompra && HoraNegociacao())
          {
           trade.Buy(LOTE,_Symbol,0,ask-L, ask+G ,"Compra a mercado");
          }
         //--- sinal de venda
         if( sinalVenda && HoraNegociacao() )
          {
           trade.Sell(LOTE,_Symbol,0 , bid+L,bid-G,"Venda a mercado");
          }
        }
        
       
    
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

 
//---
//---

//---
//---

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 >= 45)
                     {
                        return true;
                     }
                  else
                     {
                        return false;
                     }
               }
            return true;
         }
      return false;
   }
   
//---
//---

void FechaPosicao()
   {
      for(int i = PositionsTotal()-1; i>=0; i--)
         {
            string symbol = PositionGetSymbol(i);
            ulong magic = PositionGetInteger(POSITION_MAGIC);
            if(symbol == _Symbol && magic == magicNum)
               {
                  ulong PositionTicket = PositionGetInteger(POSITION_TICKET);
                  if(trade.PositionClose(PositionTicket, desvPts))
                     {
                        Print("Posição Fechada - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                     }
                  else
                     {
                        Print("Posição Fechada - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                     }
               }
         }
   }




   

Descubra novos recursos para o MetaTrader 5 com a comunidade e os serviços MQL5
Descubra novos recursos para o MetaTrader 5 com a comunidade e os serviços MQL5
  • www.mql5.com
One Click Close The script allows users to easily close positions if their profit/loss reaches or exceeds a value specified in pips. Please set slippage value first. Sometimes some positions do not close due to high volatility of the market. Please set larger slippage or restart the script. CreateGridOrdersTune A script for opening a grid of...
Arquivos anexados:
 

Como eu posso colocar a condicao de BID>=ASK para o Stop Loss ou Take Profit


 //+------------------------------------------------------------------+
      //| LOGICA DE ROTEAMENTO                                             |
      //+------------------------------------------------------------------+
      //--- zerado
      ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);   
      
      if( !comprado && !vendido && HoraNegociacao() )
        {
         //--- sinal de compra
         if( sinalCompra  )
          {
            double SL = ask -L;
            double TP = ask +G;
           trade.Buy(LOTE,_Symbol,0,SL, TP ,"Compra a mercado");
          }
        
       
         //--- sinal de venda
         if( sinalVenda  )
          {
            double SL = bid +L;
            double TP = bid -G;
           trade.Sell(LOTE,_Symbol,0 , SL, TP,"Venda a mercado");
          }
 

Boa tarde amigos,

A função: 

SymbolInfoInteger( SYMBOL_TIME ) retorna uma variável do tipo datetime com a data e horário da última negociação do ativo.

Pode ser comparada com o valor de data e horário do servidor ou sistema (seu computador ou VPN). Se essa diferença for maior do que alguns segundos E BID>=ASK, então está em leilão por 2 confirmações diferentes. Acredito que assim fique mais seguro.

Documentação sobre MQL5: Informações de Mercado / SymbolInfoInteger
Documentação sobre MQL5: Informações de Mercado / SymbolInfoInteger
  • www.mql5.com
SymbolInfoInteger - Informações de Mercado - Referência MQL5 - Referência sobre algorítimo/automatização de negociação na linguagem para MetaTrader 5
Razão: