help with mql5 hedge terminal close all positions

 

I am trying to code a hedge terminal EA

please help me with mql5 hedge terminal close all positions

my simple code not closing any Buy position

and please help me with

1-what is the code sequence to count positions, get tikets, select tickets, put tickets to an Array, get tickets from array, select tickets of the array and modify the position. 

2-where to put dynamic stoploss code

#include <Mql5Book\Trade.mqh>
CTrade trade;
#include <Mql5Book\TradeHedge.mqh>
CTradeHedge Trade;
ulong posTicket;
// Global variables
//bool glBuyPlaced, glSellPlaced;
void OnTick()
  {
   static datetime timestamp;
   datetime time = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(timestamp != time)
     {
      timestamp = time;
      static int handleSlowMa = iMA(_Symbol, PERIOD_CURRENT, 9, 0, MODE_EMA, PRICE_CLOSE);
      double slowMaArray[];
      CopyBuffer(handleSlowMa, 0, 1, 2, slowMaArray);
      ArraySetAsSeries(slowMaArray, true);
      static int handleFastMa = iMA(_Symbol, PERIOD_CURRENT, 5, 0, MODE_EMA, PRICE_CLOSE);
      double fastMaArray[];
      CopyBuffer(handleFastMa, 0, 1, 2, fastMaArray);
      ArraySetAsSeries(fastMaArray, true);
      ulong buyTicket = 0, sellTicket = 0;
      int buyTicketCount = 0;
      int sellTicketCount = 0;
      ulong buyTickets[];
      ulong sellTickets[];
      for(int i = 0; i < PositionsTotal(); i++)
        {
         ulong ticket = PositionGetTicket(i);
         PositionSelectByTicket(ticket);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            buyTicketCount++;
            ArrayResize(buyTickets, buyTicketCount);
            buyTickets[ArraySize(buyTickets) - 1] = ticket;
            //buyTicket = ticket;
           }
         //else
         //   if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
         //     {
         //      sellTicket = ticket;
         //     }
        }
      if(fastMaArray[0] > slowMaArray[0] && fastMaArray[1] < slowMaArray[1])
        {
         // Close sell order
         //if(sellTicket > 0)
         //  {
         //   PositionSelectByTicket(sellTicket);
         //   Print("FAST Ma is now>than SLOW Ma");
         double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
         double sl = 0; // ask - 500 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
         double tp = 0; // ask + 500 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
         Trade.Buy(_Symbol, 0.1, sl, tp, "BUY");
         //}
        }
      if(fastMaArray[0] < slowMaArray[0] && fastMaArray[1] > slowMaArray[1] && buyTicket > 0)
        {
         // Close buy order
         for(int i = 0; i < ArraySize(buyTickets); i++)
           {
            ulong ticket = buyTickets[i];
            PositionSelectByTicket(ticket);
            Trade.Close(ticket);
            Print("FAST Ma is now<than SLOW Ma And Cloooooooooooooooooose");
           }
        }
     }
  }

Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
  • www.mql5.com
Position ticket. Unique number assigned to each newly opened position. It usually matches the ticket of an order used to open the position except when the ticket is changed as a result of service operations on the server, for example, when charging swaps with position re-opening. To find an order used to open a position, apply the...
 

What is 'Mql5Book'?


The correct entry looks like this:

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

Error: You get a NEW HANDLE of the indicator at every tick!

void OnTick()
  {
   static datetime timestamp;
   datetime time = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(timestamp != time)
     {
      timestamp = time;
      static int handleSlowMa = iMA(_Symbol, PERIOD_CURRENT, 9, 0, MODE_EMA, PRICE_CLOSE);
      double slowMaArray[];
      CopyBuffer(handleSlowMa, 0, 1, 2, slowMaArray);
      ArraySetAsSeries(slowMaArray, true);
      static int handleFastMa = iMA(_Symbol, PERIOD_CURRENT, 5, 0, MODE_EMA, PRICE_CLOSE);
      double fastMaArray[];

This is the BIGGEST mistake. Read the help: the indicator handle MUST BE RECEIVED ONCE in OnInit.

 

Error: You get a NEW HANDLE of the indicator at every tick!

the EA gets in Buy positions well But I do have close positions problem

The Fundamentals of Testing in MetaTrader 5
The Fundamentals of Testing in MetaTrader 5
  • www.mql5.com
The idea of ​​automated trading is appealing by the fact that the trading robot can work non-stop for 24 hours a day, seven days a week. The robot does not get tired, doubtful or scared, it's is totally free from any psychological problems. It is sufficient enough to clearly formalize the trading rules and implement them in the algorithms, and...
 
hassan077 :

Error: You get a NEW HANDLE of the indicator at  every tick !

the EA gets in Buy positions well But I do have close positions problem

Correct your code. You are making a BIGGEST MISTAKE. How to create an indicator handle - see the help: iMA

Documentation on MQL5: Technical Indicators / iMA
Documentation on MQL5: Technical Indicators / iMA
  • www.mql5.com
//|                                                     Demo_iMA.mq5 | //|                        Copyright 2011, MetaQuotes Software Corp. | //|                                              https://www.mql5.com | "The method of creation of the handle is set through the 'type' parameter (function type...
 
hassan077: I have put the handle in onInit

Please edit your post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
          General rules and best pratices of the Forum. - General - MQL5 programming forum 2019.05.06
          Messages Editor

 
#include <Mql5\Trade.mqh>

CTrade trade;
#include <Mql5\TradeHedge.mqh>
CTradeHedge Trade;
ulong posTicket;
// Global variables
double slowMaArray[];
double fastMaArray[];
static int handleSlowMa = 0;
static int handleFastMa = 0;
int OnInit()
  {
   handleSlowMa = iMA(_Symbol, PERIOD_CURRENT, 9, 0, MODE_EMA, PRICE_CLOSE);
   handleFastMa = iMA(_Symbol, PERIOD_CURRENT, 5, 0, MODE_EMA, PRICE_CLOSE);
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   static datetime timestamp;
   datetime time = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(timestamp != time)
     {
      timestamp = time;
      CopyBuffer(handleSlowMa, 0, 1, 2, slowMaArray);
      ArraySetAsSeries(slowMaArray, true);
      CopyBuffer(handleFastMa, 0, 1, 2, fastMaArray);
      ArraySetAsSeries(fastMaArray, true);
      // Get current market orders
      ulong buyTicket = 0, sellTicket = 0;
      int buyTicketCount = 0;
      int sellTicketCount = 0;
      ulong buyTickets[];
      ulong sellTickets[];
      for(int i = 0; i < PositionsTotal(); i++)
        {
         ulong ticket = PositionGetTicket(i);
         PositionSelectByTicket(ticket);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            buyTicketCount++;
            ArrayResize(buyTickets, buyTicketCount);
            buyTickets[ArraySize(buyTickets) - 1] = ticket;
            //buyTicket = ticket;
           }
         //else
         //   if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
         //     {
         //      sellTicket = ticket;
         //     }
        }
      if(fastMaArray[0] > slowMaArray[0] && fastMaArray[1] < slowMaArray[1])
        {
         // Close sell order
         //if(sellTicket > 0)
         //  {
         //   PositionSelectByTicket(sellTicket);
         //   Print("FAST Ma is now>than SLOW Ma");
         double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
         double sl = 0; // ask - 500 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
         double tp = 0; // ask + 500 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
         Trade.Buy(_Symbol, 0.1, sl, tp, "BUY");
         //}
        }
      if(fastMaArray[0] < slowMaArray[0] && fastMaArray[1] > slowMaArray[1] && buyTicket > 0)
        {
         // Close buy order
         for(int i = 0; i < ArraySize(buyTickets); i++)
           {
            ulong ticket = buyTickets[i];
            PositionSelectByTicket(ticket);
            Trade.Close(ticket);
            Print("FAST Ma is now<than SLOW Ma And Cloooooooooooooooooose");
           }
        }
     }
  }

@Vladimir Karputov


I have put the handle in onInit function same result as the first EA


 
hassan077 :

@Vladimir Karputov


I have put the handle in onInit function same result as the first EA


You have fixed a bug with indicators.

Your code won't compile - you'll get a bunch of errors. Now fix

 #include  <Mql5\Trade.mqh>
 #include  <Mql5\TradeHedge.mqh>

It should be like this:

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

In general, the code that closes all positions looks like this:

//+------------------------------------------------------------------+
//| Close all positions                                              |
//+------------------------------------------------------------------+
void CloseAllPositions(void)
  {
   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)
            m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
  }
 

@Vladimir Karputov

@William Roeder

finely this code worked for me

//+------------------------------------------------------------------+
//|                                                     Multi TP.mq5 |
//|                          Copyright 2020, Multi TP Software Corp. |
//|                                         https://www.robostar.com |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+

#include <Mql5Book\Trade.mqh>
CTrade trade;
#include <Mql5Book\TradeHedge.mqh>
CTradeHedge Trade;
ulong posTicket;
// Global variables
double slowMaArray[];
double fastMaArray[];
static int handleSlowMa = 0;
static int handleFastMa = 0;
int OnInit()
  {
   handleSlowMa = iMA(_Symbol, PERIOD_CURRENT, 9, 0, MODE_EMA, PRICE_CLOSE);
   handleFastMa = iMA(_Symbol, PERIOD_CURRENT, 5, 0, MODE_EMA, PRICE_CLOSE);
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   static datetime timestamp;
   datetime time = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(timestamp != time)
     {
      timestamp = time;
      CopyBuffer(handleSlowMa, 0, 1, 2, slowMaArray);
      ArraySetAsSeries(slowMaArray, true);
      CopyBuffer(handleFastMa, 0, 1, 2, fastMaArray);
      ArraySetAsSeries(fastMaArray, true);
      // Get current market orders
      int buyTicketCount = 0;
      int sellTicketCount = 0;
      ulong buyTickets[];
      ulong sellTickets[];
      for(int i = 0; i < PositionsTotal(); i++)
        {
         ulong ticket = PositionGetTicket(i);
         PositionSelectByTicket(ticket);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            buyTicketCount++;
            ulong buyTicket;
            ArrayResize(buyTickets, buyTicketCount);
            buyTickets[ArraySize(buyTickets) - 1] = ticket;
            buyTicket = ticket;
           }
        }
      if(fastMaArray[0] > slowMaArray[0] && fastMaArray[1] < slowMaArray[1])
        {
         double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
         double sl = 0; // ask - 500 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
         double tp = 0; // ask + 500 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
         Trade.Buy(_Symbol, 0.1, sl, tp, "BUY");
         //}
        }
      if(fastMaArray[0] < slowMaArray[0] && fastMaArray[1] > slowMaArray[1])
        {
         // Close buy order
         for(int i = 0; i < ArraySize(buyTickets); i++)
           {
            ulong ticket = buyTickets[i];
            PositionSelectByTicket(ticket);
            Trade.Close(ticket);
            Print("FAST Ma is now<than SLOW Ma And Cloooooooooooooooooose");
           }
        }
     }
  }
//+------------------------------------------------------------------+
 

@Vladimir Karputov


thank you very much

Vladimir Karputov
Vladimir Karputov
  • www.mql5.com
Trader's profile