Creating a robot - page 8

 

THANK YOU ALL VERY MUCH!!!

The program code that creates the ZigZagColor indicator on the current chart and removes it after closing the EA looks like this

in block of EA initialization

//--- create handle of the indicator iCustom
   handle_iCustom=iCustom(m_symbol.Name(),Period(),"Examples\\ZigzagColor",
                          Inp_ZZ_Depth,
                          Inp_ZZ_Deviation,
                          Inp_ZZ_Backstep);
   ChartIndicatorAdd(ChartID(),0,handle_iCustom);

in block of deinitialization of Expert Advisor

(WARNING for those, who will use this code! This version of the code is an intermediate and is only applicable to the indicator settings Inp_ZZ_Depth = 80; Inp_ZZ_Deviation = 20; Inp_ZZ_Backstep = 0; at other settings, the indicator will not be removed! In order to delete the indicator at other settings in the deinitialization block, you need to specify them instead of 80,20,0).

//---
  ChartIndicatorDelete(0,0,"ZigZag(80,20,0)");

Now I have to understand how to make it delete the indicator after changing its settings. I have tried the following variant:

//---
  ChartIndicatorDelete(0,0,"ZigZag("+Inp_ZZ_Depth+","+Inp_ZZ_Deviation+","+Inp_ZZ_Backstep+")");

It clears the indicator for all settings, but when compiling the EA the editor generates 3 warnings about implicit conversion from number to string:

implicit conversion from 'number' to 'string'   ZigZag_Fibonacci_(M1).mq5       230     38

I suspect it's all about these values: "+Inp_ZZ_Depth+", "+Inp_ZZ_Deviation+","+Inp_ZZ_Backstep+". Well, I have to study the MQL5 programming language further.

Thank you once again for your kind help!

Sincerely, Vladimir.

 
MrBrooklin:

THANK YOU ALL VERY MUCH!!!

The final code that creates the ZigZagColor indicator on the current chart and removes it after the EA is closed looks like this

in block of EA initialization

in block of deinitialization of EA

(WARNING for those, who will use this code! This version of the code is an intermediate and is only applicable to the indicator settings Inp_ZZ_Depth = 80; Inp_ZZ_Deviation = 20; Inp_ZZ_Backstep = 0; at other settings, the indicator will not be removed! To make the indicator delete at other settings in the deinitialization block, specify them instead of 80,20,0).

Now I want to understand how to make it delete the indicator after changing its settings. I have tried the following variant:

It clears the indicator for all settings, but when compiling the EA the editor generates 3 warnings about implicit conversion from number to string:

I suspect it's all about these values: "+Inp_ZZ_Depth+", "+Inp_ZZ_Deviation+","+Inp_ZZ_Backstep+". Well, I have to study the MQL5 programming language further.

Thank you once again for your kind help!

Sincerely, Vladimir.

 ChartIndicatorDelete(0,0,"ZigZag("+(string)Inp_ZZ_Depth+","+(string)Inp_ZZ_Deviation+","+(string)Inp_ZZ_Backstep+")");

The warning on an implicit type conversion. For a strict implementation, the implicit conversion gives a warning.

You should explicitly type. And in MT5 it is always strict execution. In MT4 you can select and not specify in properties #property strict

 
SanAlex:

I am self-taught myself - and I copy from the available codes myself, - The problem is that I don't know how to explain how to sculpt!? - something inside tells me how to sculpt.

----------------------------------

I know what I've moulded, missing there, also a Trawl for the line.

I've added the trawl.

input string   t0="---- Trailing Line:      -----";              //
input ushort   InpObjTrailingStop           = 0;                 // Obj: Trailing Stop (distance from price to object, in pips)
input ushort   InpObjTrailingStep           = 0;                 // Obj: Trailing Step, in pips (1.00045-1.00055=1 pips)
input string   t1="---- Line Name           -----";              //
input string   InpObjUpName                 = "Имя Линии Up";    // Obj: Up (Trailing Horizontal Line) or Trend Line)
input ENUM_TRADE_COMMAND InpTradeCommand    = UpName_s;          // Obj:  command: UP
input string   InpObjDownName               = "Имя Линии Down";  // Obj: Down (Trailing Horizontal Line) or Trend Line)
input ENUM_TRADE_COMMAND InTradeCommand     = DownName_b;        // Obj:  command: DOWN
input ushort   InpObjStep                   = 15;                // Obj: Step (distance from price to object, in pips)
Files:
0006.mq5  109 kb
 
Valeriy Yastremskiy:

Warning on non-explicit type conversion. for straight (strict) execution a non-explicit conversion gives a warning.

You should explicitly cast the types. And in MT5 it is always strict execution. In MT4 you can select and not specify in the properties #property strict

You're right, Valery! As it stands, everything works as it should. The final version in the block of EA initialization:

//--- create handle of the indicator iCustom
   handle_iCustom=iCustom(m_symbol.Name(),Period(),"Examples\\ZigzagColor",
                          Inp_ZZ_Depth,
                          Inp_ZZ_Deviation,
                          Inp_ZZ_Backstep);
   ChartIndicatorAdd(ChartID(),0,handle_iCustom);

in the EA deinitialization block:

ChartIndicatorDelete(0,0,"ZigZag("+(string)Inp_ZZ_Depth+","+(string)Inp_ZZ_Deviation+","+(string)Inp_ZZ_Backstep+")");

Thanks for the tip!

Regards, Vladimir.

 
Роман Жилин:

Oooh, thank you very much, with so much information you can get so much done...

I'm just about to leave on a business trip, so I'm thinking of going deeper into the materials I've been given, but the coding... I could do it on a sheet of paper too, it would be a good training tool...


Regards, Roman

Good day everyone!

While Roman is away on a business trip and is not participating in this topic, I will continue to ask questions about the MQL5 programming language instead. I found the Maximum Percentage of Equity Risk library in CodeBase at https://www.mql5.com/ru/code/2142. I decided to try to implement opening of Buy and Sell positions in a simple Expert Advisor, but not with a fixed lot, but with the maximum percentage of equity risk.

Here is the source code (I removed all unnecessary things to focus on the main task):

//+------------------------------------------------------------------+
//|                                                  11111111111.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

input int      TakeProfit=300; //Тейк-профит
input int      StopLoss=250;  //Стоп-лосс
input double   lot=0.1;        //Лот

double Ask;
double Bid;
//+------------------------------------------------------------------+
//| Функция открытия длинной (Long) позиции.                         |
//+------------------------------------------------------------------+
int OpenLong(double volume=0.1,
             int slippage=10,
             string comment="Long",
             int magic=0)
  {
   MqlTradeRequest my_trade;
   MqlTradeResult my_trade_result;
   ZeroMemory(my_trade);
   my_trade.action=TRADE_ACTION_DEAL;
   my_trade.symbol=Symbol();
   my_trade.volume=NormalizeDouble(volume,1);
   my_trade.price=NormalizeDouble(Ask,_Digits);
   my_trade.sl=NormalizeDouble(Ask-StopLoss*_Point,_Digits);
   my_trade.tp=NormalizeDouble(Ask+TakeProfit*_Point,_Digits);
   my_trade.deviation=slippage;
   my_trade.type=ORDER_TYPE_BUY;
   my_trade.type_filling=ORDER_FILLING_FOK;
   my_trade.comment=comment;
   my_trade.magic=magic;
   ResetLastError();

   if(OrderSend(my_trade,my_trade_result))
     {
      Print("Код результата операции - ",my_trade_result.retcode);
     }
   else
     {
      Print("Код результата операции - ",my_trade_result.retcode);
      Print("Ошибка открытия ордера = ",GetLastError());
     }
   return(0);
  }
//+------------------------------------------------------------------+
//| функция открытия короткой (Short) позиции.                       |
//| Аналогична функции открытия длинной позиции.                     |
//+------------------------------------------------------------------+
.
.
.
.
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){}
//+------------------------------------------------------------------+
//| Expert OnTick function                                           |
//+------------------------------------------------------------------+
void OnTick()
  {
.   double Open[];
.
.
         if(Open[1]>(Open[2]))
           {
            OpenShort(lot,10,"Short",1234);
            return;
           }
         if((Open[1]<Open[2])
           {
            OpenLong(lot,10,"Long",1234);
            cantrade=false;
            return;
           }
        }
     }
   return;
  }
//+------------------------------------------------------------------+

I inserted the code from the specified library into it. I obtained the following code:

//+------------------------------------------------------------------+
//|                                                  11111111111.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade\SymbolInfo.mqh> // добавлено из библиотеки

input int      TakeProfit=300; //Тейк-профит
input int      StopLoss=250;  //Стоп-лосс
input double   lot=0.1;        //Лот
input double   MaximumPercentageRisk=25; //Риск - добавлено из библиотеки

bool UseMaximumPercentageRisk=true; // добавлено из библиотеки
double Ask;
double Bid;
//--- этот блок добавлен из библиотеки
//+------------------------------------------------------------------+
//|  GetLotSize RPTrade                                              |
//+------------------------------------------------------------------+
double GetLotSize(double lotsize)
  {
//--- Gets pair specs  
   CSymbolInfo symInfo;
   int  digits_bn=symInfo.Digits();
   double  points_bn=symInfo.Point();
   string symbol_bn=_Symbol;
//--- adjust lot 
   int tmpdecimal=1;
   double old_lot=lotsize;
//---
   if((NormalizeDouble(AccountInfoDouble(ACCOUNT_FREEMARGIN)*(MaximumPercentageRisk/100)/1000.0,tmpdecimal)<lotsize) 
   && UseMaximumPercentageRisk) //лот подходит под риск ?
     {
      lotsize=NormalizeDouble(AccountInfoDouble(ACCOUNT_FREEMARGIN)
      *(MaximumPercentageRisk/100)/1000.0,tmpdecimal);  //расчет нового размера лота 

      if(lotsize<SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_MIN)) //размер лота подходит под минимльный размер лота брокера ?
        {
         lotsize=SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_MIN); //Нет! Настройка размера лота под минимальный размер лота брокера
         Print(_Symbol," Lot adjusted from ",old_lot," для уменьшения размера разрешенного сервером ",lotsize);
        }
      else
        {
         Print(_Symbol," Lot adjusted from ",old_lot,
         " to ",lotsize," для соответствия условию максимального риска. В каждой сделке рисковать можно только ",
         MaximumPercentageRisk,"% от свободной маржи.");   //Да! 
         if(MathAbs(lotsize/SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP)
         -MathRound(lotsize/SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP)))>1.0 E-10) //Размер лота подходит под разрешенный шаг брокера ?
           {
            lotsize=SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP)
            *NormalizeDouble(lotsize/SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP),0);   //НЕТ! Перерасчет размера лота.    
            Print("M-",_Symbol," Warning: Your calculated percentage at risk lot size of was not a multiple of minimal step",
            SymbolInfoDouble(symbol_bn,SYMBOL_VOLUME_STEP),". Размер лота изменился до",lotsize);
           }
        }
     }
   return(lotsize);
 }

//+------------------------------------------------------------------+
//| Функция открытия длинной (Long) позиции.                         |
//+------------------------------------------------------------------+
int OpenLong(double volume=0.1,
             int slippage=10,
             string comment="Long",
             int magic=0)
  {
   MqlTradeRequest my_trade;
   MqlTradeResult my_trade_result;
   ZeroMemory(my_trade);
   my_trade.action=TRADE_ACTION_DEAL;
   my_trade.symbol=Symbol();
   my_trade.volume=NormalizeDouble(volume,1);
   my_trade.price=NormalizeDouble(Ask,_Digits);
   my_trade.sl=NormalizeDouble(Ask-StopLoss*_Point,_Digits);
   my_trade.tp=NormalizeDouble(Ask+TakeProfit*_Point,_Digits);
   my_trade.deviation=slippage;
   my_trade.type=ORDER_TYPE_BUY;
   my_trade.type_filling=ORDER_FILLING_FOK;
   my_trade.comment=comment;
   my_trade.magic=magic;
   ResetLastError();

   if(OrderSend(my_trade,my_trade_result))
     {
      Print("Код результата операции - ",my_trade_result.retcode);
     }
   else
     {
      Print("Код результата операции - ",my_trade_result.retcode);
      Print("Ошибка открытия ордера = ",GetLastError());
     }
   return(0);
  }
//+------------------------------------------------------------------+
//| функция открытия короткой (Short) позиции.                       |
//| Аналогична функции открытия длинной позиции.                     |
//+------------------------------------------------------------------+
.
.
.
.
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){}
//+------------------------------------------------------------------+
//| Expert OnTick function                                           |
//+------------------------------------------------------------------+
void OnTick()
  {
.   double Open[];
.
.
         if(Open[1]>(Open[2]))
           {
            OpenShort(lot,10,"Short",1234);
            return;
           }
         if((Open[1]<Open[2])
           {
            OpenLong(lot,10,"Long",1234);
            cantrade=false;
            return;
           }
        }
     }
   return;
  }
//+------------------------------------------------------------------+

But the Expert Advisor continues working by a fixed lot, i.e. the risk is not considered. Please advise what to do to make the risk percentage of the capital gain.

Regards, Vladimir.

Maximum Percentage of Equity Risk
Maximum Percentage of Equity Risk
  • www.mql5.com
Change Chart and Timeframe Модифицированные скрипты для быстрого изменения графиков и таймфреймов на всех графиках при помощи горячих клавиш. Apply Template Простой скрипт для применения шаблона и/или таймфрейма ко всем открытым графикам. Long position Простой скрипт...
 
Gentlemen, there is only one page of discussion in the whole thread, the rest is code. Isn't it enough to just insert the codes?
 
MrBrooklin:

Good day to you all!

While Roman is away on a business trip and is not actively participating in this thread, I will continue to ask questions about the MQL5 programming language instead. I found the Maximum Percentage of Equity Risk library in CodeBase at https://www.mql5.com/ru/code/2142. I decided to try to implement opening of Buy and Sell positions in a simple Expert Advisor, but not with a fixed lot, but with the maximum percentage of equity risk.

Here is the source code (I removed all unnecessary things to focus on the main task):

I inserted the code from the specified library into it. I obtained the following code:

But the Expert Advisor continues working by a fixed lot, i.e. the risk is not considered. Please advise what to do to make the risk percentage of the capital gain.

My respect Vladimir.

The way you've written it, that's how it works. You need a line, if Lot==0, then count the risky lot and assign the calculation value to the Lot variable at the end.

In Quaternary this way, through additional variable Lts

bool CheckMoneyForTrade()
 {
 RefreshRates();                              // Обновление данных
   Min_Lot=MarketInfo(Symb,MODE_MINLOT);        // Миним. колич. лотов 
   Free   =AccountFreeMargin();                 // Свободн средства
   One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED);// Стоимость 1 лота
   Step   =MarketInfo(Symb,MODE_LOTSTEP);       // Шаг изменен размера
 
   if (Lots > 0)                                // Если заданы лоты,то 
      Lts =Lots;                                // с ними и работаем 
   else                                         // % свободных средств
      Lts=MathFloor(Free*Prots/One_Lot/Step)*Step;// Для открытия
 
   if(Lts < Min_Lot) Lts=Min_Lot;               // Не меньше минимальн
   if (Lts*One_Lot > Free)                      // Лот дороже свободн.
     {
      Alert(" Not enough money for ", Lts," lots");
     Work=false;
      return(false) ;                                   // Выход из функции()
     }
     return(true);
     }
 
VVT:
Gentlemen, the whole topic is one page of discussion, the rest is code. Isn't it enough to just insert the codes?

How do you help then?

 
SanAlex:

How do you help then?

Only put in what is asked for

 
Valeriy Yastremskiy:

This is how it is written and how it works. We need a line if Lot==0 then we count the risky lot and at the end we assign the value of calculation to the Lot variable.

In Quaternary it is like this, through additional variable Lts

Thanks, Valery, I will try it in the evening!

Sincerely, Vladimir.

Reason: