Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

I will provide you an EA which works in meta trader 5…

  1. User

    I will provide you an EA which works in meta trader 5 //+------------------------------------------------------------------+ //| ProjectName | //| Copyright 2020, CompanyName | //| http://www.companyname.net | //+------------------------------------------------------------------+

    #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00"

    #include <Trade/Trade.mqh>

    CTrade trade; CPositionInfo pos; COrderInfo ord;

    input group "=== Trading Inputs ==="

      input double        RiskPercent  =  3;
      input int           Tppoints     =  200;
      input  int           Slpoints    =  200;
      input int       TslTriggerPoints = 15;
      input int            Tslpoints   = 10;
      input ENUM_TIMEFRAMES  Timeframe = PERIOD_CURRENT;
      input int            InpMagic    = 298347;
      input string         TradeComment = "Scalping Robot";
      
      enum StartHour  {Inactive=0, _0100=1, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23 };
      
      
      input StartHour SHInput =0;
      
      enum EndtHour  {Inactive=0, _0100=1, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23 };
      
      input EndtHour EHInput=0;
      
      int SHchoice;
      int EHchoice;
      
      int            BarsN = 5;
      int            ExpirationBars = 100;
      int            OrderDistPoints = 100;
    

    int OnInit() { trade.SetExpertMagicNumber(InpMagic); ChartSetInteger(0, CHART_SHOW_GRID, false);

    return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) {

    } void OnTick(){

      TrailStop();   
      if(!IsNewBar()) return;
      
      MqlDateTime time;
      TimeToStruct(TimeCurrent(),time);
      int Hournow = time.hour;
      
      SHchoice = SHInput;
      EHchoice = EHInput;
      
      if(Hournow<SHchoice){ CloseAllOrders(); return;}
      if(Hournow>=EHchoice && EHchoice!=0){ CloseAllOrders(); return;}   
      
      int BuyTotal = 0;
      int SellTotal = 0;
      
      
      for(int i=PositionsTotal()-1; i>=0; i--){
         
         pos.SelectByIndex(i);
         if(pos.PositionType()==POSITION_TYPE_BUY && pos.Symbol() == _Symbol && pos.Magic()==InpMagic)  BuyTotal++;
         if(pos.PositionType()==POSITION_TYPE_SELL && pos.Symbol() == _Symbol && pos.Magic()==InpMagic) SellTotal++;
       }
      
      
      
      for(int i=OrdersTotal()-1; i>=0; i--){
         
         ord.SelectByIndex(i);
         if(ord.OrderType()==ORDER_TYPE_BUY_STOP && ord.Symbol() == _Symbol && ord.Magic()==InpMagic)  BuyTotal++;
         if(ord.OrderType()==ORDER_TYPE_SELL_STOP && ord.Symbol() == _Symbol && ord.Magic()==InpMagic) SellTotal++;
      
      
      } 
      
      if(BuyTotal<=0){
      double high = findHigh();
      if(high >0){
         SendBuyOrder(high);
         }
     }
       if(SellTotal<=0){
      double low = findlow();
      if(low >0){
         SendSellOrder(low);
         }
     }
    

    }

    //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double findHigh() {

    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() {

    double lowestLow = DBL_MAX;

    for(int i=0; i < 200;i++) { double low = iLow(_Symbol,Timeframe,i); if(i > BarsN && iLowest(_Symbol, Timeframe, MODE_HIGH,BarsN*2+1,i-5) == i) { if(low < lowestLow) { return low; } } lowestLow = MathMin(low,lowestLow); } return -1; }

    //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool IsNewBar() { static datetime previousTime = 0; datetime currentTime = iTime(_Symbol, Timeframe,0); if(previousTime!=currentTime) { previousTime = currentTime; return true; } return false; }

    //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void SendBuyOrder(double entry) { double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);

    if(ask > entry - OrderDistPoints * _Point) return;

    double tp = entry + Tppoints * _Point; double sl = entry - Slpoints * _Point;

    double lots = 0.01; if(RiskPercent >0)lots = calcLots(entry - sl);

    datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);

    trade.BuyStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);     
    

    }

    void SendSellOrder(double entry) {

    double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);

    if(bid < entry + OrderDistPoints * _Point) return;

    double tp = entry - Tppoints * _Point; double sl = entry + Slpoints * _Point;

    double lots = 0.01; if(RiskPercent >0)lots = calcLots(sl - entry);

    datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);

    trade.SellStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);
    

    } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ 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; }

    void CloseAllOrders(){

    for(int i=OrdersTotal()-1;i>0;i--){ ord.SelectByIndex(i); ulong ticket = ord.Ticket(); if(ord.Symbol() == _Symbol && ord.Magic() == InpMagic){ trade.OrderDelete(ticket); }

    }

    }

    void TrailStop(){

      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(pos.SelectByIndex(i)){
            ulong Ticket = pos.Ticket();
               
               if(pos.Magic()==InpMagic && pos.Symbol()==_Symbol){
               
                  if (pos.PositionType() == POSITION_TYPE_BUY){           
                     if(bid-pos.PriceOpen()>TslTriggerPoints*_Point){
                        tp = pos.TakeProfit();
                        sl = bid- (Tslpoints * _Point);
                        
                        if(sl> pos.StopLoss() && sl!=0){
                           trade.PositionModify(Ticket,sl,tp);                                 
                  }
               }
            }
             else if (pos.PositionType() == POSITION_TYPE_SELL){
                     if(ask+(TslTriggerPoints*_Point)<pos.PriceOpen()){
                        tp = pos.TakeProfit();
                        sl = ask + (Tslpoints * _Point);
                        
                        if(sl < pos.StopLoss() && sl!=0){
                         trade.PositionModify(Ticket,sl,tp);                                
                     }
                  }                            
               }
            }    
         }
      }
    

    }

    now do the following Begin a theoretical backtest of the EA (Expert Advisor) using real tick data sourced from one of the following providers: Tickstory, Quant DataManager, Tick Data Suite. This analysis will occur over the period of 1st January 2025 to 20th June 2025, focusing on the currency pairs XAUUSD and EURUSD.

    Objective:

    • Optimize input settings to make the EA profitable and enable it to meet the Stellar One challenge of FundedNext.
    • Implement and utilize a 200 EMA filter within the analysis, without adding any additional indicators or filters.

    Backtesting Specifications:

    • Perform tests on different time frames: 5-minute, 15-minute, 1-hour, and 4-hour charts.
    • Optimize input settings according to each time frame and compile the best inputs for every time frame.
    • Calculate and provide the win rate, net profit, and Sharpe ratio for each optimized setting.

    Process outline: Step 1 - Acquire real tick data from the specified providers for the backtest duration. Step 2 - Implement the 200 EMA filter in the EA code for analysis. Step 3 - Perform theoretical backtests on XAUUSD and EURUSD for each specified time frame. Step 4 - Experiment with various input settings to optimize the EA. Step 5 - Compile results including best inputs, win rate, net profit, and Sharpe ratio for each time frame.

    Based on this framework, please proceed with querying data, testing settings, analyzing results, and iterating optimizations as needed.

  2. Assistant

    You have asked for a comprehensive theoretical backtest plan and results based on real tick data, with optimization of your EA that trades with stop orders on XAUUSD and EURUSD for the first half of 2025, employing a 200 EMA filter (no additional indicators) and reports performance metrics like win rate, net profit, and Sharpe ratio on multiple time frames.


    Important Notes First:

    • I cannot directly retrieve or run real tick data nor perform real backtests or optimizations in MT5 or external platforms. Instead, I will:
      • Guide you step-by-step on how to set up everything based on your EA code.
      • Provide code modifications to implement the 200 EMA filter.
      • Explain how to perform the backtests with your data sources.
      • Recommend optimization setups.
      • Describe how to calculate metrics (win rate, net profit, Sharpe) from results.
      • Give example hypothetical outcomes and analysis for your info.

    Step 1: Acquire Tick Data (User Action Required)

    1. Get real tick data for XAUUSD and EURUSD from:

    2. Download tick data for the period 1 Jan 2025 to 20 Jun 2025.

    3. Import this tick data into MetaTrader 5’s History Center:

      • Go to Tools -> History Center (F2)
      • Find XAUUSD and EURUSD
      • Import tick data for each timeframe desired: M5, M15, H1, H4
      • Make sure your data range is accurate for your test.

    Step 2: Implement the 200 EMA Filter in Your EA Code

    The 200 EMA filter will be a condition where trades are only taken if:

    • For Buy entries: Price is above the 200 EMA.
    • For Sell entries: Price is below the 200 EMA.

    No extra indicators, so the EMA must be computed within your EA code using native MQL5 functions.

    Code snippet to add at the top (after includes):

    //--- Global variables for EMA
    int emaPeriod = 200;
    
    //--- Helper function to calculate EMA price
    double iEMAValue(ENUM_TIMEFRAMES timeframe, int shift=0)
    {
        return iMA(_Symbol, timeframe, emaPeriod, 0, MODE_EMA, PRICE_CLOSE, shift);
    }
    

    Modify your OnTick() order sending logic to add EMA check:

    Locate your order send code here:

    if(BuyTotal<=0){
        double high = findHigh();
        if(high >0){
           SendBuyOrder(high);
        }
    }
    if(SellTotal<=0){
        double low = findlow();
        if(low >0){
           SendSellOrder(low);
        }
    }
    

    Change it to include the condition:

    double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID); // or Ask for buy?
    
    double emaCurrent = iEMAValue(Timeframe, 0);
    
    if(BuyTotal<=0){
        double high = findHigh();
        if(high > 0 && currentPrice > emaCurrent)  // Price above EMA for buys
        {
           SendBuyOrder(high);
        }
    }
    if(SellTotal<=0){
        double low = findlow();
        if(low >0 && currentPrice < emaCurrent)  // Price below EMA for sells
        {
           SendSellOrder(low);
        }
    }
    

    That filters trades to only trade with price on the "correct" side of 200 EMA.


    Step 3: Backtesting Setup in MetaTrader 5 Strategy Tester

    • Open MetaTrader 5.
    • Open Strategy Tester (Ctrl+R).
    • Select your EA with EMA changes.
    • Symbol: XAUUSD or EURUSD.
    • Period: from 01/01/2025 to 20/06/2025.
    • Use tick data (select your imported tick data from Step 1).
    • Test each Timeframe: M5, M15, H1, H4 — set timeframe in EA input / or chart timeframe.
    • Enable optimization.

    Step 4: Optimization of Input Settings

    Your key input parameters to optimize include (from your EA):

    • RiskPercent (e.g. 0.5 to 5%)
    • Tppoints (e.g. 50 to 400 points)
    • Slpoints (e.g. 50 to 400 points)
    • TslTriggerPoints (e.g. 5 to 50)
    • Tslpoints (e.g. 5 to 30)
    • BarsN (e.g. 1 to 10) — impacts high/low detection
    • OrderDistPoints (e.g. 50 to 200)

    You may keep some inputs fixed (like Timeframe per test), and optimize the rest.

    Optimization method:

    • Set reasonable ranges with steps in Strategy Tester:
      • Example: RiskPercent: 0.5 to 4.0 step 0.5
      • Tppoints: 100 to 400 step 50
      • Slpoints: 100 to 400 step 50
      • TslTriggerPoints: 10 to 50 step 5
      • Others similarly.
    • Focus on realistic ranges to limit optimization time.
    • For each timeframe, run full optimization for both XAUUSD and EURUSD separately.

    Step 5: Analyze Results

    From MT5 Strategy Tester optimization report:

    • Find parameter sets with best net profit and acceptable max drawdown.
    • Extract for each best run:
      • Win Rate = (Trades Won / Total Trades)
      • Net Profit (total profit amount)
      • Sharpe Ratio (standard in MT5 report or compute externally):

    How to calculate Sharpe Ratio:

    Sharpe Ratio ~ (AverageReturn - RiskFreeRate) / StdDevReturn

    In backtest, usually RiskFreeRate ~0.

    • Export results (to CSV).
    • Calculate daily/weekly returns from equity curve.
    • Compute average return and standard deviation of returns.
    • Compute Sharpe = AvgReturn / StdDevReturn.

    Hypothetical Result Summary Table Format

    SymbolTimeframeRiskPercentTppointsSlpointsTslTriggerTslpointsBarsNOrderDistWin RateNet Profit (USD)Sharpe Ratio
    XAUUSDM52.02001801510510056%45001.3
    XAUUSDM151.5150150201248058%35001.1
    EURUSDH11.0100120151066052%21000.95
    EURUSDH40.580100251575050%15000.85

    Final Notes and Recommendations

    • The 200 EMA filter generally reduces false entries.
    • Risk management via dynamic lot calculation based on stop loss keeps drawdown controlled.
    • For FundedNext's Stellar One challenge, confirm position sizing and drawdown limits first.
    • After theoretical optimization, do forward testing with live (or demo) on small real accounts before funding challenge entry.
    • Sharpe ratio above 1 is generally favorable in FX scalping.
    • Win rates in 50-60% with positive expectancy can be profitable.

    If you want, I can help you:

    • Integrate the EMA filter with full updated EA code.
    • Write a performance analysis script to parse MT5 backtest logs.
    • Or provide detailed optimization parameter files/templates for your Strategy Tester.

    Let me know how you want to proceed with code updates or tools!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.