Hi guys can you help me fix

 

if i change Lot size the robot not trading? 

and Trailing SL Not working

please

//+------------------------------------------------------------------+
//|                                                    KILANGIFX.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//+------------------------------------------------------------------+
//| Include                                                          |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
static input long    InpMagicnumber = 546872;  // magicnumber
static input double  InpLots = 0.01;           // lot size
input  int           InpBars = 20;             // bat for high/low
input  int           InpIndexFilter = 0;       // index filter in % (0=off)
input  int           InpStopLoss = 200;        // bars loss in points (0=off)
input  bool          InpTrailingSL = true;     // trailing stop loss?
input  int           InpTakeProfit = 0;        // take profit in points (0=off)

//+------------------------------------------------------------------+
//| Global variables                                                 |
//+------------------------------------------------------------------+
double high = 0; // highest price of the last N bars
double low = 0;  // lowest price of the last N bars
int highIdx = 0; // index of highest bar
int lowIdx = 0;  // index of lowest bar
MqlTick currentTick, previousTick;
CTrade trade;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//check for user imput
   if(!  CheckInputs())
     {
      return INIT_PARAMETERS_INCORRECT;
     }
// set magicnumber
   trade.SetExpertMagicNumber(InpMagicnumber);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  ObjectDelete(NULL,"high");
  ObjectDelete(NULL,"low");
  ObjectDelete(NULL,"text");
  ObjectDelete(NULL,"indexFilter");
  
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
// check for new bar open tick
   if(!IsNewBar()){return;} 
  
// get tick
   previousTick = currentTick;
   if(!SymbolInfoTick(_Symbol, currentTick))
     {
      Print("Failed to get current tick");
      return;
     }
// count open positions
   int cntBuy, cntSell;
   if(!CountopenPosition(cntBuy, cntSell))
     {
      return;
     }
// check for buy position
   if(cntBuy == 0 && high != 0 && previousTick.ask < high && currentTick.ask >= high && CheckIndexFilter(highIdx))
     {
      
// calculate stop loss / take profit
    double sl = InpStopLoss==00 ? 0 : currentTick.bid - InpStopLoss * _Point;
    double tp = InpTakeProfit==0 ? 0 : currentTick.bid + InpTakeProfit * _Point;
    if(!NormalizePrice(sl)){return;}
    if(!NormalizePrice(tp)){return;}
    
    trade.PositionOpen(_Symbol,ORDER_TYPE_BUY,InpLots,currentTick.ask,sl,tp,"KilangiFXEA");
      
     }
// check for sell position
   if(cntSell == 0 && low != 0 && previousTick.bid > low && currentTick.bid <= low && CheckIndexFilter(lowIdx))
     {
      // calculate stop loss / take profit
    double sl = InpStopLoss==00 ? 0 : currentTick.ask + InpStopLoss * _Point;
    double tp = InpTakeProfit==0 ? 0 : currentTick.ask - InpTakeProfit * _Point;
    if(!NormalizePrice(sl)){return;}
    if(!NormalizePrice(tp)){return;}
    
    trade.PositionOpen(_Symbol,ORDER_TYPE_SELL,InpLots,currentTick.bid,sl,tp,"KilangiFXEA");
     }

// update stop loss
    if(InpStopLoss>0 && InpTrailingSL){
    UpdateStopLoss(InpStopLoss*_Point)
    ;     
  } 
     
// calculate high/low
    highIdx = iHighest(_Symbol,PERIOD_CURRENT,MODE_HIGH,InpBars,1);
    lowIdx  = iLowest(_Symbol,PERIOD_CURRENT,MODE_LOW,InpBars,1);
    high = iHigh(_Symbol,PERIOD_CURRENT,highIdx);
    low  = iLow(_Symbol,PERIOD_CURRENT,lowIdx);
    
    DrawObjects();      
  }
  
  
//+------------------------------------------------------------------+
//| Functions                                                        |
//+------------------------------------------------------------------+
// check user input
bool CheckInputs()
  {
   if(InpMagicnumber <= 0)
     {
      Alert("Wrong input: Magicnumber <= 0");
      return false;
     }
   if(InpLots <= 0)
     {
      Alert("Wrong input: Lot size  <= 0");
      return false;
     }
   if(InpBars <= 0)
     {
      Alert("Wrong input: Bars <= 0");
      return false;
     }
     if(InpIndexFilter <0 || InpIndexFilter>=50)
     {
      Alert("Wrong input: Index filter < 0 or >= 50");
      return false;
     }
   if(InpStopLoss < 0)
     {
      Alert("Wrong input: Stop loss < 0");
      return false;
     }
   if(InpTakeProfit < 0)
     {
      Alert("Wrong input: Take profit < 0");
      return false;
     }
   return true;
  }


// check if high/low is inside valid index range
bool CheckIndexFilter(int index){

   if(InpIndexFilter>0 && (index<=round(InpBars*InpIndexFilter*0.01) || index>InpBars-round(InpBars*InpIndexFilter*0.01))){
      return false;
    }
    return true;
   }    
  
void DrawObjects(){  
  
  datetime time1 = iTime(_Symbol,PERIOD_CURRENT,InpBars);
  datetime time2 = iTime(_Symbol,PERIOD_CURRENT,2);
  
// high
  ObjectDelete(NULL,"high");
  ObjectCreate(NULL,"high",OBJ_TREND,0,time1,high,time2,high);
  ObjectSetInteger(NULL,"high",OBJPROP_WIDTH,3);
  ObjectSetInteger(NULL,"high",OBJPROP_COLOR,CheckIndexFilter(highIdx) ? clrLime : clrBlack);
   
// low
  ObjectDelete(NULL,"low");
  ObjectCreate(NULL,"low",OBJ_TREND,0,time1,low,time2,low);
  ObjectSetInteger(NULL,"low",OBJPROP_WIDTH,3);
  ObjectSetInteger(NULL,"low",OBJPROP_COLOR,CheckIndexFilter(lowIdx) ? clrLime : clrBlack); 
 
// index filter
  if(InpIndexFilter>0){
     datetime timeIF1 = iTime(_Symbol,PERIOD_CURRENT,(int)(InpBars-round(InpBars*InpIndexFilter*0.01)));
     datetime timeIF2 = iTime(_Symbol,PERIOD_CURRENT,(int)(round(InpBars*InpIndexFilter*0.01)));
     ObjectDelete(NULL,"indexFilter");
     ObjectCreate(NULL,"indexFilter",OBJ_RECTANGLE,0,timeIF1,low,timeIF2,high);
     ObjectSetInteger(NULL,"indexFilter",OBJPROP_BACK,true);
     ObjectSetInteger(NULL,"indexFilter",OBJPROP_FILL,true);
     ObjectSetInteger(NULL,"indexFilter",OBJPROP_COLOR,clrMintCream);   
  }
  
// text
  ObjectDelete(NULL,"text");
  ObjectCreate(NULL,"text",OBJ_TEXT,0,time2,low);
  ObjectSetInteger(NULL,"text",OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
  ObjectSetInteger(NULL,"text",OBJPROP_COLOR,clrBlack); 
  ObjectSetString(NULL,"text",OBJPROP_TEXT," Bars:"+(string)InpBars+
                                           " index filter:"+DoubleToString(round(InpBars*InpIndexFilter*0.01),0)+
                                           " high index:"+(string)highIdx+
                                           " low index:"+(string)lowIdx);
} 

//check if we have a bar open tick
bool IsNewBar(){
  
   static datetime previousTime = 0;
   datetime currentTime = iTime(_Symbol,PERIOD_CURRENT,0);
   if(previousTime!=currentTime){
      previousTime=currentTime;
      return true;
   }
   return false;
   
}       
  
// count open positions
bool CountopenPosition(int &cntBuy, int &cntSell)
  {
   cntBuy    = 0;
   cntSell   = 0;
   int total = PositionsTotal();
   for(int i = total - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(1);
      if(ticket <= 0)
        {
         Print("Failed to get position ticket");
         return false;
        }
      if(!PositionSelectByTicket(ticket))
        {
         Print("Failed to select position");
         return false;
        }
      long magic;
      if(!PositionGetInteger(POSITION_MAGIC, magic))
        {
         Print("Failed to get position magicnumber");
         return false;
        }
      if(magic == InpMagicnumber)
        {
         long type;
         if(!PositionGetInteger(POSITION_TYPE, type))
           {
            Print("Failed to get position type");
            return false;
           }
         if(type == POSITION_TYPE_BUY)
           {
            cntBuy++;
           }
         if(type == POSITION_TYPE_SELL)
           {
            cntSell++;
           }
        }
     }
   return true;
  }
// normalize price
bool NormalizePrice(double & price)
  {
   double tickSize = 0;
   if(!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, tickSize))
     {
      Print("Failed to get tick size");
      return false;
     }
   price = NormalizeDouble(MathRound(price / tickSize) * tickSize, _Digits);
   return true;
  }
// close positions
bool ClosePosition(int all_buy_sell)
  {
   int total = PositionsTotal();
   for(int i = total - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(1);
      if(ticket <= 0)
        {
         Print("Failed to get position ticket");
         return false;
        }
      if(!PositionSelectByTicket(ticket))
        {
         Print("Failed to select position");
         return false;
        }
      long magic;
      if(!PositionGetInteger(POSITION_MAGIC, magic))
        {
         Print("Failed to get position magicnumber");
         return false;
        }
      if(magic == InpMagicnumber)
        {
         long type;
         if(!PositionGetInteger(POSITION_TYPE, type))
           {
            Print("Failed to get position type");
            return false;
           }
         if(all_buy_sell == 1 && type == POSITION_TYPE_SELL)
           {
            continue;
           }
         if(all_buy_sell == 2 && type == POSITION_TYPE_BUY)
           {
            continue;
           }
         trade.PositionClose(ticket);
         if(trade.ResultRetcode() != TRADE_RETCODE_DONE)
           {
            Print("Failed to close position. ticket:",
                  (string)ticket, " result:", (string)trade.ResultRetcode(), ":", trade.CheckResultRetcodeDescription());
           }
        }
     }
   return true;
  }
  
// update stop loss
void UpdateStopLoss(double slDistance){

// loop through open positions
    int total = PositionsTotal();
    for(int i=total-1; i>=0; i--){
        ulong ticket = PositionGetTicket(i);
        if(ticket<=0){Print("Failed to get position ticket"); return;}
        if(!PositionSelectByTicket(ticket)){Print("Failed to select position by ticket"); return;}
        ulong magicnumber;
        if(!PositionGetInteger(POSITION_MAGIC,magicnumber)){Print("Failed to get position magicnumber"); return;}
        if(InpMagicnumber==magicnumber){
        
// get type
    long type;
    if(!PositionGetInteger(POSITION_TYPE,type)){Print("Failed to get position type"); return;} 
// get current sl and tp
    double currSL, currTP;
    if(!PositionGetDouble(POSITION_SL,currSL)) {Print("Failed to get position stop loss"); return;} 
    if(!PositionGetDouble(POSITION_TP,currTP)) {Print("Failed to get position take profit"); return;}
    
// calculate stop loss
    double currPrice = type==POSITION_TYPE_BUY ? currentTick.bid : currentTick.ask;
    int n            = type==POSITION_TYPE_BUY ? 1 : -1;
    double newSL     = currPrice - slDistance * n;
    if(!NormalizePrice(newSL)){return;}
    
// check if new stop loss is closer to current price than existing stop loss
    if((newSL*n) < (currSL*n) || NormalizeDouble(MathAbs(newSL-currSL),_Digits)<_Point){
// Print("No new stop loss needed");
       continue;
    }
    
// check for stop level
   long level = SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
   if(level!=0 && MathAbs(currPrice-newSL)<=level*_Point){
      Print("New stop loss inside stop level");
      continue;
   }       
   
// modify position with new stop loss
   if(!trade.PositionModify(ticket,newSL,currTP)){
      Print("Failed to modify position, ticket:",(string)ticket," currSL:",(string)currSL,
            " newSL:",(string)newSL,"currTP:",(string)currTP);
      return;
     }
    }
   }
}      
                       
//+------------------------------------------------------------------+
 
Abbas Mussa:

if i change Lot size the robot not trading? 

and Trailing SL Not working

please

add

  1. use OrderCheck() for a check of enough money.
  2. use the debugger to check the variable values for your trailing stop:
    Code debugging:  https://www.metatrader5.com/en/metaeditor/help/development/debug
    Error Handling and Logging in MQL5:  https://www.mql5.com/en/articles/2041
    Tracing, Debugging and Structural Analysis of Source Code, scroll down to: "Launching and Debuggin": https://www.mql5.com/en/articles/272

Documentation on MQL5: Trade Functions / OrderCheck
Documentation on MQL5: Trade Functions / OrderCheck
  • www.mql5.com
OrderCheck - Trade Functions - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
   int total = PositionsTotal();
   for(int i = total - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(1);
You are selecting the same ticket each time.
 
William Roeder #:
You are selecting the same ticket each time.
3 hours struggling can you edit my code plz
 
Carl Schreiber #:

add

  1. use OrderCheck() for a check of enough money.
  2. use the debugger to check the variable values for your trailing stop:
    Code debugging:  https://www.metatrader5.com/en/metaeditor/help/development/debug
    Error Handling and Logging in MQL5:  https://www.mql5.com/en/articles/2041
    Tracing, Debugging and Structural Analysis of Source Code, scroll down to: "Launching and Debuggin": https://www.mql5.com/en/articles/272

plz assist me to change code plz fix for me 3hours struggling


 
Abbas Mussa #: plz assist me to change code plz fix for me 3hours struggling

No, it is your responsibility if you are here to learn.

Put in the effort. We are not here to "serve" you. Only to offer advice.

If you are not here to learn, then use the Freelance job section.

Trading applications for MetaTrader 5 to order
Trading applications for MetaTrader 5 to order
  • 2023.04.17
  • www.mql5.com
The largest freelance service with MQL5 application developers
 
William Roeder #:
You are selecting the same ticket each time.

what to do

 
Fernando Carreiro #:

No, it is your responsibility if you are here to learn.

Put in the effort. We are not here to "serve" you. Only to offer advice.

If you are not here to learn, then use the Freelance job section.

mmh okay guide me then please

 
Abbas Mussa #: mmh okay guide me then please

We have done that already.

If you don't understand it, then you either ...

  • ... need to put in more effort into studying the MQL language on your own, or
  • ... you need to hire someone to tutor you or to code it for you.
 
Abbas Mussa #: mmh okay guide me then please

I previously posted: “You are selecting the same ticket each time.” What value are you passing to PositionGetTicket. Look carefully!

Reason: