Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам - страница 1614

 
Fast235 #:

вызывает вопрос только эта строка

-50 лишние и массив

Это чтобы рисовало выше/ниже "0"

но можно и без этого, мне сама суть нужна, как пользоваться хендлами.

 
Vladimir Simakov #:

Настоятельно рекомендую:

Иначе упс получится)))

Плюсую, сразу до целого привести правильно после деления. Иначе двоичное счисление может много чего наделать)))

 
MakarFX #:

Это чтобы рисовало выше/ниже "0"

но можно и без этого, мне сама суть нужна, как пользоваться хендлами.

хендл это указатель на файл индикатора, создается в OnInit() обычно

   Handle=iCustom(Symbol(),PERIOD_H1,"_iTrend",10);
//--- Если не удалось получить хендл индикатора
   if(Handle==INVALID_HANDLE)
     {
      PrintFormat("Failed to create handle of the iAO indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //---
      return(INIT_FAILED);
     }

дальше по коду

    if(CopyBuffer(Handle,0,1,1,Buffer1) <=0 проверка на ошибку
---
в Buffer1[1111] получаем значение
 
Fast235 #:

хендл это указатель на файл индикатора, создается в OnInit() обычно

дальше по коду

Спасибо, но это похоже на справку и к сожалению мне не понятно(

я поэтому и попросил перевести мой код в mql5 чтобы самому разобрать логику работы

я пока делаю так

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   prd = _Period > TimeFrame ? _Period : TimeFrame;
   atrHandle = iATR(_Symbol, prd, Per_Count);
   if(atrHandle == INVALID_HANDLE)
     {
      Print("Can't load indicator."); return INIT_FAILED;
     }
//--- indicator buffers mapping
   SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
   SetIndexBuffer(1,Label2Buffer,INDICATOR_DATA);
   
   ArraySetAsSeries(Label1Buffer, true);
   ArraySetAsSeries(Label2Buffer, true);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   int limit,i;
   int barPlus=iBarShift(_Symbol,_Period,iTime(_Symbol,PERIOD_W1,WeekCount),false);
   limit=rates_total-prev_calculated-3;
   if(WeekCount!=0)limit=barPlus-1;
   if(limit<1) return(0);
   for(i=limit;i>=0;i--)
     {
      TimeToStruct(time[i],inTime);
      index01=iBarShift(_Symbol,PERIOD_D1,time[i],false);
      if(inTime.hour==0&&inTime.min==0)
        {
         Label1Buffer[i]=GetIndicator(atrHandle, index01+1);
        }
     }
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
double GetIndicator(const int handle, const int i)
  {
   double res[1];
   if(CopyBuffer(handle, 0, i, 1, res) <= 0) return 0;
   return res[0];
  }
//+------------------------------------------------------------------+

но ощущение, что что-то не так, а iMAOnArray вообще не нашел в справке.

 

добрый день.

не могу решить проблему с зацикливанием мартина,

отключается после исполнения :(n>=OrdersClose)- и далее мартин не включается пока не произойдет прибыльная сделка, 

а мне нужно, чтобы после  исполнения :  (n>=OrdersClose) происходил  - return(dLots)и мартин запускался снова если следующая сделка снова убыточная.

подскажите пожалуйста как организовать?

double LOT()
{
   int n=0;
   double OL=dLots;
   for (int j = OrdersHistoryTotal()-1; j >= 0; j--)
   {
      if (OrderSelect(j, SELECT_BY_POS,MODE_HISTORY))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == iMagic)
         {
            if (OrderProfit()<0) 
            {
               if (n==0) OL=NormalizeDouble(OrderLots()*K_Martin,DigitsLot);
               n++;
               if (n>=OrdersClose) {return(dLots);}
            }
            else
            {
               if (n==0) {return(dLots);}
               else {return(OL);}
            }
         }
      }
   }
   return(OL);
}
 

Всем доброго времени суток!!!

Подскажите пожалуйста в коде сеточного советника прописал отображение средней цены на графике. Всё бы ничего но не корректно удаляется линия после закрытия сетки то есть средой цены нет. пожалуйста подскажите что я сделал не так. Вот код и картинка. 

//+----------------------------------------------------------------------------+
//| Модификация групповых ордеров                                              |
//+----------------------------------------------------------------------------+
void ModifyOrders(int otype)
{
    double avg_price, AveragePriceBuy, AveragePriceSell, order_lots = 0;
    price = 0;
   
    for(int i = OrdersTotal()-1; i>=0; i--)
    {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
       {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
         {
            price += OrderOpenPrice() * OrderLots();
            order_lots += OrderLots() ;
         }
       }
    }
    avg_price = NormalizeDouble(price / order_lots, Digits);
    AveragePriceBuy = NormalizeDouble(avg_price + Spread, Digits);
    AveragePriceSell = NormalizeDouble(avg_price - Spread, Digits);
     {
     ObjectDelete(0, "AveragePriceLine");
     ObjectCreate("AveragePriceLine" ,OBJ_HLINE, 0, 0 ,AveragePriceBuy);
      ObjectCreate("AveragePriceLine" ,OBJ_HLINE, 0, 0 ,AveragePriceSell);
     ObjectSet("AveragePriceLine",OBJPROP_COLOR,Blue);
     }
    if ((otype == OP_BUY) && (Drawdown <= DrawdownClosingTakeprofitZero)) 
    tp = NormalizeDouble (AveragePriceBuy + TakeProfitGroupOrder*Point, Digits);
    if ((otype == OP_SELL) && (Drawdown <= DrawdownClosingTakeprofitZero))
    tp = NormalizeDouble (AveragePriceSell - TakeProfitGroupOrder*Point, Digits);
    if ((otype == OP_BUY) && (Drawdown > DrawdownClosingTakeprofitZero)) 
    tp = NormalizeDouble (AveragePriceBuy, Digits);
    if ((otype == OP_SELL) && (Drawdown > DrawdownClosingTakeprofitZero))
    tp = NormalizeDouble (AveragePriceSell, Digits);
    
    for(int i = OrdersTotal()-1; i>=0; i--) 
    {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
       {
           if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
           {
               if(OrderModify(OrderTicket(), OrderOpenPrice(), 0, tp, 0))
                  Print("Ордера успешно модифицированы!");
                else Print("Ошибка модификации ордеров!");
           }
       }
    }
}   


 
EVGENII SHELIPOV #:

Всем доброго времени суток!!!

Подскажите пожалуйста в коде сеточного советника прописал отображение средней цены на графике. Всё бы ничего но не корректно удаляется линия после закрытия сетки то есть средой цены нет. пожалуйста подскажите что я сделал не так. Вот код и картинка.

Попробуй так

//+----------------------------------------------------------------------------+
//| Модификация групповых ордеров                                              |
//+----------------------------------------------------------------------------+
void ModifyOrders(int otype)
{
    double avg_price, AveragePriceBuy, AveragePriceSell, order_lots = 0;
    price = 0;
   
    for(int i = OrdersTotal()-1; i>=0; i--)
    {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
       {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
         {
            price += OrderOpenPrice() * OrderLots();
            order_lots += OrderLots() ;
         }
       }
    }
    avg_price = NormalizeDouble(price / order_lots, Digits);
    AveragePriceBuy = NormalizeDouble(avg_price + Spread, Digits);
    AveragePriceSell = NormalizeDouble(avg_price - Spread, Digits);
    if(ObjectFind(0,"AveragePriceLineBuy")==0)
     {
     ObjectDelete(0,"AveragePriceLineBuy");
     ObjectCreate(0,"AveragePriceLineBuy" ,OBJ_HLINE, 0, 0 ,AveragePriceBuy);
     ObjectSetInteger(0,"AveragePriceLine",OBJPROP_COLOR,Blue);
     }
    else
     {
     ObjectCreate(0,"AveragePriceLineBuy" ,OBJ_HLINE, 0, 0 ,AveragePriceBuy);
     ObjectSetInteger(0,"AveragePriceLine",OBJPROP_COLOR,Blue);
     }
    if(ObjectFind(0,"AveragePriceLineSell")==0)
     {
     ObjectDelete(0,"AveragePriceLineSell");
     ObjectCreate(0,"AveragePriceLineSell" ,OBJ_HLINE, 0, 0 ,AveragePriceSell);
     ObjectSetInteger(0,"AveragePriceLine",OBJPROP_COLOR,Blue);
     }
    else
     {
     ObjectCreate(0,"AveragePriceLineSell" ,OBJ_HLINE, 0, 0 ,AveragePriceSell);
     ObjectSetInteger(0,"AveragePriceLine",OBJPROP_COLOR,Blue);
     }
    if ((otype == OP_BUY) && (Drawdown <= DrawdownClosingTakeprofitZero)) 
    tp = NormalizeDouble (AveragePriceBuy + TakeProfitGroupOrder*Point, Digits);
    if ((otype == OP_SELL) && (Drawdown <= DrawdownClosingTakeprofitZero))
    tp = NormalizeDouble (AveragePriceSell - TakeProfitGroupOrder*Point, Digits);
    if ((otype == OP_BUY) && (Drawdown > DrawdownClosingTakeprofitZero)) 
    tp = NormalizeDouble (AveragePriceBuy, Digits);
    if ((otype == OP_SELL) && (Drawdown > DrawdownClosingTakeprofitZero))
    tp = NormalizeDouble (AveragePriceSell, Digits);
    
    for(int i = OrdersTotal()-1; i>=0; i--) 
    {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
       {
           if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
           {
               if(OrderModify(OrderTicket(), OrderOpenPrice(), 0, tp, 0))
                  Print("Ордера успешно модифицированы!");
                else Print("Ошибка модификации ордеров!");
           }
       }
    }
}   

А лучше прописать,

если нет открытых ордеров селл, то удалить линию селл...

аналогично для бая

 
Добрый вечер, как сбрасывать состояние графической кнопки при клике, чтобы она не была потом нажатой всё время пока ещё раз не кликнешь?
 
Nerd Trader #:
Добрый вечер, как сбрасывать состояние графической кнопки при клике, чтобы она не была потом нажатой всё время пока ещё раз не кликнешь?
ObjectSetInteger(0,name,OBJPROP_STATE,false);
 
MakarFX #:
Не, вы не так поняли. Мне нужно чтобы состояние сбрасывалось как у нормальных кнопок после отжатия клика. Как это реализовать, если в mql4 нет событий состояния клавиш мыши: нажатие/отжатие.
Причина обращения: