Please Check out my Code

 
I am trying to find what is wrong

#property strict
#property version "1.00" 

input string TradeComment = "Peinjo"; 
input int MagicNumber = 101; 
input int Slippage = 3;
input int MaxSpread = 262;
input double FixedLot = 0;
input int RiskPercent = 20; 
input int MaxDrawdown = 3;  
input int StartHour = 19; 
input int EndHour = 1;
input int GMTOffset = 0;
input int Trailing = 7;   
input int Profit = 13; 
input int VelocityTrigger = 50; 
input int Offset = 11;
int VelocityTime = 7;   

int OrderExpiry = 15; 
int TickSample = 100;  
int r, gmt, brokerOffset, size, digits, stoplevel;

double marginRequirement, maxLot, minLot, lotSize, points, currentSpread, avgSpread, maxSpread, initialBalance, rateChange, rateTrigger, deleteRatio, commissionPoints;

double spreadSize[]; 
double tick[];
double avgtick[];
int tickTime[];   

string testerStartDate, testerEndDate; 

int lastBuyOrder, lastSellOrder;

bool calculateCommission = true;

double max = 0;

int OnInit() {   
   marginRequirement = SymbolInfoDouble(_Symbol, SYMBOL_MARGIN_INITIAL)/100;
   maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);  
   minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);  
   currentSpread = NormalizeDouble(_Ask - _Bid, _Digits); 
   stoplevel = ( int ) MathMax( SymbolInfoInteger(_Symbol, SYMBOL_FREEZE_LEVEL), SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) );
   if( stoplevel > Offset ) Offset = stoplevel;
   if( stoplevel > Trailing ) Trailing = stoplevel;
   avgSpread = currentSpread; 
   size = TickSample;
   ArrayResize( spreadSize, size ); 
   ArrayFill( spreadSize, 0, size, avgSpread );
   maxSpread = NormalizeDouble( MaxSpread * _Point, _Digits ); 
   rateTrigger = NormalizeDouble( ( double ) VelocityTrigger * _Point, _Digits );
   testerStartDate = StringConcatenate( Year(), "-", Month(), "-", Day() );
   initialBalance = AccountInfoDouble(ACCOUNT_BALANCE);  
   gmt = OfflineGMT();
   display();
   return ( INIT_SUCCEEDED );
} 

int OfflineGMT(){
   int bkrH = TimeHour(TimeCurrent());
   int gOffset =  bkrH - GMTOffset; 
   if( gOffset < 0 ) gOffset += 24;
   else if( gOffset > 23 ) gOffset -= 24;
   return ( gOffset );
}

void Commission(){ 
   if( !IsTesting() ){ 
      double rate = 0;
      for( int pos = HistoryDealsTotal() - 1; pos >= 0; pos-- ) {
         if( HistoryDealSelect( pos ) ) {
            if( HistoryDealProfit() != 0.0 ) {
               if( HistoryDealClosePrice() != HistoryDealOpenPrice() ) {
                  if( HistoryDealSymbol() == _Symbol ) {
                     calculateCommission = false;
                     rate = MathAbs( HistoryDealProfit() / MathAbs( HistoryDealClosePrice() - HistoryDealOpenPrice() ) );
                     commissionPoints = ( -HistoryDealCommission() ) / rate;
                     break;
                  }
               }
            }
         }
      } 
   }
}

void OnTick()
int OnTick()
{
int totalBuyStop = 0;
int totalSellStop = 0;
int totalTrades = 0;
int accountTrades = 0;
double accountEquity;
if( calculateCommission ) commission();
gmt = offlineGMT();
prepareSpread();
manageTicks();

for( int pos = 0; pos < OrdersTotal(); pos++ ) {
if( !OrderSelect( pos, SELECT_BY_POS, MODE_TRADES ) ) continue;
if( OrderSymbol() != Symbol() ) continue;
accountTrades++;
if( OrderMagicNumber() == MagicNumber ){
totalTrades++;
switch ( OrderType() ) {
case OP_BUYSTOP:
if( (int) TimeCurrent() - lastBuyOrder > VelocityTime )
if( !OrderDelete( OrderTicket() ) ) Print("Error deleting buy stop order #", OrderTicket(), ": ", GetLastError() );
totalBuyStop++;
break;
case OP_SELLSTOP:
if( (int) TimeCurrent() - lastSellOrder > VelocityTime )
if( !OrderDelete( OrderTicket() ) ) Print("Error deleting sell stop order #", OrderTicket(), ": ", GetLastError() );
totalSellStop++;
break;
case OP_BUY:
accountEquity = AccountBalance() + OrderProfit() + OrderCommission() + OrderSwap();
if( Bid - OrderOpenPrice() > ( Trailing * Point ) + commissionPoints + ( Profit * Point ) ){
if( OrderStopLoss() == 0.0 || Bid - OrderStopLoss() > Trailing * Point )
if( NormalizeDouble( Bid - ( Trailing * Point ), Digits ) != OrderStopLoss() )
if( !OrderModify( OrderTicket(), OrderOpenPrice(), NormalizeDouble( Bid - ( Trailing * Point ), Digits ), OrderTakeProfit(), 0 ) )
Print("Error modifying buy order #", OrderTicket(), ": ", GetLastError() );
} else {
if( accountEquity > max || accountEquity / AccountBalance() < ( ( double ) 100 - MaxDrawdown ) / 100 ){
if( Bid < OrderOpenPrice() - ( VelocityTrigger * Point ) )
if( OrderStopLoss() == 0.0 || Bid - OrderStopLoss() > ( Trailing * Point * Trailing ) )
if( NormalizeDouble( Bid - ( Trailing * Point ), Digits ) != OrderStopLoss() )
if( !OrderModify( OrderTicket(), OrderOpenPrice(), NormalizeDouble( Bid - ( Trailing * Point ), Digits ), OrderTakeProfit(), 0 ) )
Print("Error modifying buy order #", OrderTicket(), ": ", GetLastError() );
}
}
break;
if (OrderType() == OP_SELL) {
   double accountEquity = AccountBalance() + OrderProfit() + OrderCommission() + OrderSwap();
   if (OrderOpenPrice() - SymbolInfoDouble(_Symbol, SYMBOL_ASK) > (Trailing * _Point) + commissionPoints + (Profit * _Point)) {  
      if (OrderStopLoss() == 0.0 || OrderStopLoss() - SymbolInfoDouble(_Symbol, SYMBOL_ASK) > Trailing * _Point) {
         if (NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (Trailing * _Point), Digits) != OrderStopLoss()) {
            r = OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (Trailing * _Point), Digits), OrderTakeProfit(), 0);
         }                  
      }
   } else {
      if (accountEquity > max || accountEquity / AccountBalance() < ((double)100 - MaxDrawdown) / 100) {
         if (SymbolInfoDouble(_Symbol, SYMBOL_ASK) > OrderOpenPrice() + (VelocityTrigger * _Point)) {
            if (OrderStopLoss() == 0.0 || OrderStopLoss() - SymbolInfoDouble(_Symbol, SYMBOL_ASK) > (Trailing * _Point * Trailing)) {
               if (NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (Trailing * _Point), Digits) != OrderStopLoss()) {
                  r = OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (Trailing * _Point), Digits), OrderTakeProfit(), 0);
               }
            }
         }
      }
   }
} else if (totalTrades == 0 && accountTrades == 0) {
   if (rateChange > VelocityTrigger * _Point && avgSpread <= maxSpread && totalBuyStop < 1) { 
      ticket = OrderSend(_Symbol, OP_BUYSTOP, lotSize(), SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (totalBuyStop + 1.0) * (_Point * Offset), Slippage, 0, 0, TradeComment, MagicNumber, 0);
      lastBuyOrder = (int)TimeCurrent();
   } 
   if (rateChange < -VelocityTrigger * _Point && avgSpread <= maxSpread && totalSellStop < 1) { 
      ticket = OrderSend(_Symbol, OP_SELLSTOP, lotSize(), SymbolInfoDouble(_Symbol, SYMBOL_BID) - (totalSellStop + 1.0) * (_Point * Offset), Slippage, 0, 0, TradeComment, MagicNumber, 0);
      lastSellOrder = (int)TimeCurrent();
   }    
}
display();
return (0);
double lotSize(){
   double lotSize;
   if(FixedLot > 0){
      lotSize = NormalizeDouble(FixedLot, 2);
   } else {
      if(marginRequirement > 0){
         lotSize = MathMax(MathMin(NormalizeDouble(AccountBalance() * ((double)RiskPercent / 1000) * 0.01 / marginRequirement, 2), maxLot), minLot);
      }
   }
   return(NormalizeLots(lotSize));
}

double NormalizeLots(double p){
   double ls = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_LOTSTEP);
   return(MathRound(p / ls) * ls);
}

void prepareSpread(){
   if(!IsTesting()){
      double spreadSize_temp[];
      ArrayResize(spreadSize_temp, size - 1);
      ArrayCopy(spreadSize_temp, spreadSize, 0, 1, size - 1);
      ArrayResize(spreadSize_temp, size);
      spreadSize_temp[size-1] = NormalizeDouble(_Ask - _Bid, _Digits);
      ArrayCopy(spreadSize, spreadSize_temp, 0, 0);
      avgSpread = iMA(_Symbol, 0, size, 0, MODE_LWMA, PRICE_CLOSE);
   }
}
void manageTicks(){    
   double tick_temp[], tickTime_temp[], avgtick_temp[];
   ArrayResize( tick_temp, size - 1 );
   ArrayResize( tickTime_temp, size - 1 );
   ArrayCopy( tick_temp, tick, 0, 1, size - 1 ); 
   ArrayCopy( tickTime_temp, tickTime, 0, 1, size - 1 ); 
   ArrayResize( tick_temp, size ); 
   ArrayResize( tickTime_temp, size );
   tick_temp[size-1] = SymbolInfoDouble(_Symbol,SYMBOL_BID);
   tickTime_temp[size-1] = ( int ) TimeCurrent();
   ArrayCopy( tick, tick_temp, 0, 0 );    
   ArrayCopy( tickTime, tickTime_temp, 0, 0 ); 
   int timeNow = tickTime[size-1];
   double priceNow = tick[size-1];
   double priceThen = 0;   
   int period = 0;
   for( int i = size - 1; i >= 0; i-- ){ 
      period++;
      if( timeNow - tickTime[i] > VelocityTime ){
         priceThen = tick[i]; 
         break;
      }  
   }     
    
   rateChange = ( priceNow - priceThen );
   if( rateChange / Point > 5000 ) rateChange = 0;     
} 

string niceHour( int kgmt ){ 
   string m;
   if( kgmt > 12 ) {
      kgmt = kgmt - 12;
      m = "PM"; 
   } else {
      m = "AM";
      if( kgmt == 12 )
         m = "PM";
   }
   return ( StringConcatenate( kgmt, " ", m ) );
} 
void display(){  
    if( !Testing() ){ 
      string display = "  Peinjo\n"; 
      display = StringConcatenate( display, " ----------------------------------------\n" );
      display = StringConcatenate( display, "  Leverage: ", DoubleToStr( AccountLeverage(), 0 ), " Lots: ", DoubleToStr( lotSize, 2 ), ", \n" ); 
      display = StringConcatenate( display, "  Avg. Spread: ", DoubleToStr( avgSpread / _Point, 0 ), " of ", MaxSpread, ", \n" ); 
      display = StringConcatenate( display, "  Commission: ", DoubleToStr( commissionPoints / _Point, 0 ), " \n" ); 
      display = StringConcatenate( display, "  GMT Now: ", niceHour( _GMT ), " \n" ); 
      display = StringConcatenate( display, " ----------------------------------------\n" );
      display = StringConcatenate( display, "  Set: ", _TradeComment, " \n" ); 
      display = StringConcatenate( display, " ----------------------------------------\n" );    
      Comment( display ); 
  }
}
 

Please explain in detail your issue. We can't read your mind.

And please use the MetaEditor Styler to "style" your code, so that it becomes more readable.

Also, is this ChatGPT generated code? If so, please stop using it.

 
Code debugging - Developing programs - MetaEditor Help
  • www.metatrader5.com
MetaEditor has a built-in debugger allowing you to check a program execution step by step (by individual functions). Place breakpoints in the code...
 
Carl Schreiber #: If your code doesn't do what it should use the debugger to find out where, why and when it happens and what variable causing this:

The user will not be able to debug because it will not even compile ...

void OnTick()
int OnTick()
{

That is why I asked if this was ChatGPT code.

 
Fernando Carreiro #:

The user will not be able to debug because it will not even compile ...

That is why I asked if this was ChatGPT code.

You are right such people can't even react to the error information with line and character number of the compiler :(
 
  1.    currentSpread = NormalizeDouble(_Ask - _Bid, _Digits); 

    Do not post code that will not even compile. No such variables.

  2. Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

  3. Stop using ChatGPT.
              Help needed to debug and fix an AI EA - Trading Systems - MQL5 programming forum #2 (2023)

       int bkrH = TimeHour(TimeCurrent());
    no such function in MQL5
    switch ( OrderType() ) {
    case OP_BUYSTOP:
    MQL4 code
 
Yeah, up to Half of it is gotten based on instructions from ChatGPT, I was using it to learn mql5, I think that is where the problem is from.
Let me scratch it.
 
Peinjo #:
Yeah, up to Half of it is gotten based on instructions from ChatGPT, I was using it to learn mql5, I think that is where the problem is from.
Let me scratch it.

Searching is the better AI - the code is working!

Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5!

 
Carl Schreiber #:

Searching is the better AI - the code is working!

Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5!

Thank you.

I am trying to learn mql4/mql5. I have this idea in my mind but it is really complicated and I do not know if it is possible to be implemented so I want to learn the language and see

Reason: