Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1543

 
Andy Dufresne:

Hi. Can you explain to a sucker how to initialise a structure array? For a normal array, it's simple

int HiddenFunc[3,2] = {1,2,3,4,5,6};

But what about the array of structures? Initialize an array with this structure, for example

struct MODE_KEY {string Key; bool Act;};

just like classes:
https://www.mql5.com/ru/docs/basis/types/classes


or arrays)

struct trade_settings
  {
   double take;         // значения цены фиксации прибыли
   double stop;         // значение цены защитного стопа
   uchar  slippage;     // значение допустимого проскальзывания
  };



   trade_settings ss[]={
                        {1.0, 2.0, 5},
                        {1.0, 2.0, 5},
                        {1.0, 2.0, 5}
                        };  
Документация по MQL5: Основы языка / Типы данных / Структуры, классы и интерфейсы
Документация по MQL5: Основы языка / Типы данных / Структуры, классы и интерфейсы
  • www.mql5.com
Структуры, классы и интерфейсы - Типы данных - Основы языка - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 

Hello.

testing owls. (the code is attached below).

owl uses martingale based on previous order history (if loss, then multiply the lot by the martin coefficient...).

the previous order was closed by a stop with e.g. 0.2 lot at (Martin = 2...). then I switch off "auto-trading" in the MT4 terminal, or switch off the terminal completely and the owl stops trading.

Then when I switch on the "auto-trading" button - Then the owl switches on and opens the next lot with a volume of 0.4.

So, how to correct the code, so that when you turn off "auto-trading", turn off the terminal and then turn it on, the owl starts the next trading session with the starting lot,

specified in the settings (e.g. 0.01) rather than multiplying the last closed one in the history?

//+------------------------------------------------------------------+
#property copyright "Copyright © 2018, http://cmillion.ru"
#property link      "cmillion@narod.ru"
#property strict
#property description "Советник открывает позиции по индикатору RSI после SL увеличивает лот"
#property description "Следующая сделка не открывается, пока не закрыта предыдущая"
//-------------------------------------------------------------------
extern ENUM_TIMEFRAMES timeframe_RSI = 60;
extern int    period_RSI   = 14;
extern int    level_buy    = 30;
extern int    level_sell   = 70;

extern double Lot          = 0.1;
extern double K_Martin     = 2.0;

extern int    Stoploss     = 10,
              Takeprofit   = 50;
extern int    OrdersClose  = 5;

extern int    Magic        = 0;
extern int    DigitsLot    = 2;
extern int    slippage     = 3;
//-------------------------------------------------------------------
string AC;
datetime OpenTime;
double MINLOT,MAXLOT;
//-------------------------------------------------------------------
void OnTick()
{
   if (!IsTradeAllowed()) 
   {
      DrawLABEL("Торговля",0,0,0,Red,"Торговля запрещена");
      return;
   } 
   else DrawLABEL("Торговля",0,0,0,Lime,"Торговля разрешена");

   //---

   double STOPLEVEL=MarketInfo(Symbol(),MODE_STOPLEVEL);
   //---
   double OSL,OTP,OOP,SL,TP,Profit=0;
   int b=0,s=0,tip;
   for (int i=0; i<OrdersTotal(); i++)
   {    
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
      { 
         if (OrderSymbol()==Symbol() && Magic==OrderMagicNumber())
         { 
            tip = OrderType(); 
            OSL = NormalizeDouble(OrderStopLoss(),Digits);
            OTP = NormalizeDouble(OrderTakeProfit(),Digits);
            OOP = NormalizeDouble(OrderOpenPrice(),Digits);
            SL=OSL;TP=OTP;
            Profit+=OrderProfit()+OrderCommission()+OrderSwap();
            if (tip==OP_BUY)             
            {  
               b++; 
               if (OSL==0 && Stoploss!=0)
               {
                  if ((Bid-NormalizeDouble(OOP - Stoploss * Point,Digits)) / Point>=STOPLEVEL) SL = NormalizeDouble(OOP - Stoploss * Point,Digits);
               } 
               if (OTP==0 && Takeprofit!=0)
               {
                  if ((NormalizeDouble(OOP + Takeprofit * Point,Digits)-Ask) / Point>=STOPLEVEL) TP = NormalizeDouble(OOP + Takeprofit * Point,Digits);
               } 
               if (SL != OSL || TP != OTP)
               {  
                  if (!OrderModify(OrderTicket(),OOP,SL,TP,0,White)) Print("Error OrderModify ",GetLastError());
               }
            }                                         
            if (tip==OP_SELL)        
            {
               s++;
               if (OSL==0 && Stoploss!=0)
               {
                  if ((NormalizeDouble(OOP + Stoploss * Point,Digits)-Ask) / Point>=STOPLEVEL) SL = NormalizeDouble(OOP + Stoploss   * Point,Digits);
               }
               if (OTP==0 && Takeprofit!=0)
               {
                  if ((Bid-NormalizeDouble(OOP - Takeprofit * Point,Digits)) / Point>=STOPLEVEL) TP = NormalizeDouble(OOP - Takeprofit * Point,Digits);
               }
               if (SL != OSL || TP != OTP)
               {  
                  if (!OrderModify(OrderTicket(),OOP,SL,TP,0,White)) Print("Error OrderModify ",GetLastError());
               }
            } 
         }
      }
   }
   
   
   //---
   
   double AB = AccountBalance();
   
   //---
   
   DrawLABEL("Balance"        ,1,5,0,clrGreen,StringConcatenate("Balance ",DoubleToStr(AB,2),AC));
   DrawLABEL("Equity"         ,1,5,0,clrGreen,StringConcatenate("Equity ",DoubleToStr(AccountEquity(),2),AC));
   DrawLABEL("FreeMargin"     ,1,5,0,clrGreen,StringConcatenate("FreeMargin ",DoubleToStr(AccountFreeMargin(),2),AC));
   DrawLABEL("Take"           ,1,5,0,Color(Profit>0,Lime,Red),StringConcatenate("Profit ",DoubleToStr(Profit,2),AC));
   
   double Lots=0,RSI1=0,RSI0=0;
   if (b+s==0)
   {
      RSI0= iRSI (NULL,timeframe_RSI,period_RSI,PRICE_CLOSE,0);
      RSI1= iRSI (NULL,timeframe_RSI,period_RSI,PRICE_CLOSE,1);
   }
   else return;

   //---
   if (RSI0>=level_buy && RSI1<=level_buy)
   {
      Lots=LOT();

      if (Lots>MAXLOT) Lots = MAXLOT;
      if (Lots<MINLOT) Lots = MINLOT;
      
      if(SendOrder(OP_BUY, Lots, NormalizeDouble(Ask,Digits)))OpenTime=iTime(NULL,timeframe_RSI,1); 
   }

   //---
   
   if (RSI0<=level_sell && RSI1>=level_sell)
   {
      Lots=LOT();

      if (Lots>MAXLOT) Lots = MAXLOT;
      if (Lots<MINLOT) Lots = MINLOT;

      if(SendOrder(OP_SELL, Lots, NormalizeDouble(Bid,Digits))) OpenTime=iTime(NULL,timeframe_RSI,1); 
   }
}
//------------------------------------------------------------------
bool SendOrder(int tip, double lots, double price, double sl=0, double tp=0)
{
   if (tip<2)
   {
      if (AccountFreeMarginCheck(Symbol(),tip,lots)<0)
      {
         Alert("Недостаточно средств");
         return(0);
      }
   }
   for (int i=0; i<10; i++)
   {    
      if (OrderSend(Symbol(),tip, lots,price,slippage,sl,tp,NULL,Magic,0,clrNONE)!=-1) return(1);
         Alert(" попытка ",i," Ошибка открытия ордера ",Strtip(tip)," <<",(GetLastError()),">>  lot=",lots,"  pr=",price," sl=",sl," tp=",tp);
      Sleep(500);
      RefreshRates();
      if (IsStopped()) return(0);
   }
   return(0);
}
//------------------------------------------------------------------
string Strtip(int tip)
{
   switch(tip) 
   { 
   case OP_BUY:
      return("BUY"); 
   case OP_SELL:
      return("SELL"); 
   case OP_BUYSTOP:
      return("BUYSTOP"); 
   case OP_SELLSTOP:
      return("SELLSTOP"); 
   case OP_BUYLIMIT:
      return("BUYLIMIT"); 
   case OP_SELLLIMIT:
      return("SELLLIMIT"); 
   }
   return("error"); 
}
//------------------------------------------------------------------
void OnDeinit(const int reason)
{
   if (!IsTesting()) 
   {
      ObjectsDeleteAll(0);
   }
}
//-------------------------------------------------------------------
void DrawLABEL(string name, int CORNER, int X, int Y, color clr, string Name)
{
   if (ObjectFind(name)==-1)
   {
      ObjectCreate(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);
}
//+------------------------------------------------------------------+
int OnInit()
{
   MINLOT = MarketInfo(Symbol(),MODE_MINLOT);
   MAXLOT = MarketInfo(Symbol(),MODE_MAXLOT);
   Comment("Start ",TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS));
   
   AC = StringConcatenate(" ", AccountCurrency());
   
   int Y=15;
   DrawLABEL("Торговля"  ,1,5,Y,Red,"Торговля ");Y += 20;
   DrawLABEL("Balance"   ,1,5,Y,clrGreen,StringConcatenate("Balance ",DoubleToStr(AccountBalance(),2),AC));Y += 15;
   DrawLABEL("Equity"    ,1,5,Y,clrGreen,StringConcatenate("Equity ",DoubleToStr(AccountEquity(),2),AC));Y += 15;
   DrawLABEL("FreeMargin",1,5,Y,clrGreen,StringConcatenate("FreeMargin ",DoubleToStr(AccountFreeMargin(),2),AC));Y += 30;

   DrawLABEL("Take"           ,1,5,Y,Lime,"Profit ");Y += 20;
   
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
color Color(bool P,color a,color b)
{
   if (P) return(a);
   else return(b);
}
//------------------------------------------------------------------
double LOT()
{
   int n=0;
   double OL=Lot;
   for (int j = OrdersHistoryTotal()-1; j >= 0; j--)
   {
      if (OrderSelect(j, SELECT_BY_POS,MODE_HISTORY))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
         {
            if (OrderProfit()<0) 
            {
               if (n==0) OL=NormalizeDouble(OrderLots()*K_Martin,DigitsLot);
               n++;
               if (n>=OrdersClose) {Comment("1");return(Lot);}
            }
            else
            {
               if (n==0) {Comment("2");return(Lot);}
               else {Comment("3");return(OL);}
            }
         }
      }
   }
   return(OL);
}
//------------------------------------------------------------------


Программные помощники MQL для работы на финансовых рынках
  • cmillion.ru
Скрипт показывает максимальную и минимальную корреляцию на выбранном отрезке истории, например за последние 10000 свечей. Таким образом можно заранее проанализировать какие пары и как коррелируют. В параметрах задаем Тф период корреляции и период анализа корреляции. Зеленым цветом выделяются пары с прямой корреляцией у которых корреляция выше...
 
законопослушный гражданин:

Hello.

testing owls. (the code is attached below).

owl uses martingale based on previous order history (if loss, then multiply the lot by the martin coefficient...).

the previous order was closed by a stop with e.g. 0.2 lot at (martin =2...) then I switch off "auto-trading" in the MT4 terminal or switch off the terminal completely and the owl stops trading.

Then when I switch on the "auto-trading" button - Then the owl switches on and opens the next lot with a volume of 0.4.

So, how to correct the code, so that when you turn off "auto-trading", turn off the terminal and then turn it on, the owl starts the next trading session with the starting lot,

specified in the settings (e.g. 0.01) rather than multiplying the last closed one in the history?

You create a global variable

datetime Start;

int OnInit()
{
   Start=TimeCurrent();
.....................
}
void OnTick()
{
   if (!IsTradeAllowed()) 
   {
      DrawLABEL("Торговля",0,0,0,Red,"Торговля запрещена");
      Start=TimeCurrent();
      return;
   } 
.....................
}

and then if there are no open/closed orders later "Start"

Lots=Lot;
 
MakarFX:

You create a global variable

and then if there are no open/closed orders later "Start".

Thank you.

I'm not good at this yet. I already have a datetime OpenTime; - should it be replaced withdatetime Start or in addition?

"If there are no open/closed orders later than "Start "Lots=Lot;" - is it not clear where to put it?

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

Thank you.

I'm not good at this yet. I already have datetime OpenTime; - should it be replaced withdatetime Start or in addition?

"and then if there are no open/closed orders later "Start "Lots=Lot; " - it's not at all clear where to refer to?

Describe in a nutshell what you want from this EA (the logic of its work),

I think you have a lot of unnecessary things in your code or I don't understand something.

 
In order to add an indicator when passing another indicator handle to it (like applied_price) this other one must have only one buffer? Or is it possible to have several buffers? If there is more than one, in this case the first one takes data only from zero buffer of the second indicator?
 

Good afternoon. Help with the EA. According to the strategy, if a stop triggered, then the EA should add (the number of points) to the next set takeaway
from the history by ID, but it does not do it for some reason.

What is wrong with the code?

if(isLimitOn && OrderSelect(OrderMagicNumber(), SELECT_BY_TICKET, MODE_HISTORY)){
            tpc += stop_loss;
            if(OrderSelect(lastMagic, SELECT_BY_TICKET)){
               if(OrderType() == OP_BUY) {
                  double tp_price = NormalizeDouble((OrderOpenPrice() + Point() * (tp + tpc)), Digits);
                  if(!OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), tp_price, OrderExpiration()))
                     Print("Ошибка модификации ордера:", GetLastError());
               }else if(OrderType() == OP_SELL){
                  double tp_price = NormalizeDouble((OrderOpenPrice() - Point() * (tp + tpc)), Digits);
                  if(!OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), tp_price, OrderExpiration()))
                     Print("Ошибка модификации ордера:", GetLastError());
               }
            }
               
            isLimitOn = false;
         }
 
SGarnov:

Good afternoon. Help with the EA. According to the strategy, if a stop triggered, then the EA should add (the number of points) to the next set takeaway
from the history by ID, but it does not do it for some reason.

What is wrong with the code?

it's not clear that it's "OrderMagicNumber()" and it's "stop_loss"
 
verified?
 
Hello, I need an advisor. Where can I get a trusted one?
Reason: