Tutte le domande dei nuovi arrivati su MQL4 e MQL5, aiuto e discussione su algoritmi e codici - pagina 480

 
Aiuto con un consulente non giudicare rigorosamente Sto scrivendo il primo

una volta. Non vuole chiudere posizioni , cosa c'è che non va???

 //+------------------------------------------------------------------+
//|                                                     cjdtnybr.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+


//--- Inputs
extern double Lots          = 0.1 ; // лот
extern int     StopLoss      = 500 ; // лось 
extern int     TakeProfit    = 500 ; // язь
extern int     Profit        = 500 ; // язь в рублях
extern int     Delta         = 100 ; // расстояние от фрактала
extern int     MAPeriod      = 12 ;   // период МА
extern int     Slip          = 30 ;   // проскальзывание
extern int     Shift         = 2 ;   // сдвиг баров назад
extern int     Expiration    = 44 ;   // время истечения в часах
extern int     Count         = 100 ; // количество открываемых ордеров
extern int     Magic         = 123 ; // магик
extern double TrailingStop  =- 10 ; //отрицательные значения для перевода в ордера БУ по достижении
extern bool    SetOnlyZeroValues= true ; //Признак изменения только нулевых значений
extern color   BuyOrderColor=Green;
extern color   SellOrderColor=Red;
int t= 0 ;
//+------------------------------------------------------------------+
int CountTrades()
  {
   int count= 0 ;
   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY || OrderType ()== OP_SELL )
               count++;
           }
        }
     }
   return (count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double AllProfit()
  {
   double profit= 0 ;

   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY || OrderType ()== OP_SELL ) profit+= OrderProfit ();
           }
        }
     }
   return (profit);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseAll()
  {
   bool cl;
   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY )       cl= OrderClose ( OrderTicket (), OrderLots (), Bid ,Slip,Blue);
             if ( OrderType ()== OP_SELL )      cl= OrderClose ( OrderTicket (), OrderLots (), Ask ,Slip,Red);
             if ( OrderType ()== OP_BUYSTOP )  cl= OrderDelete ( OrderTicket ());
             if ( OrderType ()== OP_SELLSTOP ) cl= OrderDelete ( OrderTicket ());
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ClosePos()
  {
   double up= iFractals ( NULL , 0 , MODE_UPPER ,Shift);
   double dn= iFractals ( NULL , 0 , MODE_LOWER ,Shift);
   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY )
              {
               if (up> 0 &&dn== 0 &&Profit> 0 )
                 {
                  CloseAll();
                 }
              }
             if ( OrderType ()== OP_SELL )
              {
               if (dn> 0 &&up== 0 )
                 {
                  CloseAll();
                 }
              }
           }
        }
     }
   return ;
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void OpenPos()
  {
   double up= 0 ,dn= 0 ,ma= 0 ,pr= 0 ,sl= 0 ,tp= 0 ;
   int     res;
//--- get ind
   up= iFractals ( NULL , 0 , MODE_UPPER ,Shift);
   dn= iFractals ( NULL , 0 , MODE_LOWER ,Shift);
   
//--- sell conditions
   if (up> 0 &&dn== 0 )
     {
      pr= NormalizeDouble (up+Delta* Point , Digits );
       if (StopLoss> 0 ) sl= NormalizeDouble (pr-StopLoss* Point , Digits );
       if (TakeProfit> 0 ) tp= NormalizeDouble (pr+TakeProfit* Point , Digits );
      res= OrderSend ( Symbol (), OP_BUYSTOP ,Lots,pr,Slip,sl,tp, "" ,Magic, TimeCurrent ()+Expiration* 3600 ,Red);
       return ;
     }
//--- buy conditions
   if (dn> 0 &&up== 0 )
     {
      pr= NormalizeDouble (dn-Delta* Point , Digits );
       if (StopLoss> 0 ) sl= NormalizeDouble (pr+StopLoss* Point , Digits );
       if (TakeProfit> 0 ) tp= NormalizeDouble (pr-TakeProfit* Point , Digits );
      res= OrderSend ( Symbol (), OP_SELLSTOP ,Lots,pr,Slip,sl,tp, "" ,Magic, TimeCurrent ()+Expiration* 3600 ,Blue);
       return ;
     }
//---
  }                      
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick ()
  {
   double up= 0 ,dn= 0 ,ma= 0 ;
//--- get ind
   up= iFractals ( NULL , 0 , MODE_UPPER ,Shift);
   dn= iFractals ( NULL , 0 , MODE_LOWER ,Shift);
   
   if (CountTrades()<Count && t!= Time [ 0 ])
     {
      OpenPos();
      t= Time [ 0 ];
     }
     
        
   
   
   
   
   
   

   Comment ( "\n  UP Fractal " ,up,
           "\n  DN Fractal " ,dn,
           "\n  Profit: " ,AllProfit());
//---
  

  
//--- check for trailing stop



  
   int cnt,total= OrdersTotal (); double kd;
   if ( Digits == 5 ) kd= 10 ; else kd= 1 ;
   double TP= MathAbs (TakeProfit)*kd;
   double SL= MathAbs (StopLoss)*kd;
   double TS=TrailingStop*kd;
   if (TP< MarketInfo ( Symbol (), MODE_STOPLEVEL ) && TP!= 0 )
     {
       Comment ( "TakeProfit value too small, must be >= " + DoubleToStr ( MarketInfo ( Symbol (), MODE_STOPLEVEL )/kd, 0 ));
      
     }
   if (SL< MarketInfo ( Symbol (), MODE_STOPLEVEL ) && SL!= 0 )
     {
       Comment ( "StopLoss value too small, must be >= " + DoubleToStr ( MarketInfo ( Symbol (), MODE_STOPLEVEL )/kd, 0 ));
      
     }
// Установка ограничения прибыли и убытка
   for (cnt= 0 ;cnt<total;cnt++)
     {
       if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES ))
       continue ;
       if ( OrderType ()<= OP_SELL && OrderSymbol ()== Symbol ())
        {
         if ( OrderType ()== OP_BUY )
           {
             if ((( OrderTakeProfit ()== 0 && TP!= 0 ) || ( OrderStopLoss ()== 0 && SL!= 0 )) && !SetOnlyZeroValues)
              {
               if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()- Point *SL, OrderOpenPrice ()+ Point *TP, 0 ,BuyOrderColor))
                   Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderTakeProfit ()== 0 && SetOnlyZeroValues && TP!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderStopLoss (), OrderOpenPrice ()+ Point *TP, 0 ,BuyOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderStopLoss ()== 0 && SetOnlyZeroValues && SL!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()- Point *SL, OrderTakeProfit (), 0 ,BuyOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
           }
         else
           {
             if ((( OrderTakeProfit ()== 0 && TP!= 0 ) || ( OrderStopLoss ()== 0 && SL!= 0 )) && !SetOnlyZeroValues)
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()+ Point *SL, OrderOpenPrice ()- Point *TP, 0 ,SellOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderTakeProfit ()== 0 && SetOnlyZeroValues && TP!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderStopLoss (), OrderOpenPrice ()- Point *TP, 0 ,SellOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderStopLoss ()== 0 && SetOnlyZeroValues && SL!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()+ Point *SL, OrderTakeProfit (), 0 ,SellOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
           }
        }
     }
   if ( MathAbs (TS)< MarketInfo ( Symbol (), MODE_STOPLEVEL ) && TS!= 0 )
     {
       Comment ( "Traling stop value too small, must be >= " + DoubleToStr ( MarketInfo ( Symbol (), MODE_STOPLEVEL )/kd, 0 ));
      
     }
//Trailing
   if (TS> 0 )
     {
       for (cnt= 0 ;cnt<total;cnt++)
        {
         if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES ))
         continue ;
         if ( OrderType ()<= OP_SELL && OrderSymbol ()== Symbol ())
           {
             if ( OrderType ()== OP_BUY )
              {
               if ( Bid - OrderOpenPrice ()> Point *TS && OrderStopLoss ()< Bid - Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), Bid - Point *TS, OrderTakeProfit (), 0 ,BuyOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
             else
              {
               if ( OrderOpenPrice ()- Ask > Point *TS && OrderStopLoss ()> Ask + Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), Ask + Point *TS, OrderTakeProfit (), 0 ,SellOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
           }
        }
     }
//ZeroTrailing     
   if (TS< 0 )
     {
       for (cnt= 0 ;cnt<total;cnt++)
        {
         if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES ))
         continue ;
         if ( OrderType ()<= OP_SELL && OrderSymbol ()== Symbol ())
           {
             if ( OrderType ()== OP_BUY )
              {
               if ( Bid - OrderOpenPrice ()>- Point *TS && OrderStopLoss ()!= OrderOpenPrice () && OrderStopLoss ()< Bid + Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice (), OrderTakeProfit (), 0 ,BuyOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
             else
              {
               if ( OrderOpenPrice ()- Ask >- Point *TS && OrderStopLoss ()!= OrderOpenPrice () && OrderStopLoss ()> Ask - Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice (), OrderTakeProfit (), 0 ,SellOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
           }
        }
     }
   return ;
  }
//+------------------------------------------------------------------+

 
Aleksandr0:
Scusa per il codice, non l'ho capito subito.

Non hai visto dove stai cercando di chiudere gli ordini?

 
void ClosePos()
  {
   double up=iFractals(NULL,0,MODE_UPPER,Shift);
   double dn=iFractals(NULL,0,MODE_LOWER,Shift);
   for(int i=OrdersTotal()-1;i>=0;i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY)
              {
               if(up>0&&dn==0&&Profit>0)
                 {
                  CloseAll();
                 }
              }
            if(OrderType()==OP_SELL)
              {
               if(dn>0&&up==0)
                 {
                  CloseAll();
                 }
              }
           }
        }
     }
   return;
  }
 
o è sbagliato?
 
se non viene aggiunto un profitto superiore a 0, le operazioni vengono chiuse correttamente secondo la condizioneup>0&dn==0ma quando viene aggiunto un profitto, tutto smette di funzionare
 
Aleksandr0:
o è sbagliato?

Tutte le biciclette sono state inventate prima di te: collega le funzioni in modo intelligente e il gioco è fatto. Sarebbe anche una buona idea leggere un libro di testo sulle chiusure degli ordini.

IMHO.

Торговые функции - Создание обычной программы - Учебник по MQL4
Торговые функции - Создание обычной программы - Учебник по MQL4
  • book.mql4.com
Как правило, обычный эксперт содержит несколько торговых функций. Их можно разделить на две категории - управляющие и исполнительные. В большинстве случаев в эксперте используется всего одна управляющая функция и несколько исполнительных. Торговая стратегия в обычном эксперте реализуется на основе двух функций - функции определения торговых...
 
@Roman Shiredchenko Mi dispiace, ho scritto come meglio potevo usando libri e internet, non capisco più, per favore aiutatemi e consigliatemi dove ho sbagliato.
 
STARIJ:

Avete provato il mio programma? Non capisco bene il 300... Se metti 300 invece di 60, è vero? Se mi dici come trarne profitto, guarderò più attentamente!

Sì, il vostro programma scrive sui file ogni 60 secondi. Ma i tempi di apertura delle posizioni sono diversi e dovrebbero essere contati dai tempi di apertura di ogni posizione separatamente, cioè il tempo delle entrate sarà diverso, ma risulta che i dati sono scritti quasi simultaneamente su tutte le posizioni. Per 300 secondi, la differenza può essere vista più chiaramente. Profitto?) Forse, è importante sapere in quale momento dall'apertura della posizione il numero "P" è maggiore di "L", è per BOO.

 

Puoi dirmi come leggere l'ultima riga di un file?

Изменение Уровней   BlueLine   RedLine
2018.02.26 12:42    1.24140    1.22391
2018.02.26 12:42    1.24919    1.22029
2018.02.26 12:43    1.25471    1.22029
2018.02.26 12:43    1.25395    1.21649
2018.02.26 12:48    1.24539    1.21649
2018.02.26 12:49    1.24368    1.22581

ConFileReadDouble?

Ho bisogno solo dei valoriBlueLine eRedLine dell'ultima linea. ????

Lo stavo scrivendo in questo modo:

FileWrite(handle,TimeToStr(TimeCurrent()), "  ",B_level, "  ",R_level);
 
Rewerpool:

Puoi dirmi come leggere l'ultima riga di un file?

ConFileReadDouble?

Ho bisogno solo dei valoriBlueLine eRedLine dell'ultima linea. ????

Lo stavo scrivendo in questo modo:

Quando si apre il file per la scrittura si specifica TXT o CSV. Questo è un file di testo. Leggilo come una stringa, seleziona StringSubstr e convertilo in quello che ti serve