Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1319

 
SanAlex:

I am self-taught and will not be able to explain it to you - I just chose the functions that I need, I know that this goes there and that goes there.

Basically all the functions I copy from the codes of Vladimir Karputov, for which I thank him very much! - He will tell you if you have any questions.

You are self-taught, and I just started programming, and my head is full of questions.

I have the algorithm for this EA in my head and it's no problem if I have to change the indicator in the process, because there are only two tasks (direction point - up and direction point - down).

At the moment, I am proceeding from the classic that the simplest is the best. That's why I want to simplify...... to the max and at the same time get the most out of what I want to create. I propose to work together on my algorithm - I think it would be interesting for both of us.
If you are interested, please contact me in person.
 
Vladimir Karputov:

Inheritance involves creating a class.

So I'm writing -- which class should I inherit my class from to use these methods from their standard library?

 
SanAlex:

here's another option - once the take is triggered - will open again in the same direction

Exactly right, with profit !!!

At first glance - everything is correct.

And the fact that there should be no Stop Loss - all correct too.

But I do not understand what happens to the oder, which is not closed at Take Profit....... when the direction of price changes....(just closes by default, i.e. on the signal of the trend change indicator)? If so, that's not my intention.

And according to my idea - the order should remain, but here it should come into effect - a martin with its settings:

input group "======== МАРТИН ========"; 
input int      MMType        = 1;        // 1 - вкл. , 2 - выкл.
input double   Multiplikator = 1.667;    // множитель следующего лота
input double   Step          = 150.0;    // Расстояние между ордерами

I.e. set orders in the opposite direction to the trend with increasing lot and averaging take profit. In short, work like a simple Martin, for example (Adviser Autoprofit 3), which is in the open source in the web, but written in mql4.

By the way, the original variant of trend work, which you correctly wrote, has not been cancelled when working with Martin.

In short, the trend work is one task, which you have brilliantly demonstrated in part, and the second task is a martin.

It is not necessary that these two tasks are interrelated - in my opinion, they can work completely independently

 
Sprut 185:

Absolutely right, with profits !!!

At first glance - everything is correct.

And the fact that the Stop Loss - should not be there either - all correct.

But I did not understand where the oder, which did not close at Take Profit....... when the direction of price changes....(it just closes by default, i.e. on the signal of the trend change indicator)? If so, that's not my intention.

But according to my idea, the order should remain, but a martin with its settings should come into effect here:

The same is true for the other side of the trend with increasing lot size and averaging the Take Profit. In short, work like a simple Martin - for example (Autoprofit 3), which is open source on the web, but written in mql4.

One remark at once: not "order", but "position".

 
Vladimir Karputov:

One remark at once: not "order", but "position".

I apologise for the error.
I will take this into account and try to correct myself in the future.
 
Sprut 185:

all the options I could find - there don't seem to be any more

4 Sprut 185

//+------------------------------------------------------------------+
//|                                                  4 Sprut 185.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//---
#define  MACD_MAGIC 1234502
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
double            m_adjusted_point;             // point value adjusted for 3 or 5 points
CTrade            m_trade;                      // trading object
CSymbolInfo       m_symbol;                     // symbol info object
CPositionInfo     m_position;                   // trade position object
CAccountInfo      m_account;                    // account info wrapper
//---
input double InpLots          =0.1;   // Lots
input int    InpTakeProfit    =50;    // Take Profit (in pips)
input bool   InpVariant       =false; // Option
input int    InpBar           =1;     // Bar
input bool   InpClOp          =false; // Close opposite
//---
double m_macd_current;
double m_signal_current;
double m_take_profit;
int    price_uno;
int    m_handle_macd; // MACD indicator handle
int    ExtTimeOut=10; // time out in seconds between trade operations
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- initialize common information
   m_symbol.Name(Symbol());                  // symbol
   m_trade.SetExpertMagicNumber(MACD_MAGIC); // magic
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   m_adjusted_point=m_symbol.Point()*digits_adjust;
//--- set default deviation for trading in adjusted points
   m_take_profit     =InpTakeProfit*m_adjusted_point;
//--- set default deviation for trading in adjusted points
   m_trade.SetDeviationInPoints(3*digits_adjust);
//--- create StepMA_NRTR indicator
   m_handle_macd=iCustom(NULL,0,"StepMA_NRTR");
   if(m_handle_macd==INVALID_HANDLE)
     {
      printf("Error creating StepMA_NRTR indicator");
      return(false);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
   static datetime limit_time=0; // last trade processing time + timeout
//--- don't process if timeout
   if(TimeCurrent()>=limit_time)
     {
      //--- check for data
      if(Bars(Symbol(),Period())>2)
        {
         //--- change limit time by timeout in seconds if processed
         if(!InpVariant && Processing())
            limit_time=TimeCurrent()+ExtTimeOut;
         //--- change limit time by timeout in seconds if processed
         if(InpVariant && Processing_1())
            limit_time=TimeCurrent()+ExtTimeOut;
        }
     }
  }
//+------------------------------------------------------------------+
//| main function returns true if any position processed             |
//+------------------------------------------------------------------+
bool Processing(void)
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
   double m_buff_MACD_main[],m_buff_MACD_signal[];
   ArraySetAsSeries(m_buff_MACD_main,true);
   ArraySetAsSeries(m_buff_MACD_signal,true);
   int start_pos=InpBar,count=3;
   if(!iGetArray(m_handle_macd,0,start_pos,count,m_buff_MACD_main)||
      !iGetArray(m_handle_macd,1,start_pos,count,m_buff_MACD_signal))
     {
      return(false);
     }
//---
   m_macd_current   =m_buff_MACD_main[0];
   m_signal_current =m_buff_MACD_signal[0];
//---
   if(m_position.Select(Symbol()))
     {
      //--- try to close or modify long position
      if(LongClosed())
         return(true);
      //--- try to close or modify short position
      if(ShortClosed())
         return(true);
     }
   else
     {
      //--- check for long position (BUY) possibility
      if(LongOpened())
         return(true);
      //--- check for short position (SELL) possibility
      if(ShortOpened())
         return(true);
     }
//--- exit without position processing
   return(false);
  }
//+------------------------------------------------------------------+
//| main function returns true if any position processed             |
//+------------------------------------------------------------------+
bool Processing_1(void)
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
   double m_buff_MACD_main[],m_buff_MACD_signal[];
   bool StNRUp,StNRDn;
   ArraySetAsSeries(m_buff_MACD_main,true);
   ArraySetAsSeries(m_buff_MACD_signal,true);
   int start_pos=InpBar,count=3;
   if(!iGetArray(m_handle_macd,0,start_pos,count,m_buff_MACD_main)||
      !iGetArray(m_handle_macd,1,start_pos,count,m_buff_MACD_signal))
     {
      return(false);
     }
//---
   m_macd_current   =m_buff_MACD_main[0];
   m_signal_current =m_buff_MACD_signal[0];
//---
   StNRUp=m_buff_MACD_main[0]<m_buff_MACD_signal[0];
   StNRDn=m_buff_MACD_main[0]>m_buff_MACD_signal[0];
//--- BUY Signal
   if(StNRUp)
     {
      if(InpClOp)
         if(ShortClosed())
            Sleep(1000);
      if(price_uno<0)
         LongOpened();
      price_uno=+1;
      return(true);
     }
//--- SELL Signal
   if(StNRDn)
     {
      if(InpClOp)
         if(LongClosed())
            Sleep(1000);
      if(price_uno>0)
         ShortOpened();
      price_uno=-1;
      return(true);
     }
//--- exit without position processing
   return(false);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool LongClosed(void)
  {
   bool res=false;
//--- should it be closed?
   if(m_macd_current>m_signal_current)
     {
      //--- close position
      if(InpClOp)
         ClosePositions(POSITION_TYPE_BUY);
      //--- processed and cannot be modified
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for short position closing                                 |
//+------------------------------------------------------------------+
bool ShortClosed(void)
  {
   bool res=false;
//--- should it be closed?
   if(m_macd_current<m_signal_current)
     {
      //--- close position
      if(InpClOp)
         ClosePositions(POSITION_TYPE_SELL);
      //--- processed and cannot be modified
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for long position opening                                  |
//+------------------------------------------------------------------+
bool LongOpened(void)
  {
   bool res=false;
//--- check for long position (BUY) possibility
   if(m_macd_current<m_signal_current)
     {
      double price=m_symbol.Ask();
      double tp   =m_symbol.Bid()+m_take_profit;
      //--- check for free money
      if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_BUY,InpLots,price)<0.0)
         printf("We have no money. Free Margin = %f",m_account.FreeMargin());
      else
        {
         //--- open position
         if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,InpLots,price,0.0,tp))
            printf("Position by %s to be opened",Symbol());
         else
           {
            printf("Error opening BUY position by %s : '%s'",Symbol(),m_trade.ResultComment());
            printf("Open parameters : price=%f,TP=%f",price,tp);
           }
         PlaySound("ok.wav");
        }
      //--- in any case we must exit from expert
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for short position opening                                 |
//+------------------------------------------------------------------+
bool ShortOpened(void)
  {
   bool res=false;
//--- check for short position (SELL) possibility
   if(m_macd_current>m_signal_current)
     {
      double price=m_symbol.Bid();
      double tp   =m_symbol.Ask()-m_take_profit;
      //--- check for free money
      if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_SELL,InpLots,price)<0.0)
         printf("We have no money. Free Margin = %f",m_account.FreeMargin());
      else
        {
         //--- open position
         if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,InpLots,price,0.0,tp))
            printf("Position by %s to be opened",Symbol());
         else
           {
            printf("Error opening SELL position by %s : '%s'",Symbol(),m_trade.ResultComment());
            printf("Open parameters : price=%f,TP=%f",price,tp);
           }
         PlaySound("ok.wav");
        }
      //--- in any case we must exit from expert
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
void FreezeStopsLevels(double &freeze,double &stops)
  {
//--- check Freeze and Stops levels
   double coeff=(double)1;
   if(!RefreshRates() || !m_symbol.Refresh())
      return;
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();
   if(freeze_level==0.0)
      if(1>0)
         freeze_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();
   if(stop_level==0.0)
      if(1>0)
         stop_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//---
   freeze=freeze_level;
   stops=stop_level;
//---
   return;
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions(const ENUM_POSITION_TYPE pos_type)
  {
   double freeze=0.0,stops=0.0;
   FreezeStopsLevels(freeze,stops);
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==MACD_MAGIC)
            if(m_position.PositionType()==pos_type)
              {
               if(m_position.PositionType()==POSITION_TYPE_BUY)
                 {
                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=freeze) || m_position.TakeProfit()==0.0);
                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=freeze) || m_position.StopLoss()==0.0);
                  if(take_profit_level && stop_loss_level)
                     if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
                 }
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                 {
                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=freeze) || m_position.TakeProfit()==0.0);
                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=freeze) || m_position.StopLoss()==0.0);
                  if(take_profit_level && stop_loss_level)
                     if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
                 }
               PlaySound("ok.wav");
              }
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+
 
SanAlex:

all the options I could find - there don't seem to be any more


What if you try to use 2 independent blocks in your Expert Advisor. Then one will work on its own, as you have already working on the - trend (using an indicator)..........
And the second by the signal set by the first block - by position - not by trend........


I have already written above:

These two tasks don't have to be interrelated - in my opinion, they can work completely independently.

Such an algorithm that I propose (in my opinion) has not yet been used by programmers. In any case, I have not found such a solution - on the Internet.

 
Sprut 185 This algorithm I propose - (in my opinion) has not yet been used by programmers. In any case, I have not found such a solution on the Internet.

this is probably not possible to implement

it does not give - on the symbol, there must be one position (if it is closed on a profit and reopened a position) (and when the opposite signal is applied - it cannot open in the other direction

   if(m_position.Select(Symbol()))

if just from a signal (from a point) there is no problem . (and this should not be present in the code (line above)))

 
SanAlex:

this is probably not possible to implement

it does not give - on the symbol, there must be one position (if it is closed on a profit and reopened a position) (and when the opposite signal is applied - it cannot open in the other direction

if just from a signal (from a point) there is no problem . (and then, it should not be present in the code (line above)))

I see - that's probably why I haven't found such a solution on the Internet. But in my opinion, there must be a solution to this problem.
Thanks - I will look for a solution to this problem.....
Then let's pause for now.
 

After upgrading to version 2981, an error started appearing in the line

MqlTradeRequest request = {0}
cannot convert 0 to enum 'ENUM_TRADE_REQUEST_ACTIONS'   OrderaiPosicii.mqh      11      34
Please advise how to replace this line.