新人对MQL4和MQL5的任何问题,对算法和代码的帮助和讨论 - 页 1568

 
Alexey Viktorov:

识别码为CHART_PRICE_MIN 和CHART_PRICE_MAX。

似乎正是我所需要的。
 
MakarFX:

返回true/false , 我们谈论的是什么时间?

该类存储了前一个刻度的时间,真/假不是由该类返回,而是由该类的 一个成员函数返回。

void OnTick()
{
    if (NB_M1.IsNewBar())  // (1) Если появился новый бар M1
        {....}
    ......
}
 
Mikhail Tkachev:

该类存储了前一个刻度的时间,真/假不是由该类返回,而是由该类的 一个成员函数返回。

在你发布的代码中,只有公共栏!

鉴于该类报告了一个新的酒吧,时间是iTime(所有你需要的,0)。

iTime(all you need,1)分别为上一次的时间。

Z.U. 也许你知道如何用几分之一秒来获得时间...

 
MakarFX:

在你发布的代码中,publc只有bool!

鉴于该类报告了一个新的酒吧,时间是iTime(所有你需要的,0)。

iTime(all you need,1)分别为上一次的时间。

Z.U. 也许你知道如何用几分之一秒来获得时间...

我的错误,对不起

,我不需要几分之一秒的时间。我需要抓住一个新酒吧的第一秒

 
Mikhail Tkachev:

错了一点,对不起

,我不需要几分之一秒的时间。我需要抓住一个新酒吧的第一秒

像这样

datetime NB_M1;
int OnInit()
{
}

void OnTick()
{
   if (CIsNewBar(_Symbol,PERIOD_M1))  // (1) Если появился новый бар M1
        {NB_M1=TimeCurrent();}
    ......
}

并保存之前的值

datetime NB_01_M1, NB_02_M1;
int OnInit()
{
}

void OnTick()
{
   if (CIsNewBar(_Symbol,PERIOD_M1))  // (1) Если появился новый бар M1
        {NB_02_M1=NB_01_M1; NB_01_M1=TimeCurrent();}
    ......
}
 
MakarFX:

那么它就像这样

谢谢你,MakarFX,我将尝试一下)

 
законопослушный гражданин :

好的,谢谢,我会考虑并在测试器中运行它。

请告诉我更多关于代码中的马丁函数的信息。

我需要在哪里更换一些东西,以便马丁传播到有利可图的订单而不是无利可图的订单?

 //+------------------------------------------------------------------+
//|                                                 Citizen.v2.1.mq4 |
//|                                           Copyright 2020, DrMak. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, DrMak."
#property link        " https://www.mql5.com "
#property version    "1.00"
#property strict
//--- input parameters
input ENUM_TIMEFRAMES    timeframe_RSI  = PERIOD_H1 ;
input int                period_RSI     = 14 ;
input int                level_buy      = 30 ;
input int                level_sell     = 70 ;
input double             Lot            = 0.1 ;   // Размер стартового лота
input double             K_Martin       = 2.0 ;   // Размер увеличения лота(Мартин) 
input int                Stoploss       = 100 ;   // Размер StopLoss в пунктах
input int                Takeprofit     = 500 ;   // Размер TakeProfit в пунктах
input double             CountLoss      = 200 ;   // Размер максимального убытка
input double             CountProfit    = 300 ;   // Размер минимального профита
input int                Magic          = 777 ;   // Магик
input int                DigitsLot      = 2 ;     // Шаг лота
input int                slippage       = 3 ;     // Проскальзывание
//---
string AC;
datetime Start;
double AB,MINLOT,MAXLOT,RSI1,RSI0,SL,TP,sl,tp;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- create timer
   ObjectsDeleteAll ( 0 , "lab_" );
   EventSetMillisecondTimer ( 500 );
   Start  = TimeCurrent ();
   MINLOT = MarketInfo( Symbol (),MODE_MINLOT);
   MAXLOT = MarketInfo( Symbol (),MODE_MAXLOT);
   AC     = StringConcatenate ( " " , AccountCurrency());
   AB     = AccountInfoDouble ( ACCOUNT_BALANCE );
   int Y= 20 ;
   CreateButton( 0 , "lab_Button" , 0 , 79 ,Y, 77 , 25 , CORNER_RIGHT_UPPER , "Советник остановлен" , "START" , "Arial Black" , 10 , clrWhite , clrGreen ,
   false , false , false , false , false , 0 );Y += 25 ;
   DrawLABEL( "lab_Торговля"    , 1 , 5 ,Y, clrRed , "Торговля " );Y += 20 ;
   DrawLABEL( "lab_Start Time" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Start Time: " ,TimeToStr(Start, TIME_DATE | TIME_SECONDS )));Y += 15 ;
   DrawLABEL( "lab_Current Lot" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Current Lot: " ,DoubleToStr(Lots(),DigitsLot)));Y += 15 ;
   DrawLABEL( "lab_Balance"     , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Balance: " ,DoubleToStr(AccountBalance(), 2 ),AC));Y += 15 ;
   DrawLABEL( "lab_Equity"      , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Equity: " ,DoubleToStr(AccountEquity(), 2 ),AC));Y += 15 ;
   DrawLABEL( "lab_FreeMargin" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "FreeMargin: " ,DoubleToStr(AccountFreeMargin(), 2 ),AC));Y += 30 ;
   DrawLABEL( "lab_Take"        , 1 , 5 ,Y, clrLime , "Profit: " );
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//--- destroy timer
   EventKillTimer ();
   if (!IsTesting()) 
     {
       ObjectsDeleteAll ( 0 , "lab_" );
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   if (IsTesting()) 
     {
       if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== true )
        {
         ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrRed );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник запущен" );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "STOP" );
        }
       if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== false )
        {
         ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrGreen );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник остановлен" );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "START" );
         Start = iTime ( _Symbol , PERIOD_D1 , 0 );
        }
     }
   if (GetProfitFromStart()>CountProfit || GetProfitFromStart()<CountLoss*- 1 )
     {
       if (IsTesting()) 
        {
         CloseOrder(); ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_STATE , false );
        }
       else
        {
         CloseOrder();
        }
     }
   // Обновляем текст на лейблах
   DrawLABEL( "lab_Start Time" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Start Time: " ,TimeToStr(Start, TIME_DATE | TIME_SECONDS )));
   DrawLABEL( "lab_Current Lot" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Current Lot: " ,DoubleToStr(Lots(),DigitsLot)));
   DrawLABEL( "lab_Balance"     , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Balance: " ,DoubleToStr(AB, 2 ),AC));
   DrawLABEL( "lab_Equity"      , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Equity: " ,DoubleToStr(AccountEquity(), 2 ),AC));
   DrawLABEL( "lab_FreeMargin" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "FreeMargin: " ,DoubleToStr(AccountFreeMargin(), 2 ),AC));
   DrawLABEL( "lab_Take"        , 1 , 5 , 0 ,Color(GetProfitFromStart()> 0 ,Lime,Red), StringConcatenate ( "Profit: " ,DoubleToStr(GetProfitFromStart(), 2 ),AC));
   //---
   sl  = MathMax (Stoploss, MarketInfo( _Symbol , MODE_STOPLEVEL)) * Point ();
   SL  = NormalizeDouble (sl* Point (), Digits );
   tp  = MathMax (Takeprofit, MarketInfo( _Symbol , MODE_STOPLEVEL)) * Point ();
   TP  = NormalizeDouble (tp* Point (), Digits );
   //---
   if (CountOrders()== 0 && ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE ))
     {
       if (TradeSignal()>= 0 )
        {
         SendOrder(TradeSignal());
        }
     }
   //---
   if (!IsTradeAllowed()) 
     {DrawLABEL( "lab_Торговля" , 0 , 0 , 0 , clrRed , "Торговля запрещена" ); return ;} 
   else
     {DrawLABEL( "lab_Торговля" , 0 , 0 , 0 , clrLime , "Торговля разрешена" );}
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer ()
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Сигнал для открытия ордера                                       |
//+------------------------------------------------------------------+
int TradeSignal() 
  {
   int sig=- 1 ;
   // Здесь расчет сигнала
   RSI0= iRSI ( NULL ,timeframe_RSI,period_RSI, PRICE_CLOSE , 0 );
   RSI1= iRSI ( NULL ,timeframe_RSI,period_RSI, PRICE_CLOSE , 1 );
   // Здесь определение направления сигнала sig=0-BUY, sig=1-SELL
   if (RSI0>=level_buy && RSI1<=level_buy)   sig= 0 ;
   if (RSI0<=level_sell && RSI1>=level_sell) sig= 1 ;
   return (sig);
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent ( const int id,
                   const long &lparam,
                   const double &dparam,
                   const string &sparam)
  {
//---
   if (sparam== "lab_Button" ) TradeButton();
  }
//+--------------------------------------------------------------------------------------------------------------------+
//| ButtonSTART                                                                                                        |
//+--------------------------------------------------------------------------------------------------------------------+
void TradeButton()
  {
   if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== true )
     {
       ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrRed );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник запущен" );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "STOP" );
     }
   if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== false )
     {
       ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrGreen );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник остановлен" );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "START" );
      Start = TimeCurrent ();
     }
  }
//+------------------------------------------------------------------+
//| Расчет лота                                                      |
//+------------------------------------------------------------------+
double Lots()
  {
   double L= 0 ;
   if (GetInfoLastPos( 3 )>Start && GetInfoLastPos( 2 )< 0 )
     {L= NormalizeDouble (GetInfoLastPos( 1 )*K_Martin,DigitsLot);}
   else
     {L=Lot;}
   
   if (L>MAXLOT) L = MAXLOT;
   if (L<MINLOT) L = MINLOT;
   return (L);
  }
//+----------------------------------------------------------------------------+
//|  Функция возвращает по символу и магику                                    |
//|  размер профита с учетом комиссии и свопа с начала цикла                   |
//+----------------------------------------------------------------------------+
double GetProfitFromStart()
  {
   double lp= 0 ,cp= 0 ;
   for ( int i= 0 ; i<OrdersHistoryTotal(); i++)
     {
       if ( OrderSelect (i, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if (Start<OrderCloseTime()) {lp+=OrderProfit()+OrderCommission()+OrderSwap();}
              }
           }
        }
     }
   for ( int pos= OrdersTotal ()- 1 ;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL) {cp=OrderProfit()+OrderCommission()+OrderSwap();}
           }
        }
     }
   return (lp+cp);
  }
//+----------------------------------------------------------------------------+
//|  Функция возвращает по символу и магику                                    |
//|  1 - размер лота последней закрытой позиции                                |
//|  2 - размер профита с учетом комиссии и свопа последней закрытой позиции   |
//|  3 - время последней закрытой позиции                                      |
//+----------------------------------------------------------------------------+
double GetInfoLastPos( int a= 1 )
  {
   datetime t= 0 ;
   double result= 0 ,l= 0 ,p= 0 ,f= 0 ;
   int i=OrdersHistoryTotal();
   for ( int pos= 0 ; pos<i; pos++)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if (t<OrderCloseTime()) {t=OrderCloseTime(); l=OrderLots(); p=OrderProfit()+OrderCommission()+OrderSwap();}
              }
           }
        }
     }
   if (a== 1 ) {result=l;} else
   if (a== 2 ) {result=p;} else
   if (a== 3 ) {result=( double )t;}
   else      {result= 0 ;}
   return (result);
  }
//+------------------------------------------------------------------+
//| Подсчет открытых ордеров                                         |
//+------------------------------------------------------------------+
int CountOrders() 
  {
   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) cnt++;
           }
        }
     }
   return (cnt);
  }
//+------------------------------------------------------------------+
//| Открытие ордера                                                  |
//+------------------------------------------------------------------+
void SendOrder( int so= 0 ) 
  {
   if (so== 0 )
     {
       if ( OrderSend ( Symbol (),OP_BUY, Lots(),Ask,slippage,Ask-sl,Ask+tp, NULL ,Magic, 0 , clrBlue ))
        { Print ( "Open Buy: " , _Symbol );} else { Print ( "Error Open Buy: " , _Symbol , " / " , GetLastError ());}
     }
   if (so== 1 )
     {
       if ( OrderSend ( Symbol (),OP_SELL, Lots(),Bid,slippage,Bid+sl,Bid-tp, NULL ,Magic, 0 , clrBlue ))
        { Print ( "Open Sell: " , _Symbol );} else { Print ( "Error Open Sell: " , _Symbol , " / " , GetLastError ());}
     }
  }
//+------------------------------------------------------------------+
//| Закрытие открытого ордера                                        |
//+------------------------------------------------------------------+
void CloseOrder() 
  {
   int i= OrdersTotal ()- 1 ;
   for ( int pos=i;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY)
              {
               if (OrderClose(OrderTicket(),OrderLots(),Bid,slippage, clrBlue )) TradeButton();
              }
             if (OrderType()==OP_SELL)
              {
               if (OrderClose(OrderTicket(),OrderLots(),Ask,slippage, clrRed )) TradeButton();
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Установка цвета                                                  |
//+------------------------------------------------------------------+
color Color( bool P, color a, color b)
  {
   if (P) return (a);
   else return (b);
  }
//+------------------------------------------------------------------+
//| Установка лейблов/текста                                         |
//+------------------------------------------------------------------+
void DrawLABEL( string name, int CORNER, int X, int Y, color clr, string Name)
  {
   if ( ObjectFind ( 0 ,name)!= 0 )
     {
       ObjectCreate ( 0 ,name, OBJ_LABEL , 0 , 0 , 0 );
      ObjectSet(name, OBJPROP_CORNER , CORNER);
      ObjectSet(name, OBJPROP_XDISTANCE , X);
      ObjectSet(name, OBJPROP_YDISTANCE , Y);
     }
   ObjectSetText(name,Name, 10 , "Arial" ,clr);
  }
//+--------------------------------------------------------------------------------------------------------------------+
//| Создает кнопку                                                                                                     |
//+--------------------------------------------------------------------------------------------------------------------+
bool CreateButton( const long               chart_ID= 0 ,               // ID графика
                   const string             name= "Button" ,             // имя кнопки
                   const int                sub_window= 0 ,             // номер подокна
                   const int                x= 0 ,                       // координата по оси X
                   const int                y= 0 ,                       // координата по оси Y
                   const int                width= 50 ,                 // ширина кнопки
                   const int                height= 18 ,                 // высота кнопки
                   const int                corner= 0 ,                 // угол графика для привязки
                   const string             tool= "TOOLTIP" ,           // TOOLTIP
                   const string             text= "Button" ,             // текст
                   const string             font= "Arial" ,             // шрифт
                   const int                font_size= 10 ,             // размер шрифта
                   const color              clr= clrBlack ,             // цвет текста
                   const color              back_clr= C'236,233,216' ,   // цвет фона
                   const bool               state= false ,               // нажата/отжата
                   const bool               back= false ,               // на заднем плане
                   const bool               selection= false ,           // выделить для перемещений
                   const bool               selected= false ,           // выделить для перемещений
                   const bool               hidden= true ,               // скрыт в списке объектов
                   const long               z_order= 0 )                 // приоритет на нажатие мышью
  {
//--- сбросим значение ошибки
   ResetLastError ();
//--- создадим кнопку
   if (! ObjectCreate (chart_ID,name, OBJ_BUTTON ,sub_window, 0 , 0 ))
     {
       Print ( __FUNCTION__ , ": не удалось создать кнопку! Код ошибки = " , GetLastError ()); return ( false );
     }
   ObjectSetInteger (chart_ID,name, OBJPROP_XDISTANCE ,x);
   ObjectSetInteger (chart_ID,name, OBJPROP_YDISTANCE ,y);
   ObjectSetInteger (chart_ID,name, OBJPROP_XSIZE ,width);
   ObjectSetInteger (chart_ID,name, OBJPROP_YSIZE ,height);
   ObjectSetInteger (chart_ID,name, OBJPROP_CORNER ,corner);
   ObjectSetString (chart_ID,name, OBJPROP_TOOLTIP ,tool);
   ObjectSetString (chart_ID,name, OBJPROP_TEXT ,text);
   ObjectSetString (chart_ID,name, OBJPROP_FONT ,font);
   ObjectSetInteger (chart_ID,name, OBJPROP_FONTSIZE ,font_size);
   ObjectSetInteger (chart_ID,name, OBJPROP_COLOR ,clr);
   ObjectSetInteger (chart_ID,name, OBJPROP_BGCOLOR ,back_clr);
   ObjectSetInteger (chart_ID,name, OBJPROP_BACK ,back);
   ObjectSetInteger (chart_ID,name, OBJPROP_STATE ,state);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTABLE ,selection);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTED ,selected);
   ObjectSetInteger (chart_ID,name, OBJPROP_HIDDEN ,hidden);
   ObjectSetInteger (chart_ID,name, OBJPROP_ZORDER ,z_order);
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
 
законопослушный гражданин:

请告诉我更多关于你代码中的Martin函数。

我应该在哪里替换什么,以便将马汀应用于盈利的订单而不是亏损的订单?

突出显示......如果<0,那么亏损交易的手数会增加

如果>0,那么盈利交易的手数就会增加

//+------------------------------------------------------------------+
//| Расчет лота                                                      |
//+------------------------------------------------------------------+
double Lots()
  {
   double L=0;
   if(GetInfoLastPos(3)>Start && GetInfoLastPos(2)<0)
     {L=NormalizeDouble(GetInfoLastPos(1)*K_Martin,DigitsLot);}
   else
     {L=Lot;}
   
   if(L>MAXLOT) L = MAXLOT;
   if(L<MINLOT) L = MINLOT;
   return(L);
  }
 
AMarkov:
这似乎是你所需要的。

这样做是不对的!这就是你如何获得仪器的最低和最高价格,而不是震荡器。一个有经验的程序员都不好意思对这样的初级问题给出这样的答案......。

事实上,你需要使用CopyBufer获得振荡器数据

    int s, len;
    double main[];
    double min, max;
    len = (int)ChartGetInteger(0, CHART_VISIBLE_BARS); // длина копируемых видимых значений
    s = (int)ChartGetInteger(0, CHART_FIRST_VISIBLE_BAR) - len + 1; // 1-й видимый бар минус длина -- начало копируемых баров
    if (CopyBuffer(handle, MAIN_LINE, s, len, main) != len)
      return;
    // handle - хэндэл осциллятора
    // MAIN_LINE - меняем на нужный индекс буфера осциллятора
    // получаем мин. и макс. значения
    min = main[ArrayMinimum(main, 0, WHOLE_ARRAY)];
    max = main[ArrayMaximum(main, 0, WHOLE_ARRAY)];
        

如何创建一个震荡器

handle = iMACD(NULL, PERIOD_CURRENT, 12, 26, 1, PRICE_CLOSE);

或任何其他你需要的振荡器。

 
MakarFX:

突出显示......如果<0,那么亏损交易的手数就会增加

如果>0,那么盈利交易的手数将增加。

非常感谢您

原因: