How to start with MQL5 - page 30

 
CodeFx # :

***

However, my initial code opened several positions yearly as expected but its problem was just that when the last opened Buy position is in losses it fails to open a sell position as intended . Kindly have a look at the code:

***

  

I do not understand. Describe in other words.

And further:

 
Vladimir Karputov #:

I do not understand. Describe in other words.

And further:


I meant when the last opened position is a Buy (with its Lot size being currently the highest and no opened position has equal Lot size)  and the current market trend goes downwards thereby making this Buy position to lose minimum of 250 pips, that is not making profit, then the EA ought to open a Sell position with same Lot size as that Buy. 

Thanks for your help.

 
CodeFx #:
I meant when the last opened position is a Buy (with its Lot size being currently the highest and no opened position has equal Lot size)  and the current market trend goes downwards thereby making this Buy position to lose minimum of 250 pips, that is not making profit, then the EA ought to open a Sell position with same Lot size as that Buy. 

Ok. Add code:

 
CodeFx # :

I meant when the last opened position is a Buy (with its Lot size being currently the highest and no opened position has equal Lot size)  and the current market trend goes downwards thereby making this Buy position to lose minimum of 250 pips, that is not making profit, then the EA ought to open a Sell position with same Lot size as that Buy. 

Thanks for your help.

Your mistake: You remember the parameters of a certain position, but for some reason compare in the m_positions object:

      if(last_position_type==POSITION_TYPE_BUY && last_position_price_open> m_position.PriceCurrent() + (m_take_profit))
         if(count_max_volume==1 && last_position_volume==max_volume)
            m_trade.Sell(last_position_volume*1.0,m_symbol.Name(),Bid,0,(Bid-m_take_profit),NULL);
 
Vladimir Karputov #:

Ok. Add code:


When the last opened position is a Buy (with its Lot size being currently the highest and no opened position has equal Lot size)  and the current market trend goes downwards thereby making this Buy position to lose minimum of 250 pips, that is not making profit, then the EA should open a Sell position with same Lot size as that Buy and vice versa. 

Kindly see my original code, before your proposed solution, below:

//+------------------------------------------------------------------+
//|                                                 New edition).mq5 |
//|                                              Copyright © 2021,   |
//|                                          |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021"
#property link      "CodeFx"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
#include <Trade\OrderInfo.mqh>

CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
COrderInfo     m_order;                      // pending orders object
//--- input parameters
input ushort   InpStep           = 10;
input double   InpLot            = 0.01;
ulong          m_magic           = 12345;    // magic number
ulong          m_slippage        = 30;       // slippage
//---
double         ExtStep           = 0.0;
double         m_adjusted_point;             // point value adjusted for 3 or 5 points
input int      PF                = 10;       // Incremental Profit To Close All Trades
input int      DEP               = 1000;     // Deposit or Start Balance 
input int      TP                = 250;      // TakeProfit
double         Previous_balance  = AccountInfoDouble (ACCOUNT_BALANCE); // Balance at start of each algorithm  

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
 
   Comment("????? ????????? ",TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUTES|TIME_SECONDS));
//---
   if(!m_symbol.Name(Symbol())) // sets symbol name
      return(INIT_FAILED);
   RefreshRates();

   string err_text="";
   if(!CheckVolumeValue(InpLot,err_text))
     {
      Print(err_text);
      return(INIT_PARAMETERS_INCORRECT);
     }
//---
   m_trade.SetExpertMagicNumber(m_magic);
//---
   if(IsFillingTypeAllowed(m_symbol.Name(),SYMBOL_FILLING_FOK))
      m_trade.SetTypeFilling(ORDER_FILLING_FOK);
   else if(IsFillingTypeAllowed(m_symbol.Name(),SYMBOL_FILLING_IOC))
      m_trade.SetTypeFilling(ORDER_FILLING_IOC);
   else
      m_trade.SetTypeFilling(ORDER_FILLING_RETURN);
//---
   m_trade.SetDeviationInPoints(m_slippage);
//--- 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;

   ExtStep=InpStep*m_adjusted_point;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   datetime             last_position_time         = 0;
   double               last_position_price_open   = 0.0;
   double               last_position_volume       = 0.0;
   ENUM_POSITION_TYPE   last_position_type         = -1;
   int                  count_positions            = 0;    
   int                  count_max_volume           = 0;
   double               total_profit               = 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()==m_magic)
           {
            if(m_position.Time()>last_position_time)
              {
               last_position_time         = m_position.Time();
               last_position_price_open   = m_position.PriceOpen();
               last_position_volume       = m_position.Volume();
               last_position_type         = m_position.PositionType();               
              }
            count_positions++;
            count_max_volume++;           
            total_profit=total_profit+m_position.Commission()+m_position.Swap()+m_position.Profit();
           }
   int count_pending_orders=0;
   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders
      if(m_order.SelectByIndex(i)) // selects the pending order by index for further access to its properties
         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==m_magic)
            count_pending_orders++;

if (PositionsTotal()==0)
{Previous_balance = AccountInfoDouble (ACCOUNT_BALANCE);} 

double equity    = AccountInfoDouble (ACCOUNT_EQUITY);
if(equity > Previous_balance + PF) 
     {
      Print("Closing on profit");
      CloseAllPositions();
      return;
     } 

   if(!RefreshRates())
      return;

   if(count_positions>0)
     {
       double Ask=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_ASK),_Digits);
       double Bid=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_BID),_Digits); 
       double max_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
       
       if(last_position_type==POSITION_TYPE_BUY && m_symbol.Ask()-(TP * _Point) >last_position_price_open )                  
         m_trade.Buy(last_position_volume*2,m_symbol.Name(),Ask,0,(Ask+TP*_Point),NULL);
                                     
       if(last_position_type==POSITION_TYPE_BUY && last_position_price_open > m_position.PriceCurrent() + (TP * _Point) )                                 
       if(count_max_volume==1 && last_position_volume==max_volume) 
           m_trade.Sell(last_position_volume*1,m_symbol.Name(),Bid,0,(Bid-TP*_Point),NULL); 
                              
       if(last_position_type==POSITION_TYPE_SELL && m_symbol.Bid()+(TP * _Point) <last_position_price_open )       
         m_trade.Sell(last_position_volume*2,m_symbol.Name(),Bid,0,(Bid-TP*_Point),NULL);  
        
       if(last_position_type==POSITION_TYPE_SELL && last_position_price_open < m_position.PriceCurrent() - (TP * _Point) )                                                  
       if(count_max_volume==1 && last_position_volume==max_volume) 
           m_trade.Buy(last_position_volume*1,m_symbol.Name(),Ask,0,(Ask+TP*_Point),NULL);                                                                                                                   
               }

   if(count_positions==0 && count_pending_orders==0)
     {
      double Ask=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_ASK),_Digits);
      double Bid=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_BID),_Digits);     
      m_trade.Sell(InpLot,m_symbol.Name(),Bid,0,(Bid-TP*_Point),NULL);                 
      m_trade.Buy(InpLot,m_symbol.Name(),Ask,0,(Ask+TP*_Point),NULL);      
      return;
     }

   if(count_positions>0 && count_pending_orders>0)
      DeleteAllOrders();
//---
   return;
  }
//+------------------------------------------------------------------+
//| 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 the correctness of the order volume                        |
//+------------------------------------------------------------------+
bool CheckVolumeValue(double volume,string &error_description)
  {
//--- minimal allowed volume for trade operations
// double min_volume=m_symbol.LotsMin();
   double min_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
   if(volume<min_volume)
     {
      error_description=StringFormat("Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f",min_volume);
      return(false);
     }

//--- maximal allowed volume of trade operations
// double max_volume=m_symbol.LotsMax();
   double max_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
   if(volume>max_volume)
     {
      error_description=StringFormat("Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f",max_volume);
      return(false);
     }

//--- get minimal step of volume changing
// double volume_step=m_symbol.LotsStep();
   double volume_step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);

   int ratio=(int)MathRound(volume/volume_step);
   if(MathAbs(ratio*volume_step-volume)>0.0000001)
     {
      error_description=StringFormat("Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f",
                                     volume_step,ratio*volume_step);
      return(false);
     }
   error_description="Correct volume value";
   return(true);
  }
//+------------------------------------------------------------------+ 
//| Checks if the specified filling mode is allowed        .          | 
//+------------------------------------------------------------------+ 
bool IsFillingTypeAllowed(string symbol,int fill_type)
  {
//--- Obtain the value of the property that describes allowed filling modes 
   int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
//--- Return true, if mode fill_type is allowed 
   return((filling & fill_type)==fill_type);
  }
//+------------------------------------------------------------------+
//| Close all positions                                              |
//+------------------------------------------------------------------+
void CloseAllPositions()
  { 
   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()==m_magic)
            m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
  }
//+------------------------------------------------------------------+
//| Delete all pendingA rders                                         |
//+------------------------------------------------------------------+
void DeleteAllOrders()
  {
   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders
      if(m_order.SelectByIndex(i))     // selects the pending order by index for further access to its properties
         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==m_magic)
            m_trade.OrderDelete(m_order.Ticket());
  }
//+------------------------------------------------------------------+
Files:
 
Vladimir Karputov #:

Your mistake: You remember the parameters of a certain position, but for some reason compare in the m_positions object:

Thanks for your response. Kindly confirm your proposed correction is:

         if(last_position_type==POSITION_TYPE_BUY && last_position_price_open> m_symbol.Ask() + (m_take_profit))
         if(count_max_volume==1 && last_position_volume==max_volume)
            m_trade.Sell(last_position_volume*1.0,m_symbol.Name(),Bid,0,(Bid-m_take_profit),NULL);

Based on above, the complete code becomes thus: 

//+------------------------------------------------------------------+
//|                                                 New edition).mq5 |
//|                                              Copyright © 2021,   |
//|                                          |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021"
#property link      "CodeFx"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
#include <Trade\OrderInfo.mqh>

CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
COrderInfo     m_order;                      // pending orders object
//--- input parameters
input ushort   InpStep           = 10;
input double   InpLot            = 0.01;
ulong          m_magic           = 12345;    // magic number
ulong          m_slippage        = 30;       // slippage
//---
double         ExtStep           = 0.0;
double         m_adjusted_point;             // point value adjusted for 3 or 5 points
input int      PF                = 10;       // Incremental Profit To Close All Trades
input int      DEP               = 1000;     // Deposit or Start Balance 

double         Previous_balance  = AccountInfoDouble (ACCOUNT_BALANCE); // Balance at start of each algorithm  
double         m_take_profit     = 250;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
 
   Comment("????? ????????? ",TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUTES|TIME_SECONDS));
//---
   if(!m_symbol.Name(Symbol())) // sets symbol name
      return(INIT_FAILED);
   RefreshRates();

   string err_text="";
   if(!CheckVolumeValue(InpLot,err_text))
     {
      Print(err_text);
      return(INIT_PARAMETERS_INCORRECT);
     }
//---
   m_trade.SetExpertMagicNumber(m_magic);
//---
   if(IsFillingTypeAllowed(m_symbol.Name(),SYMBOL_FILLING_FOK))
      m_trade.SetTypeFilling(ORDER_FILLING_FOK);
   else if(IsFillingTypeAllowed(m_symbol.Name(),SYMBOL_FILLING_IOC))
      m_trade.SetTypeFilling(ORDER_FILLING_IOC);
   else
      m_trade.SetTypeFilling(ORDER_FILLING_RETURN);
//---
   m_trade.SetDeviationInPoints(m_slippage);
//--- 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;

   ExtStep=InpStep*m_adjusted_point;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   datetime             last_position_time         = 0;
   double               last_position_price_open   = 0.0;
   double               last_position_volume       = 0.0;
   ENUM_POSITION_TYPE   last_position_type         = -1;
   int                  count_positions            = 0;    
   int                  count_max_volume           = 0;
   double               total_profit               = 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()==m_magic)
           {
            if(m_position.Time()>last_position_time)
              {
               last_position_time         = m_position.Time();
               last_position_price_open   = m_position.PriceOpen();
               last_position_volume       = m_position.Volume();
               last_position_type         = m_position.PositionType();               
              }
            count_positions++;
            count_max_volume++;           
            total_profit=total_profit+m_position.Commission()+m_position.Swap()+m_position.Profit();
           }
   int count_pending_orders=0;
   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders
      if(m_order.SelectByIndex(i)) // selects the pending order by index for further access to its properties
         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==m_magic)
            count_pending_orders++;

if (PositionsTotal()==0)
{Previous_balance = AccountInfoDouble (ACCOUNT_BALANCE);} 

double equity    = AccountInfoDouble (ACCOUNT_EQUITY);
if(equity > Previous_balance + PF) 
     {
      Print("Closing on profit");
      CloseAllPositions();
      return;
     } 

   if(!RefreshRates())
      return;

   if(count_positions>0)
     {
       double Ask=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_ASK),_Digits);
       double Bid=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_BID),_Digits); 
       double max_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
       
       if(last_position_type==POSITION_TYPE_BUY && m_symbol.Ask()-(m_take_profit) >last_position_price_open )                  
         m_trade.Buy(last_position_volume*2,m_symbol.Name(),Ask,0,(Ask+m_take_profit),NULL);
                                     
       if(last_position_type==POSITION_TYPE_BUY && last_position_price_open> m_symbol.Ask() + (m_take_profit))
         if(count_max_volume==1 && last_position_volume==max_volume)
            m_trade.Sell(last_position_volume*1.0,m_symbol.Name(),Bid,0,(Bid-m_take_profit),NULL);
                                          
       if(last_position_type==POSITION_TYPE_SELL && m_symbol.Bid()+(m_take_profit) <last_position_price_open )       
         m_trade.Sell(last_position_volume*2,m_symbol.Name(),Bid,0,(Bid-m_take_profit),NULL);  
        
       if(last_position_type==POSITION_TYPE_SELL && last_position_price_open < m_symbol.Bid() - (m_take_profit) )                                                  
       if(count_max_volume==1 && last_position_volume==max_volume) 
           m_trade.Buy(last_position_volume*1,m_symbol.Name(),Ask,0,(Ask+m_take_profit),NULL);                                                                                                                   
               }

   if(count_positions==0 && count_pending_orders==0)
     {
      double Ask=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_ASK),_Digits);
      double Bid=NormalizeDouble (SymbolInfoDouble (_Symbol,SYMBOL_BID),_Digits);     
      m_trade.Sell(InpLot,m_symbol.Name(),Bid,0,(Bid-m_take_profit),NULL);                 
      m_trade.Buy(InpLot,m_symbol.Name(),Ask,0,(Ask+m_take_profit),NULL);      
      return;
     }

   if(count_positions>0 && count_pending_orders>0)
      DeleteAllOrders();
//---
   return;
  }
//+------------------------------------------------------------------+
//| 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 the correctness of the order volume                        |
//+------------------------------------------------------------------+
bool CheckVolumeValue(double volume,string &error_description)
  {
//--- minimal allowed volume for trade operations
// double min_volume=m_symbol.LotsMin();
   double min_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
   if(volume<min_volume)
     {
      error_description=StringFormat("Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f",min_volume);
      return(false);
     }

//--- maximal allowed volume of trade operations
// double max_volume=m_symbol.LotsMax();
   double max_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
   if(volume>max_volume)
     {
      error_description=StringFormat("Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f",max_volume);
      return(false);
     }

//--- get minimal step of volume changing
// double volume_step=m_symbol.LotsStep();
   double volume_step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);

   int ratio=(int)MathRound(volume/volume_step);
   if(MathAbs(ratio*volume_step-volume)>0.0000001)
     {
      error_description=StringFormat("Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f",
                                     volume_step,ratio*volume_step);
      return(false);
     }
   error_description="Correct volume value";
   return(true);
  }
//+------------------------------------------------------------------+ 
//| Checks if the specified filling mode is allowed        .          | 
//+------------------------------------------------------------------+ 
bool IsFillingTypeAllowed(string symbol,int fill_type)
  {
//--- Obtain the value of the property that describes allowed filling modes 
   int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
//--- Return true, if mode fill_type is allowed 
   return((filling & fill_type)==fill_type);
  }
//+------------------------------------------------------------------+
//| Close all positions                                              |
//+------------------------------------------------------------------+
void CloseAllPositions()
  { 
   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()==m_magic)
            m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
  }
//+------------------------------------------------------------------+
//| Delete all pendingA rders                                         |
//+------------------------------------------------------------------+
void DeleteAllOrders()
  {
   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders
      if(m_order.SelectByIndex(i))     // selects the pending order by index for further access to its properties
         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==m_magic)
            m_trade.OrderDelete(m_order.Ticket());
  }
//+------------------------------------------------------------------+


However, when backtested from January to September 2021, only 2 positions were opened.

 
CodeFx # :

Thanks for your response. Kindly confirm your proposed correction is:

Based on above, the complete code becomes thus: 


However, when backtested from January to September 2021, only 2 positions were opened.

Yes, now the train of thought is correct

 
Vladimir Karputov #:

Yes, now the train of thought is correct

Thanks for your reply. From year 2021 backtesting, EA opened last Buy position on 6th January 2021 and did not open any Sell after losing 250 pips and above till 23rd September 2021 when testing ended. 

Maybe the train of thought I coded is incorrect with respect to what I intend to achieve. 

In summary, I want the EA to function like this:   

1. At start, EA to open 1 Buy and 1 Sell positions with 0.01 Lot size each 

2. If last opened position is Buy and market trends up, allow current Buy to close with 250 pips take profit and open new Buy with double, 2 times, lot size of previous Buy. 

3. If last opened position is Buy and market trends down, immediately current Buy loses 250 pips (makes no profit) open Sell with same, 1 times, lot size of previous Buy. 

4. If last opened position is Sell and market trends down, allow current Sell to close with 250 pips take profit and open new Sell with double, 2 times, lot size of previous Sell. 

5. If last opened position is Sell and market trends up, immediately current Sell loses 250 pips (makes no profit) open Buy with same, 1 times, lot size of the previous Sell. 

6. Lastly, only 1 Buy and 1 Sell position can have similar (same) lot sizes,   

Thanks a lot for assisting.

 

 

 
CodeFx # :

Thanks for your reply. From year 2021 backtesting, EA opened last Buy position on 6th January 2021 and did not open any Sell after losing 250 pips and above till 23rd September 2021 when testing ended.  

Maybe the train of thought I coded is incorrect with respect to what I intend to achieve.  

In summary, I want the EA to function like this:     

1. At start, EA to open 1 Buy and 1 Sell positions with 0.01 Lot size each  

2. If last opened position is Buy and market trends up, allow current Buy to close with 250 pips take profit and open new Buy with double, 2 times, lot size of previous Buy.  

3. If last opened position is Buy and market trends down, immediately current Buy loses 250 pips (makes no profit) open Sell with same, 1 times, lot size of previous Buy.  

4. If last opened position is Sell and market trends down, allow current Sell to close with 250 pips take profit and open new Sell with double, 2 times, lot size of previous Sell.  

5. If last opened position is Sell and market trends up, immediately current Sell loses 250 pips (makes no profit) open Buy with same, 1 times, lot size of the previous Sell.  

6. Lastly, only 1 Buy and 1 Sell position can have similar (same) lot sizes,    

Thanks a lot for assisting.

 

 

I would work through OnTradeTransaction - I would catch the "EXIT" deal.

 
CodeFx # :

Thanks for your reply. From year 2021 backtesting, EA opened last Buy position on 6th January 2021 and did not open any Sell after losing 250 pips and above till 23rd September 2021 when testing ended.  

Maybe the train of thought I coded is incorrect with respect to what I intend to achieve.  

In summary, I want the EA to function like this:     

1. At start, EA to open 1 Buy and 1 Sell positions with 0.01 Lot size each  

2. If last opened position is Buy and market trends up, allow current Buy to close with 250 pips take profit and open new Buy with double, 2 times, lot size of previous Buy.  

3. If last opened position is Buy and market trends down, immediately current Buy loses 250 pips (makes no profit) open Sell with same, 1 times, lot size of previous Buy.  

4. If last opened position is Sell and market trends down, allow current Sell to close with 250 pips take profit and open new Sell with double, 2 times, lot size of previous Sell.  

5. If last opened position is Sell and market trends up, immediately current Sell loses 250 pips (makes no profit) open Buy with same, 1 times, lot size of the previous Sell.  

6. Lastly, only 1 Buy and 1 Sell position can have similar (same) lot sizes,    

Thanks a lot for assisting.

 

 

New Project 'Andromeda Nebula'

How to join the project

In MetaEditor, in the "Tools" window, go to the "Public Projects" tab, in the "Name" column on the "AlligatorAndStochastic" project, right click and select the "Join" item

AlligatorAndStochastic