EA doesnt place trades..

 

Hello there! :)

At start ill say that im beginner writing EA's but im trying my best to improve each day.

I have just managed to put all function together, at least what i thought, no error, compiling no problem. But when i put it into test, indicators load, but it doesnt take a trade, if anybody could help me figure out what is the problem, i would really appreciate help. And no Im not using chatgpt or any AI to create code, functions. If i would I would have no freacking clue whats what here. okay. Here is the Ea..

#include  <Trade\Trade.mqh>
   CTrade         trade;
   CPositionInfo  posinfo;
   COrderInfo     ord;
#include  <Indicators\Trend.mqh>
   CiBands        Bollinger;
   CiMA           MovAvgFast, MovAvgSlow;
#include  <Indicators\Oscilators.mqh>
   CiRSI          RSI;
   enum StartHour {SInactive=0, S1=1, S2=2, S3=3, S4=4, S5=5, S6=6, S7=7, S8=8, S9=9, S10=10, S11=11, S12=12, S13=13, S14=14, S15=15, S16=16, S17=17, S18=18, S19=19, S20=20, S21=21, S22=22, S23=23,};
   enum EndHour {EInactive=0, E1=1, E2=2, E3=3, E4=4, E5=5, E6=6, E7=7, E8=8, E9=9, E10=10, E11=11, E12=12, E13=13, E14=14, E15=15, E16=16, E17=17, E18=18, E19=19, E20=20, E21=21, E22=22, E23=23};
   enum LotTyp    {Fixed=0, RiskPercent=1,};
   enum SystemType{Forex=0, _Gold=1, Bitcoin=2, Indicies=3};
   
       
   input group "||-->[ Main EA Settings ]<--||"
      input    int               InpMagic       = 270591;            // EA UNIQE ID
      input    ENUM_TIMEFRAMES   Timeframe      = PERIOD_M5;    // Timeframe to run EA
      input    StartHour         SHInput        = 0;                 // Time for EA to Starts Trading (0 = Trades All Day)
      input    EndHour           EHInput        = 0;                 // Time for EA to Stop Trading (0 = Trades All Day)
   input group "||-->[ Trading System Profile ]<--||"
   input SystemType SType=0; //Trading System Apllied (Forex, Bitcoin, Gold, Indicies)
   int SysChoice;
      
   input group "||-->[ Strategy Selection ]<--||"
      input    bool        BollingerRSI         = true;              // Bollinger+RSI Reversals
      input    bool        Highlow              = true;              // High and lows trend continuations
      
   input group "||-->[ Money Management ]<--||"
      input    LotTyp      Lot_Type             = 0;                 // Type of Lotsize
      input    double      Fixed                = 0.02;              // Fixed
      input    double      RiskPercent          = 3;                 // Risk Percent of trading Capital
      input    double      BuyExitPct           = 5;                 // Close open trade if profit > % starting balance
   
   input group "||-->[ Trade Management ]<--||"
      input    int         Maxtradessymbol      = 0;                 // Max open trades per pair (0=Unlimited)
      input    int         BarsSince            = 20;               // Bars before new trade can be taken
      
   input group "||-->[ Trade Settings ]<--||"
      input    int         BollingerMAperiod    = 20;               // Bollinger MA value
      input    double      BollingerStDev       = 2;                 // Bollinger Deviation
      input    int         RSIUpper             = 80;                // RSI Upper Level (for taking trades)
      input    int         RSILower             = 20;                // RSI Lower Level (for taking trades)
      input    int         RSIPeriod            = 14;                // RSI Period
      input    int         BarsN                = 5;                 // Number of candle below/above to define HighLow
   input group "||-->[ Moving Average Filter ]<--||"
      input    bool        MAFilterOn           = false;             // Buy above or Sell below MA Fast > MA Slow
      input    ENUM_TIMEFRAMES   MATimeframe    = PERIOD_D1;         // Timeframe to Moving Average Filter
      input    int         Slow_MA_Period       = 200;               // Slow Moving Average Period
      input    int         Fast_MA_Period       = 50;                // Fast Moving Average Period
      input    ENUM_MA_METHOD    MA_MODE        = MODE_EMA;          // Type of applied Moving Average
      input    ENUM_APPLIED_PRICE   MA_AppPrice = PRICE_MEDIAN;      // Moving Average Applied Price                       
   input group "||-->[ Forex Profile ]<--||"
      input    int         TppointsInput         = 200;              // Take Profit (10 points = 1pip)
      input    int         SlpointsInput         = 100;              // Stop Loss   (10 points = 1pip)
      input    int         TslTriggerPointsInput = 50;               // Points in profit before Trailing SL is activated
      input    int         TslPointsInput        = 10;               // Trailing Stop Loss step
      
   input group "|-->[ Gold Profile ]<--|"
      
      input    double      TPasPctGold           = 0.5;              // TP as % of price 
      input    double      SLasPctGold           = 0.6;              // SL as % of price
      input    double      TSLasPctofTPGold      = 4;                // Trail SL as % of TP
      input    double      TSLTgrasPctofTPGold   = 20;                // Trigger of Trail SL % of TP
         
   input group "||-->[ Bitcoin Profile ]<--||"
      
      input    double      TPasPct               = 0.4;              // TP as % of price 
      input    double      SLasPct               = 0.4;              // SL as % of price
      input    double      TSLasPctofTP          = 4;                // Trail SL as % of TP
      input    double      TSLTgrasPctofTP       = 7;                // Trigger of Trail SL % of TP
         
   input group "||-->[ Indicies Profile ]<--||"
      
      input    double      TPasPctIndicies       =0.2;               // TP as % of price 
      input    double      SLasPctIndicies       =0.2;               // SL as % of price
      input    double      TSLasPctofTPIndicies  =5;                 // Trail SL as % of TP
      input    double      TSLTgrasPctofTPIndicies =7;               // Trigger of Trail SL % of TP         
      
      int   SHChoice;
      int   EHChoice;
      ENUM_APPLIED_PRICE   AppPrice                = PRICE_MEDIAN;   // Moving Avg Applied Price
      int BarsLastTraded = 0;
      double   Tppoints,Slpoints,TslTriggerPoints,TslPoints;
      double         OrderDistPoints = 25;
int OnInit(){
   trade.SetExpertMagicNumber(InpMagic);
   
   ChartSetInteger(0,CHART_SHOW_GRID,false);
   SHChoice = SHInput;
   EHChoice = EHInput;
   
   if(SType==0) SysChoice=0;
   if(SType==1) SysChoice=1;
   if(SType==2) SysChoice=2;
   if(SType==3) SysChoice=3;
   
   Tppoints = TppointsInput;
   Slpoints = SlpointsInput;
   TslTriggerPoints = TslTriggerPointsInput;
   TslPoints = TslPointsInput;
   
   
   return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason){
   
}
void OnTick(){
   
   string symbol = _Symbol;
      if(PositionsTotal()>0){
      TrailSL(symbol);
      if(BuyExitPct!=0) ExitPositionsinProfit(symbol);
   if(!IsNewBar()) return;
         MqlDateTime time;
         TimeToStruct(TimeCurrent(), time);
         int Hournow = time.hour;
         
         if(Hournow < SHChoice || Hournow > EHChoice) return;
         
      if(SysChoice==1){
      double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      Tppoints = ask * TPasPct;
      Slpoints = ask * SLasPct;
      OrderDistPoints = Tppoints/2;
      TslPoints = Tppoints * TSLasPctofTP/100;
      TslTriggerPoints = Tppoints * TSLTgrasPctofTP/100;
   }
   
   if(SysChoice==2){
      double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      Tppoints = ask * TPasPctGold;
      Slpoints = ask * SLasPctGold;
      OrderDistPoints = Tppoints/2;
      TslPoints = Tppoints * TSLasPctofTPGold/100;
      TslTriggerPoints = Tppoints * TSLTgrasPctofTPGold/100;
   }
   
      if(SysChoice==3){
      double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      Tppoints = ask * TPasPctIndicies;
      Slpoints = ask * SLasPctIndicies;
      OrderDistPoints = Tppoints/2;
      TslPoints = Tppoints * TSLasPctofTPIndicies/100;
      TslTriggerPoints = Tppoints * TSLTgrasPctofTPIndicies/100;
   }
   }   
    if(BollingerRSI==true){
      Bollinger   = new CiBands;
      Bollinger.Create(symbol,Timeframe,BollingerMAperiod,0,BollingerStDev,AppPrice);
      RSI         = new CiRSI;
      RSI.Create(symbol,Timeframe,RSIPeriod,AppPrice);
      RSI.Refresh(-1);
      Bollinger.Refresh(-1);
     }
     double FastMA=0, SlowMA=0;
     if(MAFilterOn){
       MovAvgSlow  = new CiMA;
       MovAvgSlow.Create(symbol,MATimeframe,Slow_MA_Period,0,MA_MODE,MA_AppPrice);
       MovAvgFast  = new CiMA;
       MovAvgFast.Create(symbol,MATimeframe,Fast_MA_Period,0,MA_MODE,MA_AppPrice);
       MovAvgSlow.Refresh(-1);
       MovAvgFast.Refresh(-1);
     
       FastMA = MovAvgFast.Main(1);
       SlowMA = MovAvgSlow.Main(1);
     }
   
     double ask = SymbolInfoDouble(symbol,SYMBOL_ASK);
     double bid = SymbolInfoDouble(symbol,SYMBOL_BID);
     double previousHigh = findHigh(symbol);
     double previousLow  = findLow(symbol);
     double Closex1 = iClose(symbol,Timeframe,1);
//     int BarLastTraded = GetBarLastTraded(symbol);
     int Barsnow = iBars(symbol,Timeframe);
   
     if(Highlow==true){
         if(bid > previousHigh + 20 * _Point &&
            Barsnow > BarsLastTraded + BarsSince &&
            (Maxtradessymbol==0 || OpenTradessymbol(symbol)<Maxtradessymbol)){
            if(MAFilterOn && PricevsMovAvg(FastMA,SlowMA)!="above") return;      
                SendMarketBuyOrder(symbol);
                BarsLastTraded = iBars(symbol,Timeframe);
         }             
     }
     if(Highlow==true){
          if(ask < previousLow - 20 * _Point &&
            Barsnow > BarsLastTraded + BarsSince &&
            (Maxtradessymbol==0 || OpenTradessymbol(symbol)<Maxtradessymbol)){
            if(MAFilterOn && PricevsMovAvg(FastMA,SlowMA)!="below") return;
                SendMarketSellOrder(symbol);
          }     BarsLastTraded = iBars(symbol,Timeframe);
     }
     if(BollingerRSI==true){
        if(Closex1 < Bollinger.Lower(1) &&
           Barsnow > BarsLastTraded + BarsSince &&
           (Maxtradessymbol==0 || OpenTradessymbol(symbol)<Maxtradessymbol) &&
           RSI.Main(1)<RSILower
          ){
           if(MAFilterOn && PricevsMovAvg(FastMA,SlowMA)!="above") return;
               SendMarketBuyOrder(symbol);
               BarsLastTraded = iBars(symbol,Timeframe);
         } 
     }
     if(BollingerRSI==true){
         if(Closex1 > Bollinger.Upper(1) &&
            Barsnow > BarsLastTraded + BarsSince &&
            (Maxtradessymbol==0 || OpenTradessymbol(symbol)<Maxtradessymbol) &&            
            RSI.Main(0)>RSIUpper
           ){
            if(MAFilterOn && PricevsMovAvg(FastMA,SlowMA)!="below") return;         
              SendMarketSellOrder(symbol);
              BarsLastTraded = iBars(symbol,Timeframe);
         }   
     }
    
}
//+------------------------------------------------------------------+
void SendMarketBuyOrder(string symbol){
    double AccountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
    double ask = SymbolInfoDouble(symbol,SYMBOL_ASK);
    double tp = ask + Tppoints * _Point;
    double sl = ask - Slpoints * _Point;
    double lotSize = 0;
      switch(Lot_Type){
         case 0:  
            lotSize = Fixed; break;
         case 1:
            lotSize = RiskPercent;
            if(RiskPercent > 0 ) lotSize = calcLots(ask-sl);
      }
      trade.Buy(lotSize, symbol, ask, sl, tp, NULL);
}
void SendMarketSellOrder(string symbol){
    double AccountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
    double bid = SymbolInfoDouble(symbol,SYMBOL_ASK);
    double tp = bid - Tppoints * _Point;
    double sl = bid + Slpoints * _Point;
    double lotSize = 0;
      switch(Lot_Type){
         case 0:  
            lotSize = Fixed; break;
         case 1:
            lotSize = RiskPercent;
            if(RiskPercent > 0 ) lotSize = calcLots(sl-bid);
            
      }
      trade.Sell(lotSize, symbol, bid, sl, tp, NULL);
}
double calcLots(double slPoints){
   double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
   
   double ticksize = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   double tickvalue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
   double lotstep = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   double minvolume = SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
   double maxvolume = SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
   double volumelimit = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_LIMIT);
   
   
   
   double moneyPerLotstep = Slpoints / ticksize * tickvalue * lotstep;
   double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
   
   if(volumelimit!=0) lots = MathMin(lots,volumelimit);
   if(maxvolume!=0) lots = MathMin(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX));
   if(minvolume!=0) lots = MathMax(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN));
   lots = NormalizeDouble(lots,2);
   
   return lots;
}
            
double findHigh(string symbol){
   double highestHigh = 0;  
      for(int i = 0; i < 200; i++){      
      double high = iHigh(symbol,Timeframe,i);
         if(i > BarsN && iHighest(symbol,Timeframe,MODE_HIGH,BarsN*2+1,i-BarsN) == i){
            if(high > highestHigh){
               return high;
            }
         }
      highestHigh = MathMax(high,highestHigh);
      }
      return -1;
}
double findLow(string symbol){
   double lowestLow = DBL_MAX;
   for(int i = 0; i < 200; i++){
      double low = iLow(symbol,Timeframe,i);
      if(i > BarsN && iLowest(symbol,Timeframe,MODE_LOW,BarsN*2+1,i-BarsN) == i){
         if(low < lowestLow){
            return low;
         }   
      }
      lowestLow = MathMin(low,lowestLow);
   }
   return -1;
}
bool IsNewBar(){
      static datetime previousTime = 0;
      datetime currentTime = iTime(_Symbol,PERIOD_CURRENT,0);
      if(previousTime!=currentTime){
         previousTime=currentTime;
         return true;
      }
      return false;
}
void TrailSL(string symbol){
   double sl = 0;
   double tp = 0;      
   double ask = SymbolInfoDouble(symbol,SYMBOL_ASK);
   double bid = SymbolInfoDouble(symbol,SYMBOL_BID);
   
       for (int i=PositionsTotal()-1; i>=0; i--){
            if(posinfo.SelectByIndex(i)){
              ulong ticket = posinfo.Ticket();
                  if(posinfo.Magic()==InpMagic && posinfo.Symbol()==symbol){
                        if(posinfo.PositionType()==POSITION_TYPE_BUY){
                           if(bid-posinfo.PriceOpen()>TslTriggerPoints*_Point){
                              tp = posinfo.TakeProfit();
                              sl = bid - (TslPoints * _Point);
                        
                              if(sl > posinfo.StopLoss() && sl!=0){
                                 trade.PositionModify(ticket,sl,tp);
                              }                       
                           }
                        }
                      else if(posinfo.PositionType()==POSITION_TYPE_SELL){
                        if(ask+(TslTriggerPoints*_Point)<posinfo.PriceOpen()){
                           tp = posinfo.TakeProfit();
                           sl = ask + (TslPoints * _Point);
                           if(sl < posinfo.StopLoss() && sl!=0){
                                 trade.PositionModify(ticket,sl,tp);
                           }
                        }
                     }
                  }                  
            }      
 
      } 
} 
string PricevsMovAvg(double MAfast, double MAslow){
      if(MAfast>MAslow) return "above";
      if(MAfast<MAslow) return "below";
      
return "error";
}
void ExitPositionsinProfit(string symbol){
      double totalProfit = 0;
      double accbalance  = AccountInfoDouble(ACCOUNT_BALANCE);
      
      for(int i = PositionsTotal()-1; i>=0; i--){
         posinfo.SelectByIndex(i);
         if(posinfo.Symbol() == symbol && posinfo.Magic()==InpMagic){
               totalProfit += posinfo.Profit();
         }
      }
      
      if(totalProfit >= accbalance*BuyExitPct/100){
         for(int i = PositionsTotal()-1; i>=0; i--){
            posinfo.SelectByIndex(i);
            ulong ticket = posinfo.Ticket();
            if(posinfo.Symbol() == symbol && posinfo.Magic()==InpMagic){
               trade.PositionClose(ticket);
            }
         }
      }
}
int OpenTradessymbol(string symbol){
   int   OpenTrades = 0;
   
   for(int i = PositionsTotal()-1; i>=0; i--){
      posinfo.SelectByIndex(i);
      if(posinfo.Magic()==InpMagic && posinfo.Symbol()==symbol){
         OpenTrades++;
      }
   }
   
return OpenTrades;
}
 
Mark:

Hello there! :)

At start ill say that im beginner writing EA's but im trying my best to improve each day.

I have just managed to put all function together, at least what i thought, no error, compiling no problem. But when i put it into test, indicators load, but it doesnt take a trade, if anybody could help me figure out what is the problem, i would really appreciate help. And no Im not using chatgpt or any AI to create code, functions. If i would I would have no freacking clue whats what here. okay. Here is the Ea..

I think that the issue is in, for example:

      switch(Lot_Type){
         case 0:  
            lotSize = Fixed; break;
         case 1:
            lotSize = RiskPercent;
            if(RiskPercent > 0 ) lotSize = calcLots(ask-sl);
      }
      trade.Buy(lotSize, symbol, ask, sl, tp, NULL);

"The case keyword with a constant are just labels, and if operators are executed for some case variant, the program will further execute the operators of all subsequent variants until the break operator occurs."

Try adding break in case 1.

Switch Operator - Operators - Language Basics - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5

Documentation on MQL5: Language Basics / Operators / Break Operator
Documentation on MQL5: Language Basics / Operators / Break Operator
  • www.mql5.com
The break operator terminates the execution of the nearest nested outward switch , while , do-while or for operator. The control is passed to the...