Quaisquer perguntas de recém-chegados sobre MQL4 e MQL5, ajuda e discussão sobre algoritmos e códigos - página 1816

 
Alexander Avksentyev #:

Algum lugar de entrada

Onde está o exterior

Entenda a diferença.

Anexe um arquivo. Não me apetece montar quebra-cabeças.

 
//+------------------------------------------------------------------+
//|                                                         Cova.mq4 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link        " https://www.mql5.com "
#property version    "1.00"
#property strict

string             _0_                = "Test" ;
extern string      _1_                = " МАРТИН 1 - вкл. 2 - выкл." ;
extern int         _2_                = 1 ;
extern string      _3_                = "множитель след. лота" ;
extern double   LotMultiplikator      = 1.667 ;
extern string      _4_                = "начальный лот:" ;
extern string      _5_                = "true - постоянный, false - от баланса" ;
extern bool     LotConst_or_not       = FALSE;
extern double   Lot                   = 0.01 ;
extern double   RiskPercent           = 30.0 ;
extern string      _6_                = "прибыль в пунктах - ТР" ;
input int      iTakeProfit           = 10 ;   //TakeProfit;
extern string      _7_                = "настройки трейлинга" ;
input int      iTrailStart           = 10 ;   //Кол-во пунктов для включения тралa;
input int      iTrailDist            = 10 ;   //Расстояние от стопа до рынка;
input int      iTrailStep            = 10 ;   //Шаг трейлинг стопа";
input int      iTrailTakeProfit      = 10 ;   //TakeProfit после включения трейлинга";
extern string      _8_                = "расстояние м/у ордерами" ;
input int      iStep                 = 10 ;   //Шаг;
extern double   StepCoef              = 1.5 ; //Множитель шага между ордерами";
extern string      _9_                = "МАX кол-во ордеров" ;
input    int      MaxTrades             = 30 ;
extern string      _10_               = "Ограничение потерь" ;
extern bool     UseEquityStop         = FALSE;
extern double   TotalEquityRisk       = 20.0 ;
extern string      _11_               = "Идентификатор ордера" ;
extern int       Magic                = 12345 ;
extern string      _12_               = "логотип и вывод данных" ;
extern bool     ShowTableOnTesting    = TRUE;
extern string      _13_               = "(true-вкл.,false-выкл.)" ;
extern int      iSlippage             = 5 ;
extern int      MinOrders             = 1000 ; //АвтоРассчётЛота;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//

int       Login = 4950287 ;
datetime time  = D'2022.01.01 00:00:00' ;
string    name  = "AutoP_v.3.0" ;
datetime time1 = 0 ;
double    TP, lastlot, minlot;
int       Forder;
int       TakeProfit,TrailStart,TrailDist,TrailStep,TrailTakeProfit,Step,Slippage;
double    level_count= 0 ;
int iDistTrail = iTrailDist;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//Torder-Цена открытия первого ордера
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
{
     if (AccountNumber() != Login)
       {
         int close = MessageBox ( "Неверный номер счёта" , "Ошибка" , MB_OK | MB_ICONSTOP );
         return ( INIT_FAILED );
       } else (AccountNumber() == Login);
             {
               int close = MessageBox ( "Проверка прошла успешно.Экcперт может приступить к работе." , "Инициализация" , MB_OK | MB_ICONEXCLAMATION );
             }
 //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//  
     if ( TimeCurrent () > time)
        {
         int close = MessageBox ( "Время работы закончилось!!!" , "Время работы" , MB_OK | MB_ICONSTOP );
         return ( INIT_FAILED );
        } else ( TimeCurrent () < time);
             {
               int close = MessageBox ( "Проверка времени работы прошла успешно.Эксперт может приступить к работе!" , "Время работы" , MB_OK | MB_ICONEXCLAMATION );
             }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
      TakeProfit         =iTakeProfit;
      TrailStart         =iTrailStart;
      TrailDist          =iTrailDist;
      TrailStep          =iTrailStep;
      TrailTakeProfit    =iTrailTakeProfit;
      Step               =iStep;
      Slippage           =iSlippage;
      
 //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//   
     if ( Digits == 3 || Digits == 5 )
       {
        TakeProfit      *= 10 ;
        TrailStart      *= 10 ;
        TrailDist       *= 10 ;
        TrailStep       *= 10 ;
        TrailTakeProfit *= 10 ;
        Step            *= 10 ;
        Slippage        *= 10 ;
       }
       return ( INIT_SUCCEEDED );
    }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+

void OnTick ()
  {
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
 /*  Comment( 
  "\n",                      name,
  "\n", 
  " ",                       Symbol(),  
  "\n",
  "Тайм Фрейм ",             Period(),
  "\n",                      AccountCompany(),
  "\n",
  "\n ",                     AccountServer(),
  "\n", 
  "Lots\n",                  B_S_Lot(),
  "\n",
  "Price ",                  Bid,
  "\n", 
  "Дата ",                   TimeToString( TimeCurrent(), TIME_DATE ),
  "\n",
  "Server Time ",            TimeToString( TimeCurrent(), TIME_SECONDS ),
  "\n", 
  "Profit ",                 Profit(),
  "\n",
  "AvTP ",                   CalcTP (),
  "\n", 
  "Количество ордеров ",     CountTrades(),
  "\n",
  "\n ",                     GetVolumeLotLastOrder(),
  "\n",
  "\n", "Процент просадки ", NormalizeDouble(  (AccountInfoDouble(ACCOUNT_BALANCE)-AccountInfoDouble(ACCOUNT_MARGIN_FREE))/AccountInfoDouble(ACCOUNT_BALANCE)*100,2)
  );*/ 
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
   double body = Close[ 1 ] - Open[ 1 ];
   if (CountTrades() == 0 && body > 0 ) BuyOpen();     // Если нет открытых и сигнал бай
   if (CountTrades() == 0 && body < 0 ) SellOpen();     // Если нет открытых и сигнал селл
   if (CountTrades( 0 ) > 0 && body > 0 ) BuyOpen();     // Если есть открытые бай и сигнал бай
   if (CountTrades( 1 ) > 0 && body < 0 ) SellOpen();     // Если есть открытые селл и сигнал селл
   if (iTrailStart<MarketInfo( Symbol (),MODE_STOPLEVEL))
 /*  iTrailStart= MarketInfo(Symbol(), MODE_STOPLEVEL * Point);
   iTrailSL();
 */ 
   if (iDistTrail<MarketInfo( Symbol (),MODE_STOPLEVEL))
   iDistTrail = MarketInfo( Symbol (),MODE_STOPLEVEL);
  }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void BuyOpen() //Открытие позиции Buy
  {
   Forder = ( OrderSend ( _Symbol ,OP_BUY,Lot,Ask,iSlippage, 0 , 0 , "Коммент" ,Magic, 0 ,Blue));
   if (Forder > 0 )
     {
       Print ( "Открыта Позиция BUY" );
       if ( OrderSelect (Forder, SELECT_BY_TICKET))
        {
         TP = NormalizeDouble ((Ask+iTakeProfit* _Point ), _Digits );
         if (OrderModify(OrderTicket(),OrderOpenPrice(), 0 ,TP, 0 ))
             Print ( "Ордер Модифицирован BUY " ); 
         else 
             Print ( "Ошибка Модификации Ордера BUY = " , GetLastError ());
        }
     }
   else Print ( "Ошибка Открытия Позиции BUY" );
  }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
void SellOpen() //Открытие позиции Sell  
  {
   Forder = ( OrderSend ( _Symbol ,OP_SELL,Lot,Bid,iSlippage, 0 , 0 , "Коммент Sell" ,Magic, 0 ,Red));
   if (Forder > 0 )
     {
       Print ( "Открыта Позиция SELL" );
       if ( OrderSelect (Forder, SELECT_BY_TICKET))
        {
         TP = NormalizeDouble ((Bid-iTakeProfit* _Point ), _Digits );
         if (OrderModify(OrderTicket(),OrderOpenPrice(), 0 ,TP, 0 ))
             Print ( "Ордер Модифицирован SELL " ); 
         else 
             Print ( "Ошибка Модификации Ордера SELL = " , GetLastError ());
        }
     }
   else Print ( "Ошибка Открытия Позиции SELL" );
  }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//+------------------------------------------------------------------+
//| Tester function                                                  |
//+------------------------------------------------------------------+
double OnTester ()
  {
//---
   double ret= 0.0 ;
//---

//---
   return (ret);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Подсчет открытых ордеров по типу                                 |
//+------------------------------------------------------------------+
int CountTrades( int ot=- 1 ) 
  {
   int cnt= 0 ;
   int i= OrdersTotal ()- 1 ;
   for ( int pos=i;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos,SELECT_BY_POS,MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol )
           {
             if (OrderMagicNumber()==Magic)
              {
               if (OrderType()==ot||ot==- 1 ) cnt++;
              }
           }
        }
     }
   return (cnt);
  }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//+----------------------------------------------------------------------------+
//|                             Трейлинг стоп                                  |//off
//+----------------------------------------------------------------------------+
/*void iTrailSL()
{
   if (iTrailStart <= 0.0 || iTrailStep <= 0.0)
      return; 
      
   double sl_lev;
         
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS,MODE_TRADES))
         continue;
      
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != Magic)
         continue;  
         
      if(OrderType() == OP_BUY) 
      {
         if (NormalizeDouble(Bid - OrderOpenPrice(),Digits) < iTrailStart * MarketInfo(Symbol(),MODE_POINT) )
            continue;

         if (OrderStopLoss() >= OrderOpenPrice() || NormalizeDouble(Bid - OrderStopLoss(), Digits()) < iTrailDist * MarketInfo(Symbol(),MODE_POINT))
            continue;

         if (OrderStopLoss() == 0.0 || NormalizeDouble((Bid - OrderStopLoss()) - iTrailDist * MarketInfo(Symbol(),MODE_POINT),Digits) < iTrailStep * MarketInfo(Symbol(),MODE_POINT))
            continue;

         sl_lev = Bid - iTrailDist * MarketInfo(Symbol(),MODE_POINT);
         if (NormalizeDouble(Bid - sl_lev,Digits) < MarketInfo(Symbol(),MODE_STOPLEVEL))
            continue;
            
         if (!OrderModify(OrderTicket(), OrderOpenPrice(), sl_lev, OrderTakeProfit(), 0, clrRed))
            Print("Не удалось модифицировать стоплосс ордера №",OrderTicket(),". Ошибка: ",GetLastError());
      }

      /*if(OrderType() == OP_SELL)
             {
              if(OrderProfit() + OrderSwap() + OrderCommission() > MarketInfo(Symbol(), MODE_TICKVALUE) * iTrailStart * OrderLots())return;
                {
                 if(NormalizeDouble((OrderProfit() - Ask),_Digits) >= iTrailStart)return;
                   {
                    if(OrderStopLoss() > Ask + iTrailDist*Point || OrderStopLoss()==0)return;
                      {
                       if(iTrailStep > 0.0 && OrderStopLoss() == 0.0 && NormalizeDouble((OrderStopLoss() - Ask) - iTrailDist * Point(),_Digits) < iTrailStep * Point())return;
                         {
                          sl_lev = NormalizeDouble(Ask + iTrailDist * Point(),_Digits);
                          double iprice=NormalizeDouble(Ask + sl_lev,Digits);
                          if(iprice > MarketInfo(Symbol(),MODE_STOPLEVEL) * Point) return;
                            {
                            if(OrderModify(Forder, OrderOpenPrice(),sl_lev,OrderTakeProfit(), OrderExpiration()))
                            Print("Не удалось модифицировать стоплосс ордера №",OrderTicket(),". Ошибка: ",GetLastError());
}}}}}}}}*/
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//
//+----------------------------------------------------------------------------+
//|                             Трейлинг стоп                                  |
//+----------------------------------------------------------------------------+
void TrailSL()
  {
   if (iTrailStart <= 0 ) return ; 
      
   double sl_lev;
         
   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 ((OrderStopLoss() == 0 && Bid > OrderOpenPrice() + iTrailStart * _Point )||(OrderStopLoss() != 0 && Bid > OrderStopLoss() + (iDistTrail+iTrailStep) * _Point ))
                 {
                  sl_lev = NormalizeDouble (Bid - iDistTrail * _Point , Digits );
                   if (OrderModify(OrderTicket(), OrderOpenPrice(), sl_lev, OrderTakeProfit(), 0 , clrRed ))
                     Print ( "Удачная модифиция стоплосс ордера №" ,OrderTicket());
                   else
                     Print ( "Не удалось модифицировать стоплосс ордера №" ,OrderTicket(), ". Ошибка: " , GetLastError ());
                 }
              }
             if (OrderType() == OP_SELL) 
              {
               if ((OrderStopLoss() == 0 && Ask < OrderOpenPrice() - iTrailStart * _Point )||(OrderStopLoss() != 0 && Ask < OrderStopLoss() - (iDistTrail+iTrailStep) * _Point ))
                 {
                  sl_lev = NormalizeDouble (Ask + iDistTrail * _Point , Digits );
                   if (OrderModify(OrderTicket(), OrderOpenPrice(), sl_lev, OrderTakeProfit(), 0 , clrRed ))
                     Print ( "Удачная модифиция стоплосс ордера №" ,OrderTicket());
                   else
                     Print ( "Не удалось модифицировать стоплосс ордера №" ,OrderTicket(), ". Ошибка: " , GetLastError ());
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
 
Alexander Avksentyev #:

Você sabe sobre este botão?


 
Alexander Avksentyev #:

Aqui está o código, talvez eu esteja especificando algo errado, mas não há nenhum efeito.

Você comentou a rede de arrasto!!!

 /*  iTrailStart= MarketInfo(Symbol(), MODE_STOPLEVEL * Point);
   iTrailSL();
 */ 
 
Tretyakov Rostyslav #:

Você sabe sobre este botão?


ok

Arquivos anexados:
Test34.mq4  37 kb
 
Tretyakov Rostyslav #:

Foi você quem recomendou a rede de arrasto!!!

há vários

 
Alexander Avksentyev #:

há vários

Você comentou a rede de arrasto em OnTick()
 
Tretyakov Rostyslav #:
Você comentou a rede de arrasto em OnTick()

Havia duas redes de arrasto, uma sua e uma minha, desmontadas.

Arrumou tudo. Está funcionando.

Eu apaguei tudo e o reescrevi.

Obrigado por sua ajuda!

Vou continuar cavando para descobrir porque a antiga rede de arrasto não funcionava.

 
Alexander Avksentyev #:

Havia duas redes de arrasto, uma sua e uma minha, desmontadas.

Arrumou tudo. Está funcionando.

Eu apaguei tudo e o reescrevi.

Obrigado por sua ajuda!

Vou continuar cavando para descobrir porque a antiga rede de arrasto não funcionava.

Eu vi que havia duas redes de arrasto, mas você comentou sobre a rede de arrasto.
 


Não está muito claro o que significa "ativo". Inclui ordens de mercado aceitas pelo servidor mas ainda não executadas? Onde a documentação diz isso?