Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1324

 
Alexey Viktorov:

Yesterday I downloaded this miracle to watch... Suddenly I had no internet. After a thunderstorm I had technical works for the rest of the day. So I decided to rewrite it in MQL5 out of idleness and published it here.

So every cloud has a silver lining.........

I have added an indicator to your Expert Advisor - I think you won't mind! I think it worked out as Sprut wanted 185

(in yellow I added it to my existing Expert Advisor here)

//+------------------------------------------------------------------+
//|                                                 2 DVA_Martin.mq5 |
//|                                          © 2021, Alexey Viktorov |
//|                     https://www.mql5.com/ru/users/alexeyvik/news |
//+------------------------------------------------------------------+
#property copyright "© 2021, Alexey Viktorov"
#property link      "https://www.mql5.com/ru/users/alexeyvik/news"
#property version   "2.00"
//---
#include <Trade\Trade.mqh>
CTrade trade;
//---
input int     TakeProfit1         = 300;  // профит первой позиции
input int     TakeProfit2         = 250;  // профит второй позиции
input int     TakeProfit3         = 200;  // профит третьей позиции
input int     TakeProfit4         = 100;  // профит четвертой и следующих позиций
input int     Step                = 200;  // шаг первой позиции
input int     Delta               = 100;  // добавка к шагу
// со второй позиции увеличивает расстояние последующих позиций на величину "дельта" от предыдущего
input double  Lot                 = 0.03; // первый лот открытия
input double  MaximalLot          = 0.5;  // максимальный лот, который мы разрешаем
input int     MaxTrades           = 9;    // максимальное количество позиций одного направления
input double  MultiplicatorLot    = 1.6;  // умножаем последующие позиции
input int     Magic               = 123;  // идентификатор советника
//--- Пременные для хранения собранной информации
double MaxLot  = 0;
double LotBuy  = 0;
double LotSell = 0;
//---
int m_bar_current=0;
int StepMA_NRTR_Handle;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   trade.SetExpertMagicNumber(Magic);
   MaxLot = contractSize(MaximalLot);
//--- create StepMA_NRTR indicator
   StepMA_NRTR_Handle=iCustom(NULL,0,"StepMA_NRTR");
   if(StepMA_NRTR_Handle==INVALID_HANDLE)
     {
      printf("Error creating StepMA_NRTR indicator");
      return(false);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double StepMA_NRTR[],StepMA_NRTRS[];
   ArraySetAsSeries(StepMA_NRTR,true);
   ArraySetAsSeries(StepMA_NRTRS,true);
   int start_pos=1,count=3;
   if(!iGetArray(StepMA_NRTR_Handle,0,start_pos,count,StepMA_NRTR)||
      !iGetArray(StepMA_NRTR_Handle,1,start_pos,count,StepMA_NRTRS))
     {
      return;
     }
//---
   int posTotal = PositionsTotal();
   double BuyMinPrice = DBL_MAX, //  Минимальная цена Buy позиции
          SelMaxPrice = DBL_MIN, //  Максимальная цена Sell позиции
          BuyMinLot = 0,         //  Лот самой нижней Buy позиции
          SelMaxLot = 0,         //  Лое самой верхней Sell позиции
          posPrice = 0.0,
          posLot = 0.0,
          BuyAwerage = 0,
          SelAwerage = 0,
          BuyPrice = 0,
          SelPrice = 0,
          BuyLot = 0,
          SelLot = 0;
   MqlTick tick;
   if(!SymbolInfoTick(_Symbol, tick))
      return;
   int b = 0,
       s = 0;
   for(int i = 0; i < posTotal; i++)
     {
      ulong posTicket = PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic)
        {
         posPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         posLot = PositionGetDouble(POSITION_VOLUME);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            b++; // Считаем открытые позиции на покупку
            if(posPrice < BuyMinPrice)
              {
               BuyMinPrice = posPrice;
               BuyMinLot = posLot;
               BuyPrice += posPrice*posLot;  // добавить к переменной BuyPrice Цена оредра 1 * лот ордера 1
               BuyLot += posLot;             // суммируем лоты
              }
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
           {
            s++; // Считаем открытые позиции на продажу
            if(posPrice > SelMaxPrice)
              {
               SelMaxPrice = posPrice;
               SelMaxLot = posLot;
               SelPrice += posPrice*posLot;  // добавить к переменной BuyPrice Цена оредра 1 * лот ордера 1
               SelLot += posLot;             // суммируем лоты
              }
           }
        }
     }
   LotBuy = b == 0 ? contractSize(Lot) : fmin(MaxLot, contractSize(BuyMinLot*MultiplicatorLot));
   LotSell = s == 0 ? contractSize(Lot) : fmin(MaxLot, contractSize(SelMaxLot*MultiplicatorLot));
//---
//--- BUY Signal
   if(StepMA_NRTR[m_bar_current]<StepMA_NRTRS[m_bar_current])
     {
      if(b == 0 || (b < MaxTrades && BuyMinPrice-tick.ask >= (Step+Delta*b)*_Point))
         openPos(ORDER_TYPE_BUY, LotBuy, tick.ask);
     }
//--- SELL Signal
   if(StepMA_NRTR[m_bar_current]>StepMA_NRTRS[m_bar_current])
     {
      if(s == 0 || (s < MaxTrades && tick.bid-SelMaxPrice >= (Step+Delta*s)*_Point))
         openPos(ORDER_TYPE_SELL, LotSell, tick.bid);
     }
//--- посчитаем математические формулы средних цен
   switch(b)
     {
      case 0 :
         return;
      case 1 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit1*_Point;
         break;
      case 2 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit1*_Point;
         break;
      case 3 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit3*_Point;
         break;
      default:
         BuyAwerage = BuyPrice/BuyLot+TakeProfit4*_Point;
         break;
     }
   switch(s)
     {
      case 0 :
         return;
      case 1 :
         SelAwerage = SelPrice/SelLot-TakeProfit1*_Point;
         break;
      case 2 :
         SelAwerage = SelPrice/SelLot-TakeProfit2*_Point;
         break;
      case 3 :
         SelAwerage = SelPrice/SelLot-TakeProfit3*_Point;
         break;
      default:
         SelAwerage = SelPrice/SelLot-TakeProfit4*_Point;
         break;
     }
   normalizePrice(BuyAwerage); // Произведем расчет цены TP Buy
   normalizePrice(SelAwerage); // Произведем расчет цены TP Sell
//---
   for(int i = 0; i < posTotal; i++)
     {
      ulong posTicket = PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic)
        {
         double posTP = PositionGetDouble(POSITION_TP);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            if(fabs(posTP-BuyAwerage) > _Point && tick.ask < BuyAwerage) // Если тейк не равен требуемой цене
               if(!trade.PositionModify(posTicket, 0.0, BuyAwerage))
                  Print("Ошибка ", __LINE__);
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
           {
            if(fabs(posTP-SelAwerage) > _Point && tick.bid > SelAwerage) // Если тейк не равен требуемой цене
               if(!trade.PositionModify(posTicket, 0.0, SelAwerage))
                  Print("Ошибка ", __LINE__);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void openPos(ENUM_ORDER_TYPE type, double lot, double price)
  {
   trade.CheckVolume(_Symbol, lot, price, type);
   if(trade.CheckResultMarginFree() <= 0.0)
     {
      Print("Not enough money for ", EnumToString(type), " ", lot, " ", _Symbol, " Error code=", trade.CheckResultRetcode());
      return;
     }
   if(!trade.PositionOpen(_Symbol, type, LotBuy, price, 0.0, 0.0))
      Print(trade.ResultRetcode());
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double contractSize(double volume, string symbol = NULL)
  {
   symbol = symbol == NULL ? _Symbol : symbol;
   double v = volume;
   double volumeStep = SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
   v = round(volume/volumeStep)*volumeStep;
   double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
   return((v < minLot ? minLot : v));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double normalizePrice(double &price, string symbol = NULL)
  {
   symbol = symbol == NULL ? _Symbol : symbol;
   double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
   price = round(price/tickSize)*tickSize;
   return(tickSize);
  }
//+------------------------------------------------------------------+
//| Filling the indicator buffers from the indicator                 |
//+------------------------------------------------------------------+
bool iGetArray(const int handle,const int buffer,const int start_pos,
               const int count,double &arr_buffer[])
  {
   bool result=true;
   if(!ArrayIsDynamic(arr_buffer))
     {
      return(false);
     }
   ArrayFree(arr_buffer);
//--- reset error code
   ResetLastError();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);
   if(copied!=count)
     {
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+

Советники: DVA_Martin
Советники: DVA_Martin
  • 2021.06.30
  • www.mql5.com
Статьи и техническая библиотека по автоматическому трейдингу: Советники: DVA_Martin
 
SanAlex:

I have added an Indicator to your Expert Advisor - I think you won't mind!? I think it turned out as Sprut wanted 185

(in yellow I added it to my existing Expert Advisor here.)

And why the indicator values from three bars? And why flip the array to time series?

In general, it seems to me that it's not the right one... No martin will work.

 
Alexey Viktorov:

Why do you need the indicator values from three bars? And why flip the array to time series?

In general, it seems to me that this is not the case... No martin will work.

The indicator here is just a direction filter - and your Expert Advisor does the whole task

\\\\\\\\\\\\\

The indicator itself does not open positions.

 
SanAlex:

The indicator here is simply a directional filter - and your expert does the whole task

The written code should do the task. But you have set such a condition that the martin will never turn on. I think so, but I have no desire or time to check it.

 
Alexey Viktorov:

The task must be done by the code you have written. But you have made it a condition that the martin will never turn on. I think so, but I have no desire or time to check it.

Here I am checking its work - everything works as intended.

2 DVA_Martin

 
Alexey Viktorov:

Should Martin only be activated when the indicator signal is opposite or regardless?

Example: A Buy position was opened according to the indicator. The price has fallen by the set distance and the indicator is already showing Sell. Should the Buy position be opened?

As promised - I photoshopped something.

1

If it is not clear, I will be able to explain the meaning of my idea only if I talk to you in person

 
SanAlex:

I did something wrong here - I don't know what went from 100,000 roubles to two million.

changed the Indicator and 5min Euro\bucks in 15 days to a million.

LeMan_BrainTrend1Sig 2

LeMan_BrainTrend1Sig

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

added to the Expert Advisor - to close the profit (from all pairs) and remove the Expert Advisor

input group  "---- : Parameters:  ----"
input int    TargetProfit     = 1000000; // : Balance + Profit(add to balance)
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
//---
   if(AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)
     {
      AllClose();
      ExpertRemove();
     }
//---

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

i need these 2 indicators ( indicator names should not change)

 
SanAlex:

swapped the Indicator and 5min euro\bucks in 15 days to a million.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

added in Expert Advisor - to close profit by total profit (from all pairs) and delete Expert Advisor

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

I need these 2 indicators to be present (i.e. the indicator names would not change)

Not enough stoploss in the setup

 

There are ways to split a string into strings using a method like \n".

Are there any ways of splitting a string variable into a single string?

That is, to write all texts, values, parameters, etc., that are available in this string variable into one string.

The problem occurred when writing to csv (string variable values are written to a bunch of strings).

 
Vitaly Muzichenko:

Not enough stoploss in the setup

with Stop Loss is no longer the same profit

Stop Loss

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

I think the Expert Advisor needs to be restarted more often - for example, I took the total profit (from all pairs) for the week and deleted the Expert Advisor from all pairs.

and restart the EA until a new total profit from all pairs.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

another idea concerning the stop - stop not to close the position but to open an opposite position with a lot of opposite (losing) open positions

here is an account of open positions in lots

   int total=PositionsTotal();
   for(int i=total-1; i>=0; i--) // returns the number of open positions
     {
      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol позиции
      if(position_GetSymbol==m_symbol.Name())
        {
         if(m_position.PositionType()==POSITION_TYPE_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);
            PROFIT_BUY_Lot=PROFIT_BUY_Lot+PositionGetDouble(POSITION_VOLUME);
           }
         else
           {
            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);
            PROFIT_SELL_Lot=PROFIT_SELL_Lot+PositionGetDouble(POSITION_VOLUME);
           }
           {
            PROFIT_CLOSE=AccountInfoDouble(ACCOUNT_PROFIT);
           }
        }
     }
//---

Stop Loss 777

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

The reason is that the stop does not close the position and the opposite lot should help in manual trading.