help with mql5 hedge terminal close all positions - page 2

 
hassan077 :

@Vladimir Karputov

@William Roeder

finely this code worked for me

Your code won't compile. It contains many bugs.

 

@Vladimir Karputov

deferent libraries same code and same function

now I have tow quastions please help me with 

1-how to modify the positions? 

2-where to put dynamic stoploss code?


#include <Mql5\Trade.mqh>          //open Buy position 
CTrade trade;                      //class
#include <Mql5\TradeHedge.mqh>     //hedge position close
CTradeHedge Trade;		   //class

 #include  <Trade\PositionInfo.mqh>
 #include  <Trade\Trade.mqh>
 //--- 
CPositionInfo  m_position;                   // object of CPositionInfo class 
CTrade         m_trade;                       // object of CTrade class 

thank you very much 

 
hassan077 :


It is still not clear to me: what exactly do you need? I cannot compile your code - there are a lot of compilation errors in it.

Describe in your own words: under what condition you need to close ALL positions.

 

In general, this is how I understood your question: when two iMAs intersect, we receive a signal (open a position, and close the opposite one). This is a minimal code - there is no basic protection and verification of a trade request. This is very simple code.

//+------------------------------------------------------------------+
//|                                       Simle Two iMA Crossing.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.00"
/*
   barabashkakvn Trading engine 3.138
*/
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
CAccountInfo   m_account;                    // object of CAccountInfo class
//--- input parameters
input group             "MA Fast"
input int                  Inp_MA_Fast_ma_period     = 5;           // MA Fast: averaging period
input int                  Inp_MA_Fast_ma_shift      = 0;           // MA Fast: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Fast_ma_method     = MODE_SMA;    // MA Fast: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Fast_applied_price = PRICE_CLOSE; // MA Fast: type of price
input group             "MA Slow"
input int                  Inp_MA_Slow_ma_period     = 9;           // MA Slow: averaging period
input int                  Inp_MA_Slow_ma_shift      = 0;           // MA Slow: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Slow_ma_method     = MODE_SMA;    // MA Slow: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Slow_applied_price = PRICE_CLOSE; // MA Slow: type of price
input group             "Additional features"
input bool     InpPrintLog          = false;       // Print log
input ulong    InpDeviation         = 10;          // Deviation
input ulong    InpMagic             = 931302198;   // Magic number
//---
int      handle_iMA_Fast;                       // variable for storing the handle of the iMA indicator
int      handle_iMA_Slow;                       // variable for storing the handle of the iMA indicator
bool     m_need_close_buys          = false;    // close all BUY positions
bool     m_need_close_sells         = false;    // close all SELL positions
bool     m_need_open_buy            = false;    // open BUY position
bool     m_need_open_sell           = false;    // open SELL position
datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//--- create handle of the indicator iMA
   handle_iMA_Fast=iMA(m_symbol.Name(),Period(),Inp_MA_Fast_ma_period,Inp_MA_Fast_ma_shift,
                       Inp_MA_Fast_ma_method,Inp_MA_Fast_applied_price);
//--- if the handle is not created
   if(handle_iMA_Fast==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA ('Fast') indicator for the symbol %s/%s, error code %d",
                  m_symbol.Name(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Slow=iMA(m_symbol.Name(),Period(),Inp_MA_Slow_ma_period,Inp_MA_Slow_ma_shift,
                       Inp_MA_Slow_ma_method,Inp_MA_Slow_applied_price);
//--- if the handle is not created
   if(handle_iMA_Slow==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA ('Slow') indicator for the symbol %s/%s, error code %d",
                  m_symbol.Name(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- need close BUY positions OR SELL positions
   if(m_need_close_buys || m_need_close_sells)
     {
      int count_buys    = 0;
      int count_sells   = 0;
      CalculateAllPositions(count_buys,count_sells);
      //---
      if(m_need_close_buys)
        {
         if(count_buys>0)
           {
            ClosePositions(POSITION_TYPE_BUY);
            return;
           }
         else
            m_need_close_buys=false;
        }
      //---
      if(m_need_close_sells)
        {
         if(count_sells>0)
           {
            ClosePositions(POSITION_TYPE_SELL);
            return;
           }
         else
            m_need_close_sells=false;
        }
     }
//--- open BUY position
   if(m_need_open_buy)
     {
      if(!RefreshRates())
         return;
      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)
      double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),
                               ORDER_TYPE_BUY,
                               m_symbol.LotsMin(),
                               m_symbol.Ask());
      double margin_check=m_account.MarginCheck(m_symbol.Name(),
                          ORDER_TYPE_BUY,
                          m_symbol.LotsMin(),
                          m_symbol.Ask());
      if(free_margin_check>margin_check)
        {
         if(InpPrintLog)
            Print(__FILE__," ",__FUNCTION__,", OK: ","Signal BUY");
         m_trade.Buy(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Ask());
        }
      m_need_open_buy=false;
     }
//--- open SELL position
   if(m_need_open_sell)
     {
      if(!RefreshRates())
         return;
      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)
      double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),
                               ORDER_TYPE_SELL,
                               m_symbol.LotsMin(),
                               m_symbol.Ask());
      double margin_check=m_account.MarginCheck(m_symbol.Name(),
                          ORDER_TYPE_SELL,
                          m_symbol.LotsMin(),
                          m_symbol.Ask());
      if(free_margin_check>margin_check)
        {
         if(InpPrintLog)
            Print(__FILE__," ",__FUNCTION__,", OK: ","Signal SELL");
         m_trade.Sell(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Bid());
        }
      m_need_open_sell=false;
     }
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
//---
   double fast[],slow[];
   ArraySetAsSeries(fast,true);
   ArraySetAsSeries(slow,true);
   int start_pos=0,count=6;
   if(!iGetArray(handle_iMA_Fast,0,start_pos,count,fast) || !iGetArray(handle_iMA_Slow,0,start_pos,count,slow))
     {
      m_prev_bars=0;
      return;
     }
//--- check signal close SELL and open BUY
   if(fast[1]>slow[1]&&fast[2]<slow[2])
     {
      m_need_close_sells=true;
      m_need_open_buy=true;
      return;
     }
//--- check signal close BUY and open SELL
   if(fast[1]<slow[1]&&fast[2]>slow[2])
     {
      m_need_close_buys=true;
      m_need_open_sell=true;
      return;
     }
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      if(InpPrintLog)
         Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      if(InpPrintLog)
         Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
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))
     {
      if(InpPrintLog)
         PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);
      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)
     {
      //--- if the copying fails, tell the error code
      if(InpPrintLog)
         PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",
                     __FILE__,__FUNCTION__,count,copied,GetLastError());
      //--- quit with zero result - it means that the indicator is considered as not calculated
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+
//| Calculate all positions                                          |
//+------------------------------------------------------------------+
void CalculateAllPositions(int &count_buys,int &count_sells)
  {
   count_buys  = 0;
   count_sells = 0;
   for(int i=PositionsTotal()-1; i>=0; i--)
      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()==InpMagic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
               count_buys++;
            else
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                  count_sells++;
           }
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions(const ENUM_POSITION_TYPE pos_type)
  {
   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()==InpMagic)
            if(m_position.PositionType()==pos_type)
               if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                  if(InpPrintLog)
                     Print(__FILE__," ",__FUNCTION__,", ERROR: ","CTrade.PositionClose ",m_position.Ticket());
  }
//+------------------------------------------------------------------+
 

@Vladimir Karputov

Amazing thank you very much

yes exactly the above code what I meant.

in addition if you will I want to know how to:-

1-how to modify all opened positions ? 

2-where to put dynamic stoploss code for all opened positions in above code?

  

 
hassan077 :

@Vladimir Karputov

Amazing thank you very much

yes exactly the above code what I meant.

in addition if you will I want to know how to:-

1-how to modify all opened positions ? 

2-where to put dynamic stoploss code for all opened positions in above code?

  

Example - how to set Stop Loss and Take Profit: 

Simple Advisor with Stop Loss and Take Profit

How to start with MQL5
How to start with MQL5
  • 2020.03.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 
Vladimir Karputov:

Example - how to set Stop Loss and Take Profit: 

Simple Advisor with Stop Loss and Take Profit


OMG thank you very much

there is every thing I want

thank you

Reason: