Bibliotecas: MT4Orders - página 26

 
ilvic:

Você pode me dar um exemplo de uma variante do MT4?

https://www.mql5.com/pt/code/7712

Semelhante ao que você fez com o Spreader

Infelizmente, o MQL4_To_MQL5.mqh não foi criado para conversão e indicadores. Mas eles estão presentes no código

   //Indicadores de acúmulo
   double fast1=iMA(NULL,0,mafastperiod,mafastshift,mafastmethod,mafastprice,1);
   double fast2=iMA(NULL,0,mafastperiod,mafastshift,mafastmethod,mafastprice,2);
   double slow1=iMA(NULL,0,maslowperiod,maslowshift,maslowmethod,maslowprice,1);
   double slow2=iMA(NULL,0,maslowperiod,maslowshift,maslowmethod,maslowprice,2);

Não vou adicioná-lo. Talvez alguém concorde com isso. Havia artigos sobre esse tópico.

 

fxsaber

Funciona incorretamente no mt5 em comparação com o mt4. Ele abre uma operação e a fecha imediatamente.

Qual pode ser o problema?

#ifdef __MQL5__
double MarketInfo( const string Symb, const ENUM_SYMBOL_INFO_DOUBLE Property )  { return(SymbolInfoDouble(Symb, Property)); }
int    MarketInfo( const string Symb, const ENUM_SYMBOL_INFO_INTEGER Property ) { return((int)SymbolInfoInteger(Symb, Property)); }

#define StrToInteger StringToInteger 
#define StrToDouble StringToDouble
#define MODE_MINLOT SYMBOL_VOLUME_MIN
#define MODE_POINT     SYMBOL_POINT
#define MODE_BID       SYMBOL_BID
#define MODE_ASK       SYMBOL_ASK

void OnInit( void ) { init(); }

#include <MT4Orders.mqh>

#endif // __MQL5__

#include "simple_copier.mq4"
Arquivos anexados:
 
ilvic:

fxsaber

Funciona incorretamente no mt5 em comparação com o mt4. Ele abre uma transação e a fecha imediatamente.

Qual pode ser o problema?

Analisei rapidamente o código. É estranho que no MT4 essas condições tenham sido escritas

if(!OrderSend(symbol_,type_,LotNormalize(lot_),price_,slip,0,0,"C4F"+IntegerToString(ticket_))) Print("Error: ",GetLastError()," during setting the pending order.");

Ele nunca chegará ao Print. E o código é certamente um assassino de HDD.


Eu o modifiquei para ser multiplataforma.

Arquivos anexados:
 

fxsaber

Obrigado pela ajuda. Mas o problema é o mesmo.

Ele abre uma ordem e a fecha imediatamente. E assim, a cada segundo, em um círculo e sem parar.

Esse problema não existe no mt4.

 
ilvic:

Obrigado por sua ajuda. Mas o problema é o mesmo.

Ele abre uma ordem e a fecha imediatamente. E assim, a cada segundo, em um círculo e sem parar.

Esse problema não existe no mt4.

Infelizmente, não tenho a oportunidade de entender seu problema.

 
// Lista de modificações:
// 26.11.2018
// Correção: posição mágica e fechada do MT4 Comentário: os campos correspondentes das negociações de abertura têm prioridade maior do que os das negociações de fechamento.
// Correção: a rara mudança de MT5-OrdersTotal e MT5-PositionsTotal durante o cálculo de MT4-OrdersTotal e MT4-OrderSelect é levada em conta.
// Correção: as ordens que abriram uma posição, mas não tiveram tempo de ser excluídas pelo MT5, não são mais consideradas pela biblioteca.

Em destaque. Esse é o tipo de script

#include <MT4Orders.mqh>
#include <Debug.mqh> // https://c.mql5.com/3/173/Debug.mqh

#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

void OnStart()
{
  OrderSend(_Symbol, OP_BUYLIMIT, 0.1, Ask, 0, 0, 0);
  
  int Total = _P(OrdersTotal());
  
  while (!IsStopped())
  {
    const int NewTotal = OrdersTotal();
    
    if (Total != NewTotal)
    {
      _P(NewTotal);

// se (NewTotal < Total)
// Alert("https://www.mql5.com/ru/forum/290673#comment_9493241");
      
      Total = NewTotal;
    }
  }
}

nas contas do Hedge costumava aparecer

2018.11.26 15:27:46.513 void OnStart(), Line = 10: OrdersTotal() = 1
2018.11.26 15:27:56.128 void OnStart(), Line = 18: NewTotal = 2
2018.11.26 15:27:56.128 void OnStart(), Line = 18: NewTotal = 1


Agora é só isso.

2018.11.26 15:30:29.224 void OnStart(), Line = 10: OrdersTotal() = 1


Para contas de compensação em todos os casos, ainda não conseguimos superar as causas do MT5 (a ordem executada não é excluída). Ou seja, a biblioteca não sabe como (na verdade, e não deveria) contornar os defeitos da plataforma MT5 em todos os casos.

 
fxsaber:
A biblioteca não é capaz (de fato, não deveria ser capaz) de contornar as deficiências da própria plataforma MT5 em todos os casos.

Por exemplo, este

abrindo uma posição foi colocada e o OrdersTotal aumentou em um.

  • Ela foi executada e o OrdersTotal diminuiu em um, mas o PositionsTotal não aumentou em um. Ou seja, há uma posição, mas o Terminal não sabe sobre ela.
  • Por exemplo, não há posições nem ordens - PositionsTotal = 0, OrdersTotal = 0.

    Você coloca uma ordem a mercado. Nesse caso, PositionsTotal = 0, OrdersTotal = 1.

    A ordem a mercado é executada - OrdersTotal = 0. Mas PositionsTotal = 0!

    É preciso muito esforço para se deparar com essa situação. É ainda mais difícil percebê-la. Mas o MT5 cria esses truques.

    O MT4Orders tenta evitar essas coisas o máximo possível, mas nem sempre é possível. Se os autores do TS tentam levar em conta essas falhas da plataforma em MQL5 puro ou SB, só podemos adivinhar. É improvável.

     
    // Demonstração de como enviar manualmente ordens de negociação para o Visualizador.
    
    #include <MT4Orders.mqh> // https://www.mql5.com/pt/code/16006
    
    #define Bid SymbolInfoDouble(_Symbol, SYMBOL_BID)
    #define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)
    
    bool IsModify()
    {
      static long PrevTime = 0;
      
      const long NewTime = FileGetInteger(__FILE__, FILE_MODIFY_DATE);
      const bool Res = (PrevTime != NewTime);
      
      if (Res)
        PrevTime = NewTime;
        
      return(Res);  
    }
    
    bool CreateFile()
    {
      uchar Bytes[];
          
      return(FileSave(__FILE__, Bytes) && IsModify());
    }
    
    string GetCommand()
    {
      uchar Bytes[];
      FileLoad(__FILE__, Bytes);
      
      return(CharArrayToString(Bytes));
    }
    
    bool OrdersScan( const int Type )
    {
      for (int i = ::OrdersTotal() - 1; i >= 0; i--)
        if (OrderSelect(i, SELECT_BY_POS) && (OrderType() == Type))      
          return(true);    
        
      return(false);  
    }
    
    bool SendCommand( const string Command, const double Lot = 1, const int Offset = 100 )
    {
      bool Res = false;
      
      if (Command == "open buy")  
        Res = (OrderSend(_Symbol, OP_BUY, Lot, Ask, 0, 0, 0) > 0);
      else if (Command == "open sell")  
        Res = (OrderSend(_Symbol, OP_SELL, Lot, Bid, 0, 0, 0) > 0);
      else if (Command == "open buylimit")  
        Res = (OrderSend(_Symbol, OP_BUYLIMIT, Lot, Ask - Offset * _Point, 0, 0, 0) > 0);
      else if (Command == "open selllimit")  
        Res = (OrderSend(_Symbol, OP_SELLLIMIT, Lot, Bid + Offset * _Point, 0, 0, 0) > 0);
      else if (Command == "close buy")  
        Res = OrdersScan(OP_BUY) && OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0);
      else if (Command == "close sell")
        Res = OrdersScan(OP_SELL) && OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0);
      else if (Command == "close buylimit")  
        Res = OrdersScan(OP_BUYLIMIT) && OrderDelete(OrderTicket());
      else if (Command == "close selllimit")
        Res = OrdersScan(OP_SELLLIMIT) && OrderDelete(OrderTicket());
        
      return(Res);
    }
    
    bool TesterManual()
    {
      static const bool IsVisual = MQLInfoInteger(MQL_VISUAL_MODE) && CreateFile();
      
      return(IsVisual && IsModify() && SendCommand(GetCommand()));
    }
    
    void OnTick()
    {
      TesterManual();
    }


     

    Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

    Библиотеки: MT4Orders

    fxsaber, 2018.12.05 19:43

    // Demonstração de como enviar manualmente ordens de negociação para o Visualizer.
    
    #include <MT4Orders.mqh> // https://www.mql5.com/ru/code/16006
    
    #define Bid SymbolInfoDouble(_Symbol, SYMBOL_BID)
    #define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)
    
    bool IsModify()
    {
      static long PrevTime = 0;
      
      const long NewTime = FileGetInteger(__FILE__, FILE_MODIFY_DATE);
      const bool Res = (PrevTime != NewTime);
      
      if (Res)
        PrevTime = NewTime;
        
      return(Res);  
    }
    
    bool CreateFile()
    {
      uchar Bytes[];
          
      return(FileSave(__FILE__, Bytes) && IsModify());
    }
    
    string GetCommand()
    {
      uchar Bytes[];
      FileLoad(__FILE__, Bytes);
      
      return(CharArrayToString(Bytes));
    }
    
    bool OrdersScan( const int Type )
    {
      for (int i = ::OrdersTotal() - 1; i >= 0; i--)
        if (OrderSelect(i, SELECT_BY_POS) && (OrderType() == Type))      
          return(true);    
        
      return(false);  
    }
    
    bool SendCommand( const string Command, const double Lot = 1, const int Offset = 100 )
    {
      bool Res = false;
      
      if (Command == "open buy")  
        Res = (OrderSend(_Symbol, OP_BUY, Lot, Ask, 0, 0, 0) > 0);
      else if (Command == "open sell")  
        Res = (OrderSend(_Symbol, OP_SELL, Lot, Bid, 0, 0, 0) > 0);
      else if (Command == "open buylimit")  
        Res = (OrderSend(_Symbol, OP_BUYLIMIT, Lot, Ask - Offset * _Point, 0, 0, 0) > 0);
      else if (Command == "open selllimit")  
        Res = (OrderSend(_Symbol, OP_SELLLIMIT, Lot, Bid + Offset * _Point, 0, 0, 0) > 0);
      else if (Command == "close buy")  
        Res = OrdersScan(OP_BUY) && OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0);
      else if (Command == "close sell")
        Res = OrdersScan(OP_SELL) && OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0);
      else if (Command == "close buylimit")  
        Res = OrdersScan(OP_BUYLIMIT) && OrderDelete(OrderTicket());
      else if (Command == "close selllimit")
        Res = OrdersScan(OP_SELLLIMIT) && OrderDelete(OrderTicket());
        
      return(Res);
    }
    
    bool TesterManual()
    {
      static const bool IsVisual = MQLInfoInteger(MQL_VISUAL_MODE) && CreateFile();
      
      return(IsVisual && IsModify() && SendCommand(GetCommand()));
    }
    
    void OnTick()
    {
      TesterManual();
    }