Изменить отложенный ордер на Mql4 - PullRequest
1 голос
/ 18 февраля 2020

Я пытаюсь найти советника, который обновляет свои отложенные ордера, если текущая цена проходит уровень SL отложенного ордера как для ордеров на покупку, так и на продажу. Как вы можете видеть ниже, pi c текущая цена находится ниже точки SL отложенных ордеров. Поэтому я хочу изменить новые обновленные отложенные ордера с ценой открытия от этой точки SL (+30 и -30 пунктов) и не только для валюты окна, но и для других валют, которые есть в списке отложенных ордеров.

Я попробовал приведенный ниже код, но это не сработало. Не могли бы вы помочь мне?

//------------------------------------------------------------------------------- 1 --
int start()                                    
  {
   string Symb=Symbol();                        // Symbol
//------------------------------------------------------------------------------- 2 --
   for(int i=1; i<=OrdersTotal(); i++)          
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) 
        {                                   
         //---------------------------------------------------------------------- 3 --
         if (OrderSymbol()== Symb) continue;    
         if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP) continue;           // Market order  
         //---------------------------------------------------------------------- 4 --
           {
            int    Tip   =OrderType();          
            int    Ticket=OrderTicket();        
            double Price =OrderOpenPrice();    
            double SL    =OrderStopLoss();     
            double TP    =OrderTakeProfit();    
           }                                   
        }                                       
     }                                          
//------------------------------------------------------------------------------- 5 --
   if (Tip==0)                                  
     {
      Alert("For ",Symb," no pending orders available");
      return;                                   
     }
//------------------------------------------------------------------------------- 6 --
   while(true)                                 
     {
      RefreshRates();                           // Update data
      //------------------------------------------------------------------------- 7 --
      double c_bid =MarketInfo(Symb,MODE_BID); // Request for the value of Bid
      double c_ask =MarketInfo(Symb,MODE_ASK); // Request for the value of Ask                         

      //------------------------------------------------------------------------- 8 --
      string Text="";                           // Not to be modified
      double New_SL=0;
      double New_TP=0;
      switch(Tip)                               // By order type
        {
         case 4:                                // BuyStopt
            if (NormalizeDouble(SL,Digits) > // If it is further than by
                NormalizeDouble(c_ask,Digits))//..the preset value
              {
               double New_Price=SL+30*Point;          // Its new price
               if (NormalizeDouble(SL,Digits)>0)
                  New_SL=New_Price-(Price-SL);  // New StopLoss
               if (NormalizeDouble(TP,Digits)>0)
                  New_TP=New_Price+(TP-Price);  // New TakeProfit
               Text= "BuyStopt ";               // Modify it.
              }
            break;                              // Exit 'switch'
         case 5:                                // SellStop
            if (NormalizeDouble(SL,Digits) < // If it is further than by
                NormalizeDouble(c_bid,Digits))//..the preset value
              {
               New_Price=SL-30*Point;          // Its new price
               if (NormalizeDouble(SL,Digits)>0)
                  New_SL=New_Price+(SL-Price);  // New StopLoss
               if (NormalizeDouble(TP,Digits)>0)
                  New_TP=New_Price-(Price-TP);  // New TakeProfit
               Text= "SellStop ";               // Modify it.
              }
        }
      if (NormalizeDouble(New_SL,Digits)<0)     // Checking SL
         New_SL=0;
      if (NormalizeDouble(New_TP,Digits)<0)     // Checking TP
         New_TP=0;
      if (Text=="")                             // If it is not modified
        {
         Alert("No conditions for modification.");
         break;                                 // Exit 'while'
        }
      //------------------------------------------------------------------------ 10 --
      Alert ("Modification ",Text,Ticket,". Awaiting response..");
      bool Ans=OrderModify(Ticket,New_Price,New_SL,New_TP,0);//Modify it!
      //------------------------------------------------------------------------ 11 --
      if (Ans==true)                            // Got it! :)
        {
         Alert ("Modified order ",Text," ",Ticket," :)");
         break;                                 // Exit the closing cycle
        }
      //------------------------------------------------------------------------ 12 --
      int Error=GetLastError();                 // Failed :(
      switch(Error)                             // Overcomable errors
        {
         case  4: Alert("Trade server is busy. Retrying..");
            Sleep(3000);                        // Simple solution
            continue;                           // At the next iteration
         case 137:Alert("Broker is busy. Retrying..");
            Sleep(3000);                        // Simple solution
            continue;                           // At the next iteration
         case 146:Alert("Trading subsystem is busy. Retrying..");
            Sleep(500);                         // Simple solution
            continue;                           // At the next iteration
        }
      switch(Error)                             // Critical errors
        {
         case 2 : Alert("Common error.");
            break;                              // Exit 'switch'
         case 64: Alert("Account is blocked.");
            break;                              // Exit 'switch'
         case 133:Alert("Trading is prohibited");
            break;                              // Exit 'switch'
         case 139:Alert("Order is blocked and is being processed");
            break;                              // Exit 'switch'
         case 145:Alert("Modification prohibited. ",
                              "Order is too close to the market");
            break;                              // Exit 'switch'
         default: Alert("Occurred error ",Error);//Other alternatives   
        }
      break;                                    // Exit the closing cycle
     }                                          // End of closing cycle   
//------------------------------------------------------------------------------ 13 --
   Alert ("The script has completed its operations -----------------------");
   return;                                      // Exit start()
  }
//------------------------------------------------------------------------------ 14 --

1 Ответ

1 голос
/ 18 февраля 2020

Добро пожаловать в мир MQL-4.56789 ...

С первых дней существования языка MQL4 спецификации сильно изменились.

Ваш скрипт страдает от "недавнего" "- Новое -MQL4.56789 ... изменение, при котором область действия объявленных переменных была ограничена только синтаксическим конструктором (это не было в оригинале MQL4).

Таким образом, объявление int Tip и др., Но внутри и if(){...} -блока приводит к тому, что Tip -вариата остается видимым снаружи {...} -блок-конструктор, которого там больше не знают.


Далее, ваш код требует полной перепроектировки, чтобы соответствовать вашему требование:

" не только для валюты окна, но также и для других валют, находящихся в списке отложенных ордеров. "

// ------------------------------------------------------------------------------- 2 --
for( int i=1; i <= OrdersTotal(); i++ )          
   {
      if ( True == OrderSelect( i-1, SELECT_BY_POS ) )
      {
         //---------------------------------------------------------------------- 3 --
         if (  OrderSymbol() == Symb ) continue; // ------------------------^ JIT/LOOP
         if (  OrderType()   == OP_BUYSTOP
            || OrderType()   == OP_SELLSTOP
               ) continue; //-----------------------------------------------^ JIT/LOOP
                           //     btw. was a pending { BUYSTOP || SELLSTOP }
         //---------------------------------------------------------------------- 4 --
         {                 //              a rest goes here :
            int    Tip    = OrderType();
            int    Ticket = OrderTicket();
            double Price  = OrderOpenPrice();
            double SL     = OrderStopLoss();
            double TP     = OrderTakeProfit();
            }
         // ------------------------------ BUT ALL THESE GOT FORGOTTEN RIGHT HERE...
         }                                       
      }
   // ------------------------------------ OK, 've LOOPED THE WHOLE DB-POOL,
   //                                                     BUT DID NOTHING SO FAR
   //                                                         AND NOTHING SO FORTH

Итак, что-то из этого поможет установить сценарий на скале - solid оснований:

#define MASK "(for i==(%3d)) got OrderTKT(%20d) of TYPE{BUY|SELL|BUYLIMIT|SELLLIMIT|BUYSTOP|SELLSTOP}=[%d] in (%10s)-MARKET ... WILL LOOP for a NEXT(?) ONE"

while ( !IsStopped() ) // ----------------------------------------------------------- 1 --
{                     //                             (almost) INFINITE SCRIPT SERVICE LOOP
                     //                           as (almost) HEADLESS Sir NICHOLAS :)
    string TradeSYMBOL;
    int    Tip;
    int    Ticket;
    double Price;
    double SL;
    double TP;

    if ( 1 > OrdersTotal() ) { Sleep( 333 ); continue; } // NOP / NAP ----------^ NOP/LOOP
    // ------------------------------------------------------------------------------ 2 --
    for( int i=0; i < OrdersTotal(); i++ )             //                     DB-POOL LOOP
    {
          if ( OrderSelect( i, SELECT_BY_POS ) )
          {
             //---------------------------------------------------------------------- 3 --
             if (  OrderType()   != OP_BUYSTOP
                && OrderType()   != OP_SELLSTOP
                   ) {
                   PrintFormat( MASK, i, OrderTicket(), OrderType(), OrderSymbol() );
                   continue; //-------------------------------------------------^ JIT/LOOP
                }              //     btw.   ! a pending { BUYSTOP || SELLSTOP }
             //---------------------------------------------------------------------- 4 --
             else
             {                 //              a         { BUYSTOP || SELLSTOP } go here :
             // -------------------------------------------------------------------- SET :
                Tip          = OrderType();
                Ticket       = OrderTicket();
                Price        = OrderOpenPrice();
                SL           = OrderStopLoss();
                TP           = OrderTakeProfit();
                TradeSYMBOL  = OrderSymbol();
             // ------------------------------------------------------------- PROCESS it :
                RefreshRates();
                ...
             // Alert()       - a blocking GUI operation, quite dangerous in auto-trading
             // any
             // OrderModify() - has also to respect the Broker-defined {Stop|Freeze}Level
                ...
                } // { BUYSTOP || SELLSTOP }
             }   //  .SELECT
         }      //   .DB-POOL LOOP________________________________________________________
    }          //    .SERVICE LOOP........................................................
...