Lizwe s ea mandela

Tarea técnica


#property copyright "Custom XAUUSD EA"
#property version   "1.00"
#property strict
#property description "XAUUSD Aggressive Controlled Growth EA"

#include <Trade/Trade.mqh>

CTrade trade;

//==================================================
// USER SETTINGS
//==================================================

input group "=== GENERAL SETTINGS ==="
input string TradeSymbol       = "XAUUSD";
input ENUM_TIMEFRAMES EntryTF  = PERIOD_M15;
input ENUM_TIMEFRAMES TrendTF  = PERIOD_H1;
input ulong MagicNumber        = 20261114;
input int MaxDeviationPoints   = 30;

input group "=== RISK MANAGEMENT ==="
input double RiskPercent       = 1.5;
input double DailyLossLimit    = 4.0;
input int MaxTradesPerDay      = 3;
input int MaxOpenPositions     = 1;

input group "=== STRATEGY SETTINGS ==="
input int FastEMA              = 20;
input int SlowEMA              = 50;
input int TrendEMA             = 200;
input int RSIPeriod            = 14;
input int ATRPeriod            = 14;
input double ATR_Stop_Mult     = 2.0;
input double RewardRatio       = 2.0;
input double RSI_Buy_Level     = 52.0;
input double RSI_Sell_Level    = 48.0;

input group "=== TRADE PROTECTION ==="
input double MaxSpreadPrice    = 0.60;
input double BreakEvenAtR      = 1.0;
input double TrailAtR          = 1.5;
input double TrailATRMult      = 1.5;

//==================================================
// GLOBAL VARIABLES
//==================================================

int fastHandle;
int slowHandle;
int trendHandle;
int rsiHandle;
int atrHandle;

datetime lastBarTime = 0;

string dailyVariable;

//==================================================
// INITIALIZATION
//==================================================

int OnInit()
{
   if(RiskPercent <= 0 || RiskPercent > 5 ||
      DailyLossLimit <= 0 ||
      MaxTradesPerDay < 1 ||
      MaxOpenPositions < 1 ||
      ATR_Stop_Mult <= 0 ||
      RewardRatio <= 0)
   {
      Print("Invalid EA input settings.");
      return INIT_PARAMETERS_INCORRECT;
   }

   string symbol = _Symbol;
   StringToUpper(symbol);

   if(StringFind(symbol, "XAU") < 0 &&
      StringFind(symbol, "GOLD") < 0)
   {
      Print("Attach this EA to a Gold chart.");
      return INIT_FAILED;
   }

   fastHandle = iMA(_Symbol, EntryTF,
                    FastEMA, 0, MODE_EMA, PRICE_CLOSE);

   slowHandle = iMA(_Symbol, EntryTF,
                    SlowEMA, 0, MODE_EMA, PRICE_CLOSE);

   trendHandle = iMA(_Symbol, TrendTF,
                     TrendEMA, 0, MODE_EMA, PRICE_CLOSE);

   rsiHandle = iRSI(_Symbol, EntryTF,
                    RSIPeriod, PRICE_CLOSE);

   atrHandle = iATR(_Symbol, EntryTF, ATRPeriod);

   if(fastHandle == INVALID_HANDLE ||
      slowHandle == INVALID_HANDLE ||
      trendHandle == INVALID_HANDLE ||
      rsiHandle == INVALID_HANDLE ||
      atrHandle == INVALID_HANDLE)
   {
      Print("Indicator initialization failed.");
      return INIT_FAILED;
   }

   trade.SetExpertMagicNumber(MagicNumber);
   trade.SetDeviationInPoints(MaxDeviationPoints);
   trade.SetTypeFillingBySymbol(_Symbol);

   Print("XAUUSD EA successfully initialized.");

   return INIT_SUCCEEDED;
}

//==================================================
// RELEASE INDICATORS
//==================================================

void OnDeinit(const int reason)
{
   IndicatorRelease(fastHandle);
   IndicatorRelease(slowHandle);
   IndicatorRelease(trendHandle);
   IndicatorRelease(rsiHandle);
   IndicatorRelease(atrHandle);
}

//==================================================
// GET INDICATOR VALUE
//==================================================

double GetValue(int handle, int shift)
{
   double buffer[];

   ArraySetAsSeries(buffer, true);

   if(CopyBuffer(handle, 0, shift, 1, buffer) != 1)
      return EMPTY_VALUE;

   return buffer[0];
}

//==================================================
// DAILY EQUITY TRACKING
//==================================================

string GetDailyKey()
{
   MqlDateTime dt;
   TimeToStruct(TimeCurrent(), dt);

   return StringFormat("AGX_%I64d_%04d%02d%02d",
                       AccountInfoInteger(ACCOUNT_LOGIN),
                       dt.year, dt.mon, dt.day);
}

double GetDayStartEquity()
{
   string key = GetDailyKey();

   if(!GlobalVariableCheck(key))
   {
      GlobalVariableSet(key, AccountInfoDouble(ACCOUNT_EQUITY));
   }

   return GlobalVariableGet(key);
}

//==================================================
// DAILY LOSS PROTECTION
//==================================================

bool DailyLossAllowed()
{
   double startingEquity = GetDayStartEquity();

   if(startingEquity <= 0)
      return false;

   double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);

   double lossPercent =
      ((startingEquity - currentEquity) /
       startingEquity) * 100.0;

   if(lossPercent >= DailyLossLimit)
   {
      Print("Daily loss limit reached. Trading stopped.");
      return false;
   }

   return true;
}

//==================================================
// COUNT TODAY'S ENTRIES
//==================================================

int TradesToday()
{
   MqlDateTime dt;
   TimeToStruct(TimeCurrent(), dt);

   dt.hour = 0;
   dt.min  = 0;
   dt.sec  = 0;

   datetime startTime = StructToTime(dt);

   if(!HistorySelect(startTime, TimeCurrent()))
      return 0;

   int count = 0;

   for(int i = 0; i < HistoryDealsTotal(); i++)
   {
      ulong ticket = HistoryDealGetTicket(i);

      if(ticket == 0)
         continue;

      if(HistoryDealGetString(ticket, DEAL_SYMBOL) != _Symbol)
         continue;

      if(HistoryDealGetInteger(ticket, DEAL_MAGIC) !=
         (long)MagicNumber)
         continue;

      ENUM_DEAL_ENTRY entry =
         (ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY);

      if(entry == DEAL_ENTRY_IN || entry == DEAL_ENTRY_INOUT)
         count++;
   }

   return count;
}

//==================================================
// COUNT OPEN EA POSITIONS
//==================================================

int OpenPositions()
{
   int count = 0;

   for(int i = 0; i < PositionsTotal(); i++)
   {
      ulong ticket = PositionGetTicket(i);

      if(ticket == 0)
         continue;

      if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
         PositionGetInteger(POSITION_MAGIC) ==
         (long)MagicNumber)
      {
         count++;
      }
   }

   return count;
}

//==================================================
// SPREAD PROTECTION
//==================================================

bool SpreadAllowed()
{
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(ask <= 0 || bid <= 0)
      return false;

   return (ask - bid) <= MaxSpreadPrice;
}

//==================================================
// CALCULATE LOT SIZE
//==================================================

double CalculateLotSize(ENUM_ORDER_TYPE orderType,
                        double entryPrice,
                        double stopPrice)
{
   double equity = AccountInfoDouble(ACCOUNT_EQUITY);

   double riskMoney = equity * RiskPercent / 100.0;

   double profitForOneLot = 0;

   if(!OrderCalcProfit(orderType,
                       _Symbol,
                       1.0,
                       entryPrice,
                       stopPrice,
                       profitForOneLot))
   {
      Print("Could not calculate position risk.");
      return 0;
   }

   double lossForOneLot = MathAbs(profitForOneLot);

   if(lossForOneLot <= 0)
      return 0;

   double rawLots = riskMoney / lossForOneLot;

   double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);

   if(lotStep <= 0 || rawLots < minLot)
   {
      Print("Risk-based lot size is below broker minimum.");
      return 0;
   }

   double lots = MathFloor(rawLots / lotStep) * lotStep;

   lots = MathMin(lots, maxLot);

   int digits = 0;
   double step = lotStep;

   while(step < 1.0 && digits < 8)
   {
      step *= 10.0;
      digits++;
   }

   return NormalizeDouble(lots, digits);
}

//==================================================
// CHECK FOR NEW CANDLE
//==================================================

bool IsNewBar()
{
   datetime currentBar = iTime(_Symbol, EntryTF, 0);

   if(currentBar == 0)
      return false;

   if(currentBar != lastBarTime)
   {
      lastBarTime = currentBar;
      return true;
   }

   return false;
}

//==================================================
// BUY SIGNAL
//==================================================

bool BuySignal()
{
   double fast1 = GetValue(fastHandle, 1);
   double fast2 = GetValue(fastHandle, 2);
   double slow1 = GetValue(slowHandle, 1);

   double trend = GetValue(trendHandle, 1);
   double rsi   = GetValue(rsiHandle, 1);

   if(fast1 == EMPTY_VALUE ||
      fast2 == EMPTY_VALUE ||
      slow1 == EMPTY_VALUE ||
      trend == EMPTY_VALUE ||
      rsi == EMPTY_VALUE)
      return false;

   double close1 = iClose(_Symbol, EntryTF, 1);
   double close2 = iClose(_Symbol, EntryTF, 2);

   double trendClose = iClose(_Symbol, TrendTF, 1);

   bool bullishTrend = trendClose > trend;

   bool bullishMomentum = fast1 > slow1;

   bool pullbackRecovery =
      close2 <= fast2 && close1 > fast1;

   bool rsiConfirmation = rsi >= RSI_Buy_Level;

   return bullishTrend &&
          bullishMomentum &&
          pullbackRecovery &&
          rsiConfirmation;
}

//==================================================
// SELL SIGNAL
//==================================================

bool SellSignal()
{
   double fast1 = GetValue(fastHandle, 1);
   double fast2 = GetValue(fastHandle, 2);
   double slow1 = GetValue(slowHandle, 1);

   double trend = GetValue(trendHandle, 1);
   double rsi   = GetValue(rsiHandle, 1);

   if(fast1 == EMPTY_VALUE ||
      fast2 == EMPTY_VALUE ||
      slow1 == EMPTY_VALUE ||
      trend == EMPTY_VALUE ||
      rsi == EMPTY_VALUE)
      return false;

   double close1 = iClose(_Symbol, EntryTF, 1);
   double close2 = iClose(_Symbol, EntryTF, 2);

   double trendClose = iClose(_Symbol, TrendTF, 1);

   bool bearishTrend = trendClose < trend;

   bool bearishMomentum = fast1 < slow1;

   bool pullbackRecovery =
      close2 >= fast2 && close1 < fast1;

   bool rsiConfirmation = rsi <= RSI_Sell_Level;

   return bearishTrend &&
          bearishMomentum &&
          pullbackRecovery &&
          rsiConfirmation;
}

//==================================================
// OPEN BUY TRADE
//==================================================

void OpenBuy()
{
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   double atr = GetValue(atrHandle, 1);

   if(atr == EMPTY_VALUE || atr <= 0)
      return;

   int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);

   double sl = NormalizeDouble(
      ask - atr * ATR_Stop_Mult, digits);

   double tp = NormalizeDouble(
      ask + (ask - sl) * RewardRatio, digits);

   double lots = CalculateLotSize(ORDER_TYPE_BUY, ask, sl);

   if(lots <= 0)
      return;

   if(!trade.Buy(lots, _Symbol, 0, sl, tp, "XAUUSD EA BUY"))
   {
      Print("BUY failed: ", trade.ResultRetcodeDescription());
   }
   else
   {
      Print("BUY request sent. Volume: ", lots);
   }
}

//==================================================
// OPEN SELL TRADE
//==================================================

void OpenSell()
{
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   double atr = GetValue(atrHandle, 1);

   if(atr == EMPTY_VALUE || atr <= 0)
      return;

   int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);

   double sl = NormalizeDouble(
      bid + atr * ATR_Stop_Mult, digits);

   double tp = NormalizeDouble(
      bid - (sl - bid) * RewardRatio, digits);

   double lots = CalculateLotSize(ORDER_TYPE_SELL, bid, sl);

   if(lots <= 0)
      return;

   if(!trade.Sell(lots, _Symbol, 0, sl, tp, "XAUUSD EA SELL"))
   {
      Print("SELL failed: ", trade.ResultRetcodeDescription());
   }
   else
   {
      Print("SELL request sent. Volume: ", lots);
   }
}

//==================================================
// BREAK-EVEN AND TRAILING STOP
//==================================================

void ManagePositions()
{
   double atr = GetValue(atrHandle, 1);

   if(atr == EMPTY_VALUE || atr <= 0)
      return;

   int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);

   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);

      if(ticket == 0)
         continue;

      if(PositionGetString(POSITION_SYMBOL) != _Symbol ||
         PositionGetInteger(POSITION_MAGIC) != (long)MagicNumber)
         continue;

      ENUM_POSITION_TYPE type =
         (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);

      double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
      double currentSL = PositionGetDouble(POSITION_SL);
      double currentTP = PositionGetDouble(POSITION_TP);

      double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

      // Recover original risk distance from the 1:2 TP.
      double initialRisk = MathAbs(currentTP - openPrice) /
                           RewardRatio;

      if(initialRisk <= 0)
         continue;

      double profitDistance = 0;
      double newSL = currentSL;

      if(type == POSITION_TYPE_BUY)
      {
         profitDistance = bid - openPrice;

         if(profitDistance >= initialRisk * BreakEvenAtR)
         {
            double be = openPrice;

            if(currentSL == 0 || be > newSL)
               newSL = be;
         }

         if(profitDistance >= initialRisk * TrailAtR)
         {
            double trailing = bid - atr * TrailATRMult;

            if(trailing > newSL)
               newSL = trailing;
         }

         if(newSL > currentSL && newSL < bid)
         {
            newSL = NormalizeDouble(newSL, digits);

            if(!trade.PositionModify(ticket, newSL, currentTP))
               Print("BUY stop modification failed: ",
                     trade.ResultRetcodeDescription());
         }
      }
      else if(type == POSITION_TYPE_SELL)
      {
         profitDistance = openPrice - ask;

         if(profitDistance >= initialRisk * BreakEvenAtR)
         {
            double be = openPrice;

            if(currentSL == 0 || be < newSL)
               newSL = be;
         }

         if(profitDistance >= initialRisk * TrailAtR)
         {
            double trailing = ask + atr * TrailATRMult;

            if(newSL == 0 || trailing < newSL)
               newSL = trailing;
         }

         if((currentSL == 0 || newSL < currentSL) && newSL > ask)
         {
            newSL = NormalizeDouble(newSL, digits);

            if(!trade.PositionModify(ticket, newSL, currentTP))
               Print("SELL stop modification failed: ",
                     trade.ResultRetcodeDescription());
         }
      }
   }
}

//==================================================
// MAIN EA ENGINE
//==================================================

void OnTick()
{
   // Manage existing trades on every tick.
   ManagePositions();

   // Only evaluate new entries at a new M15 candle.
   if(!IsNewBar())
      return;

   if(!DailyLossAllowed())
      return;

   if(!SpreadAllowed())
      return;

   if(TradesToday() >= MaxTradesPerDay)
      return;

   if(OpenPositions() >= MaxOpenPositions)
      return;

   // Avoid entries when indicators are not ready.
   if(BarsCalculated(fastHandle) < 250 ||
      BarsCalculated(slowHandle) < 250 ||
      BarsCalculated(trendHandle) < 250 ||
      BarsCalculated(rsiHandle) < 50 ||
      BarsCalculated(atrHandle) < 50)
      return;

   if(BuySignal())
   {
      OpenBuy();
   }
   else if(SellSignal())
   {
      OpenSell();
   }
}

Han respondido

1
Desarrollador 1
Evaluación
(1)
Proyectos
2
0%
Arbitraje
0
Caducado
0
Libre
Ha publicado: 15 ejemplos
2
Desarrollador 2
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Trabaja
3
Desarrollador 3
Evaluación
(7)
Proyectos
10
70%
Arbitraje
0
Caducado
0
Trabaja
Ha publicado: 1 artículo, 2 ejemplos
4
Desarrollador 4
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Libre
5
Desarrollador 5
Evaluación
(24)
Proyectos
35
40%
Arbitraje
9
22% / 33%
Caducado
5
14%
Trabajando
Ha publicado: 8 artículos, 35 ejemplos
6
Desarrollador 6
Evaluación
Proyectos
1
0%
Arbitraje
0
Caducado
0
Libre
Ha publicado: 4 ejemplos
7
Desarrollador 7
Evaluación
(29)
Proyectos
36
39%
Arbitraje
0
Caducado
2
6%
Libre
8
Desarrollador 8
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Libre
Ha publicado: 3 ejemplos
9
Desarrollador 9
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Libre
10
Desarrollador 10
Evaluación
(1)
Proyectos
1
0%
Arbitraje
0
Caducado
0
Libre
Ha publicado: 4 ejemplos
11
Desarrollador 11
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Libre
12
Desarrollador 12
Evaluación
(1)
Proyectos
1
100%
Arbitraje
0
Caducado
0
Libre
Ha publicado: 7 ejemplos
13
Desarrollador 13
Evaluación
(1)
Proyectos
1
100%
Arbitraje
0
Caducado
0
Libre
14
Desarrollador 14
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Libre
15
Desarrollador 15
Evaluación
(10)
Proyectos
12
33%
Arbitraje
0
Caducado
2
17%
Trabaja
Ha publicado: 1 ejemplo
16
Desarrollador 16
Evaluación
(2)
Proyectos
2
0%
Arbitraje
1
0% / 100%
Caducado
0
Libre
17
Desarrollador 17
Evaluación
(47)
Proyectos
62
55%
Arbitraje
7
86% / 0%
Caducado
2
3%
Libre
Solicitudes similares
Hello, I need an MQL5 Expert Advisor for MetaTrader 5. STRATEGY: Pair: XAUUSD / EURUSD Timeframe: M5 and M15 (selectable) 1. Wait for a strong rejection wick at Support / Resistance or Supply / Demand zone. 2. Wait for a Fair Value Gap (FVG) in the same direction. 3. Enter on FVG retest with confirmation candle close. 4. Only 1 trade at a time, no martingale, no grid. RISK MANAGEMENT: - Lot: Fixed lot or % Risk
Metafix 50 - 200 USD
Here is a professional specification you can send directly to your developer. # Project Requirements Specification: MetaTrader 5 Trading Robot Development ### 1. Project Overview I want to develop an automated Forex trading robot (Expert Advisor) for MetaTrader 5 (MT5). The robot should analyse the financial markets, identify trading opportunities, and execute trades automatically based on predefined strategies. ###
Overview: Build an MT5 Expert Advisor that receives webhook alerts from TradingView (RayAlgo indicator) across three timeframes ( H1, M5, M1 ) for XAUUSD and executes a dual-position strategy when all three conditions align, including strict FTMO server-request limits and automated pre-market-close trade closures. 1. Webhook Receiver & Multi-Timeframe State Logic: H1 Bias State: Updates to BULLISH or BEARISH upon
I am looking for an experienced trading software developer interested in building a long-term working relationship. Im a professional Trader, Coach and Mentor, I work with traders and Student who require customized trading solutions, including automated trading bots, Expert Advisors, custom indicators, trading strategies and other algorithmic trading tools. I am looking for a technically skilled developer who can
Salman serhal 30 - 100 USD
MT5 ICT XAUUSD Sell-Only Trading Robot with Fibonacci Confirmation I am looking for an experienced MQL5 developer to create a custom Expert Advisor (EA) for MetaTrader 5, specifically for trading Gold (XAUUSD). 1. Trading Strategy The robot must use the ICT trading methodology and focus on SELL trades only. The strategy should include: * Identify important resistance and premium zones. * Use Fibonacci retracement
Objective: I am looking for an experienced MQL5 quantitative developer to code an Expert Advisor (EA) from scratch based on a fully defined, rule-based strategy, and then rigorously validate, optimize, and stress-test it before I deploy it on a live VPS environment. Note: The exact mathematical rules, indicator names, and chart screenshots will be shared privately with shortlisted candidates. Strategy Overview
JOB SPECIFICATION: Fully Automated ES/MES 5-Minute NY Opening Range Breakout EA 1. Project objective I am looking for an experienced trading algo developer to build a fully automated trading bot (EA) based on my specific 5-minute New York Opening Range Breakout strategy. The EA must identify setups, confirm breakouts, identify retests, confirm continuation, execute trades, calculate position size, place stop-loss and
Custom MT5 Expert Advisor – Developer Specification 1. Project Objective Develop a fully autonomous, custom MetaTrader 5 Expert Advisor (EA) using native MQL5. The EA must independently analyze financial markets, generate its own trading signals, evaluate opportunities, execute trades, and manage open positions without requiring an external signal provider, another trading bot, or manual intervention. The EA must
​​ Title: ​Create a Combined Indicator from 3 EX4 Indicators + Fully Automatic Trading EA (MT4) ​ Description: ​Hello, ​I need an experienced MQL4 developer to build a custom trading system based on 3 existing .ex4 indicators. ​ Project Requirements: ​ Combined Custom Indicator: ​Read and merge signals from 3 specified .ex4 indicators via buffer reading (iCustom). ​Generate a consolidated BUY or SELL arrow/signal
نازدك 30+ USD
Specify your Requirements Specification here point by point. Try to describe your requirements briefly and clearly, so that your potential developer is able to correctly assess its complexity and cost, as well as the required execution time. A bad or too generic description will result in your order being ignored, or you will spend a lot of time negotiating the details with each applicant. Remember: It is better to

Información sobre el proyecto

Presupuesto
40 - 200 USD

Cliente

Encargos realizados1
Número de arbitrajes0