Dividir as posições em aberto em grupos - página 10

 

Estou divulgando isso para o público julgar. Embora eu ainda não tenha anexado nenhum cheque, mas acho que eles devem funcionar.

void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
      {
         if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) == DEAL_ENTRY_IN)// Открылась позиция
            {
               if(PositionSelectByTicket(trans.position))
                  {
                     int SizeArrayPosition = ArraySize(ArrayPosition);
                     ArrayResize(ArrayPosition,SizeArrayPosition+1);
                        
                        ArrayPosition[SizeArrayPosition].kod_clana                      = 0;
                        ArrayPosition[SizeArrayPosition].open_price                     = trans.price;
                        ArrayPosition[SizeArrayPosition].ticket_position                = trans.position;
                        ArrayPosition[SizeArrayPosition].identi_position                = PositionGetInteger(POSITION_IDENTIFIER);
                        ArrayPosition[SizeArrayPosition].open_tyme            = (datetime)PositionGetInteger(POSITION_TIME);
                        ArrayPosition[SizeArrayPosition].type       = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
                        
                     Print("\n"
                     "Открылась новая позиция: ticket = ",ArrayPosition[SizeArrayPosition].ticket_position);
                  }
            }
         if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) == (DEAL_ENTRY_OUT || DEAL_ENTRY_OUT_BY))// Закрылась позиция
            {
               int SizeArrayDealOut = ArraySize(ArrayDealOut);
               ArrayResize(ArrayDealOut,SizeArrayDealOut+1);
               ArrayDealOut[SizeArrayDealOut].ticket_position_out = trans.position;
               ArrayDealOut[SizeArrayDealOut].identi_position_out = HistoryDealGetInteger(trans.deal,DEAL_POSITION_ID);
            }          
      }
  }

E em algum lugar em OnTick:DelitClosePositionFromArrayPosition();

//+------------------------------------------------------------------+
//| Удаляем закрытые позиции из массива структуры
//+------------------------------------------------------------------+
int DelitClosePositionFromArrayPosition()
{
   int n = 0;
   if(!Refresh_Rates())return(false);
//---Удаление закрытых позиций из структуры  
   int SizeArrayDealOut  = ArraySize(ArrayDealOut);
   int SizeArrayPosition = ArraySize(ArrayPosition);
   if(SizeArrayDealOut > 0)
      {
         for(int i = SizeArrayDealOut+1; i > 0; i--)
            {
               for(int y = SizeArrayPosition+1; y > 0; y--)
                  {
                     if(ArrayPosition[y].identi_position == ArrayDealOut[i].identi_position_out)
                        {
                           if(ArrayRemove(ArrayPosition,y,1) && ArrayRemove(ArrayDealOut,i,1))
                              {
                                 SizeArrayDealOut  = ArraySize(ArrayDealOut);
                                 SizeArrayPosition = ArraySize(ArrayPosition);
                                 n++;
                                 break;
                              }
                        }
                  }
            }
      }            
return(n);
}
 

Boa tarde e, mais uma vez, imploro. Segundo dia não consigo entender porque este pedaço de código não funciona

//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
      {
         Print("Зашла сделка ########## ",trans.position," ###########");
         
         if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) == DEAL_ENTRY_IN)// Открылась позиция
            {
               if(PositionSelectByTicket(trans.position))
                  {
                     int SizeArrayPosition = ArraySize(ArrayPosition);
                     ArrayResize(ArrayPosition,SizeArrayPosition+1);
                        
                        ArrayPosition[SizeArrayPosition].kod_clana                         = 0;
                        ArrayPosition[SizeArrayPosition].open_price                        = trans.price;
                        ArrayPosition[SizeArrayPosition].ticket_position                   = trans.position;
                        ArrayPosition[SizeArrayPosition].identi_position                   = PositionGetInteger(POSITION_IDENTIFIER);
                        ArrayPosition[SizeArrayPosition].open_tyme               = (datetime)PositionGetInteger(POSITION_TIME);
                        ArrayPosition[SizeArrayPosition].type_position = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
                        ArrayPosition[SizeArrayPosition].StopLoss                          = trans.price_sl;
                        ArrayPosition[SizeArrayPosition].TakeProfit                        = trans.price_tp;
                        
                       
                        Print("Открыта позиция +++ ",trans.position," +++ записана в структуру ArrayPosition ++++++++++++++");        

                  }
            }
         if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) != DEAL_ENTRY_IN)
            {
               Print("Закрыта позиция --- ",trans.position," --- записана в структуру ArrayDealOut ------------");
            }
      }
  }

Imprimir "Deal entered...." vai bem, então deve haver uma divisão, alguns negócios"Open position ...." são impressos, mas todos os outros negócios (estes são negócios de fechamento de posição no TakeProfit) não são impressos.

Eu não entendo qual é o problema. Vou marcar os negócios perdidos na cor abaixo.

2020.04.12 11:27:33.103 Core 1  2018.01.02 18:54:00   CTrade::OrderSend: market buy 0.01 EURUSD tp: 1.20621 [done at 1.20574]
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:54:00   Зашла сделка ########## 1042 ###########
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:54:00   Открыта позиция +++ 1042 +++ записана в структуру ArrayPosition ++++++++++++++
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:54:00   Зашла сделка ########## 1043 ###########
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:54:00   Открыта позиция +++ 1043 +++ записана в структуру ArrayPosition ++++++++++++++
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:55:43   take profit triggered #1039  sell 0.01 EURUSD 1.20579 tp: 1.20532 [#1044  buy 0.01 EURUSD at 1.20532]
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:55:43   deal #1044  buy 0.01 EURUSD at 1.20527 done (based on order #1044)
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:55:43   deal performed [#1044  buy 0.01 EURUSD at 1.20527]
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:55:43   order performed buy 0.01 at 1.20527 [#1044  buy 0.01 EURUSD at 1.20532]
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:55:43   Зашла сделка ########## 1039 ###########
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:56:30   take profit triggered #1042  sell 0.01 EURUSD 1.20571 tp: 1.20523 [#1045  buy 0.01 EURUSD at 1.20523]
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:56:30   deal #1045  buy 0.01 EURUSD at 1.20523 done (based on order #1045)
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:56:30   deal performed [#1045  buy 0.01 EURUSD at 1.20523]
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:56:30   order performed buy 0.01 at 1.20523 [#1045  buy 0.01 EURUSD at 1.20523]
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:56:30   Зашла сделка ########## 1042 ###########
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:57:00   На символе EURUSD открылся новый бар в 2018.01.02 18:57
2020.04.12 11:27:33.103 Core 1  2018.01.02 18:57:00   market sell 0.01 EURUSD tp: 1.20458 (1.20507 / 1.20509 / 1.20507)

Então é como SOS!!!

 
Alexey Viktorov:

Alexey, tudo isso se refere apenas ao tratamento de eventos da OnTradeTransaction

Ocorreu um evento, um comércio que encerra uma posição foi executado. A posição já se foi neste momento. Você pode confirmá-lo selecionando uma lista de pedidos e ofertas (não existe tal lista no código) e lendo

E note que estamos falando de uma conta de hadge onde a posição geralmente tem apenas duas ordens e dois negócios.

Boa tarde, se não for muito incômodo para você, você descreveu com precisão tudo neste post. Meus dois cargos acima, estou tentando obter o resultado de que preciso - comprometer-me a fechar uma posição. Ainda não consegui.

Por favor, me avise, onde eu tenho um erro ou defeito ?????

 
E assim não há distinção alguma, então acontece que fechar uma posição no TakeProfit também se enquadra noDEAL_ENTRY_IN???
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
      {
         Print("Зашла сделка ########## ",trans.position," ###########");
         
            if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) == DEAL_ENTRY_IN)// Открылась позиция
               {
                  Print("Открыта позиция +++ ",trans.position," +++ записана в структуру ArrayPosition ++++++++++++++");        
               }
            if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) != DEAL_ENTRY_IN)
               {
                  Print("Закрыта позиция --- ",trans.position," --- записана в структуру ArrayDealOut ------------");
               }
      }
  }


2020.04.12 12:10:27.368 Core 1  2018.01.03 04:58:00   CTrade::OrderSend: modify position #1252  EURUSD (sl: 0.00000, tp: 0.00000) [done]
2020.04.12 12:10:27.368 Core 1  2018.01.03 04:59:38   take profit triggered #2540  sell 0.01 EURUSD 1.20473 tp: 1.20425 [#2676  buy 0.01 EURUSD at 1.20425]
2020.04.12 12:10:27.368 Core 1  2018.01.03 04:59:38   deal #2676  buy 0.01 EURUSD at 1.20425 done (based on order #2676)
2020.04.12 12:10:27.368 Core 1  2018.01.03 04:59:38   deal performed [#2676  buy 0.01 EURUSD at 1.20425]
2020.04.12 12:10:27.368 Core 1  2018.01.03 04:59:38   order performed buy 0.01 at 1.20425 [#2676  buy 0.01 EURUSD at 1.20425]
2020.04.12 12:10:27.368 Core 1  2018.01.03 04:59:38   Зашла сделка ########## 2540 ###########
2020.04.12 12:10:27.368 Core 1  2018.01.03 04:59:38   Открыта позиция +++ 2540 +++ записана в структуру ArrayPosition ++++++++++++++
2020.04.12 12:10:27.368 Core 1  2018.01.03 04:59:40   take profit triggered #2473  sell 0.01 EURUSD 1.20472 tp: 1.20424 [#2677  buy 0.01 EURUSD at 1.20424]

 
Sergey Voytsekhovsky:
E assim não há separação alguma, acontece que o fechamento de uma posição na TakeProfit também se enquadra no DEAL_ENTRY_IN?

Parece-me que foram feitas algumas mudanças no tratamento do evento da OnTradeTransaction.

Tente substituir TRADE_TRANSACTION_DEAL_ADD por TRADE_TRANSACTION_HISTORY_ADD

 
Alexey Viktorov:

Parece-me que foram feitas algumas mudanças no tratamento de eventos da OnTradeTransaction.

Tente substituir TRADE_TRANSACTION_DEAL_ADD por TRADE_TRANSACTION_HISTORY_ADD

Não está funcionando. Obrigado por seu feedback.

 
Alexey Viktorov:

Parece-me que foram feitas algumas mudanças no tratamento de eventos da OnTradeTransaction.

Tente substituir TRADE_TRANSACTION_DEAL_ADD por TRADE_TRANSACTION_HISTORY_ADD

As posições de abertura de transações são impressas, ou seja, esta seleção funciona. Mas não está claro como selecionar negócios - posições de fechamento, mesmo que sejam visíveis na lista de transações terminais (um par/três linhas sempre mais alto).

 

Vou tentar desde o início, porque minha cabeça já está uma bagunça. Como dizia o clássico do filme - "Quem constrói assim.....????".

void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {

   if(trans.type == TRADE_TRANSACTION_HISTORY_ADD)
      {
         Print("Торговая транзакция = Добавление сделки в историю ######### Тикет сделки # ",trans.deal," ###########");
  
      }
  }

uma transação comercial, mas ainda não há nenhum bilhete comercial. Estou entendendo bem isto?

2020.04.12 14:14:19.287 Core 1  2018.01.02 13:15:00   deal performed [#405  buy 0.01 EURUSD at 1.20646]
2020.04.12 14:14:19.287 Core 1  2018.01.02 13:15:00   order performed buy 0.01 at 1.20646 [#405  buy 0.01 EURUSD at 1.20646]
2020.04.12 14:14:19.287 Core 1  2018.01.02 13:15:00   CTrade::OrderSend: market buy 0.01 EURUSD tp: 1.20694 [done at 1.20646]
2020.04.12 14:14:19.287 Core 1  2018.01.02 13:15:00   Торговая транзакция = Добавление сделки в историю #########  Тикет сделки # 0 ###########
2020.04.12 14:14:19.287 Core 1  2018.01.02 13:15:00   Торговая транзакция = Добавление сделки в историю #########  Тикет сделки # 0 ###########
2020.04.12 14:14:19.287 Core 1  2018.01.02 13:16:02   take profit triggered #394  sell 0.01 EURUSD 1.20675 tp: 1.20627 [#406  buy 0.01 EURUSD at 1.20627]
2020.04.12 14:14:19.287 Core 1  2018.01.02 13:16:02   deal #406  buy 0.01 EURUSD at 1.20627 done (based on order #406)
2020.04.12 14:14:19.287 Core 1  2018.01.02 13:16:02   deal performed [#406  buy 0.01 EURUSD at 1.20627]
 
Sergey Voytsekhovsky:

As posições de abertura de transações são impressas, ou seja, esta seleção funciona. Mas como selecionar as transações - posições de fechamento - não é claro, embora elas estejam visíveis na lista de transações do terminal (um par / três linhas mais alto sempre).

Tente passar no depurador pressionando o botão azul.


pré-definidos pontos de parada e verificar onde estão os valores e que valores eram esperados. OK, parece que não vejo nenhum erro, então tenho que verificar, assim escrevendo posições abertas, ajustar paradas para não ter que esperar muito tempo para fechar...

 
Sergey Voytsekhovsky:

Vou tentar desde o início, porque minha cabeça já está em uma confusão. Como dizia o clássico do filme - "Quem constrói assim.....????".

Há uma transação comercial, mas ainda não há nenhum bilhete comercial. Estou lendo isto bem?

Não entendo absolutamente nada. Aqui está um código da minha EA em execução

/*********************TradeTransaction function**********************/
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
 {
  if(trans.type == TRADE_TRANSACTION_HISTORY_ADD)
   {
    if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) == DEAL_ENTRY_IN)
     {
      if(PositionSelectByTicket(trans.position && PositionGetString(POSITION_SYMBOL) == _Symbol) && PositionGetInteger(POSITION_MAGIC) == magick)
       {
        if(HistorySelectByPosition(PositionGetInteger(POSITION_IDENTIFIER)))
         {
          double priceGrid = HistoryOrderGetDouble(HistoryOrderGetTicket(0), ORDER_PRICE_OPEN);
          if(priceGrid == 0)
            DebugBreak();

E nunca parou no DebugBreak(); assim tudo funciona sem nenhum problema.

Aparentemente, você tem um pedido sendo adicionado à história e está esperando por um bilhete comercial.