← К каталогу
Исходный код · ID 4367

XAUUSD Gold Perfect

xauusd_gold_perfect.mq4

Похожие материалы по тегам

tm sniper pro.pineTradingView · 2 общих теговsniper pro.mq5MQL5 / MetaTrader 5 · 2 общих теговpro +.pineTradingView · 2 общих теговofada_gold_trader_v230.mq5MQL5 / MetaTrader 5 · 2 общих теговmulti strategy algo combined by enigma mode.pineTradingView · 2 общих теговkirin ea.mq4MQL4 / MetaTrader 4 · 2 общих тегов
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

XAUUSD Gold Perfect — торговый советник для MetaTrader 4 на языке MQL4, рассчитанный на инструменты с XAU или GOLD в названии. Анализирует технические индикаторы, формирует сигналы покупки и продажи и сопровождает открытые позиции. Названия настроек, переменных и функций, комментарии, сообщения журнала и информационная панель переведены на английский язык. Торговая логика и значения параметров сохранены.

Предусмотрены расчёт объёма позиции по заданному риску, ограничения размера лота и количества позиций, стоп-лосс и тейк-профит с учётом волатильности, перенос стопа в безубыток и трейлинг-стоп. Есть расписание по часам сервера и дням недели, ограничение максимального спреда, фильтр направления тренда, сигнальные стрелки и панель состояния. Защита по просадке учитывает общую equity счёта относительно баланса при запуске, но закрывает только позиции этого советника на текущем символе.

Особенности текущей реализации: параметры AvoidMajorNews, EnableVolumeFilter, SignalConfirmationBars и MinSpread объявлены, но не участвуют в торговых проверках. Частичное закрытие реализовано только для покупок и может повторяться на следующих тиках, пока соблюдаются условия. Защита по просадке проверяется при появлении нового бара; постоянная блокировка дальнейшей торговли после её срабатывания не предусмотрена. Перевод не устраняет эти ограничения.

При переходе со старой версии настройки с китайскими именами нужно перенести вручную: имена входных параметров изменились. Перед использованием проверьте компиляцию в своей версии MetaEditor и поведение в тестере и на демосчёте. Результаты тестирования и подтверждённая доходность к исходнику не приложены.

Получить полный код

Поиск по коду файла

#property version     "2.00"
#property strict

input group "=== Risk Management ===";
input double  RiskPercent          = 1.5;        // Risk per trade (%)
input double  MaxLots            = 5.0;        // Maximum allowed lots
input double  MinLots            = 0.01;       // Minimum allowed lots
input int     MaxOpenPositions      = 3;          // Maximum simultaneous positions
input bool    EnableEquityStop        = true;       // Enable account equity protection
input double  MaxDrawdownPercent      = 15.0;       // Maximum allowed drawdown (%)

input group "=== Technical Indicators ===";
input int     FastEMAPeriod        = 8;          // Fast EMA period
input int     MediumEMAPeriod        = 21;         // Medium EMA period
input int     SlowEMAPeriod        = 50;         // Slow EMA period
input int     TrendEMAPeriod        = 200;        // Main trend EMA period
input int     RSIPeriod    = 14;         // RSI period
input double  OverboughtLevel            = 70.0;       // RSI overbought level
input double  OversoldLevel            = 30.0;       // RSI oversold level
input int     ATRPeriod    = 14;         // ATR period (volatility)
input int     MACDFastPeriod    = 12;         // MACD fast EMA period
input int     MACDSlowPeriod    = 26;         // MACD slow EMA period
input int     MACDSignalPeriod  = 9;          // MACD signal period
input int     BollingerPeriod          = 20;         // Bollinger Bands period
input double  BollingerDeviation          = 2.0;        // Bollinger Bands standard deviation multiplier
input int     StochasticKPeriod    = 5;          // Stochastic K period
input int     StochasticDPeriod    = 3;          // Stochastic D period
input int     StochasticSlowing    = 3;          // Stochastic slowing
input int     ADXPeriod    = 14;         // ADX period
input double  MinADXStrength    = 25.0;       // Minimum ADX trend strength

input group "=== Stop Loss and Take Profit ===";
input double  StopLossATRMultiplier    = 1.5;        // Stop loss distance = ATR multiplied by this value
input double  TakeProfitATRMultiplier    = 2.5;        // Take profit distance = ATR multiplied by this value
input bool    EnableTrailingStop        = true;       // Enable trailing stop
input double  TrailingStopATRMultiplier    = 1.0;        // Trailing stop distance = ATR multiplied by this value
input bool    EnableBreakEven        = true;       // Enable break-even stop
input double  BreakEvenATRTrigger    = 1.0;        // Break-even trigger = ATR multiplied by this value
input bool    EnablePartialClose        = true;       // Enable partial closing
input double  PartialCloseRatio        = 0.5;        // Partial close ratio (0.5 means close 50 percent)
input double  PartialCloseATRTrigger    = 1.5;        // Partial close trigger = ATR multiplied by this value

input group "=== Trading Hours ===";
input bool    EnableTimeFilter        = true;       // Restrict trading hours
input int     TradingStartHour        = 7;          // Daily trading start hour (server time)
input int     TradingEndHour        = 21;         // Daily trading end hour (server time)
input bool    TradeMonday        = true;       // Allow opening trades on Monday
input bool    TradeTuesday        = true;       // Allow opening trades on Tuesday
input bool    TradeWednesday        = true;       // Allow opening trades on Wednesday
input bool    TradeThursday        = true;       // Allow opening trades on Thursday
input bool    TradeFriday        = true;       // Allow opening trades on Friday (use caution)
input bool    AvoidMajorNews    = true;       // Pause trading around major news

input group "=== Signal Filters ===";
input int     MinSignalStrength        = 3;          // Minimum allowed signal strength (1 to 5)
input bool    EnableTrendFilter        = true;       // Filter by the main trend direction
input bool    EnableVolumeFilter      = false;      // Filter by volume conditions
input int     SignalConfirmationBars       = 1;          // Number of bars required to confirm a signal
input double  MinSpread        = 0;          // Minimum allowed spread (0 means no limit)
input double  MaxSpread        = 50;         // Maximum allowed spread (points)

input group "=== Display Settings ===";
input bool    ShowInfoPanel        = true;       // Show information panel on the chart
input bool    ShowSignalArrows        = true;       // Show buy and sell signal arrows on the chart
input color   BuySignalColor        = clrDodgerBlue;  // Buy signal arrow color
input color   SellSignalColor        = clrRed;         // Sell signal arrow color
input int     MagicNumber      = 20241201;       // Unique expert advisor magic number

double atrValue;
double fastEMA;
double mediumEMA;
double slowEMA;
double trendEMA;
double rsiValue;
double macdMain;
double macdSignal;
double bollingerUpper;
double bollingerLower;
double bollingerMiddle;
double stochasticMain;
double stochasticSignal;
double adxValue;

int    signalDirection;
int    signalStrength;
bool   breakEvenTriggered[];
bool   partialCloseDone[];

datetime lastBarTime;
double   initialBalance;

int OnInit()
{
      // код доступен только после оплаты
   }

void OnDeinit(const int reason)
{
   ObjectsDeleteAll(0, "Panel_");
   Comment("");

   Print("============================================");
   Print("Gold Smart Trading EA stopped");
   Print("Final account balance: $", DoubleToString(AccountBalance(), 2));
   Print("Total account profit/loss: $", DoubleToString(AccountBalance() - initialBalance, 2));
   Print("============================================");
}

void OnTick()
{
      // код доступен только после оплаты
   }

void UpdateIndicators()
{
   int shift = 1;

   fastEMA = iMA(NULL, 0, FastEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, shift);
   mediumEMA = iMA(NULL, 0, MediumEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, shift);
   slowEMA = iMA(NULL, 0, SlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, shift);
   trendEMA = iMA(NULL, 0, TrendEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, shift);

   rsiValue     = iRSI(NULL, 0, RSIPeriod, PRICE_CLOSE, shift);
   atrValue = iATR(NULL, 0, ATRPeriod, shift);

   macdMain = iMACD(NULL, 0, MACDFastPeriod, MACDSlowPeriod, MACDSignalPeriod, PRICE_CLOSE, MODE_MAIN,   shift);
   macdSignal = iMACD(NULL, 0, MACDFastPeriod, MACDSlowPeriod, MACDSignalPeriod, PRICE_CLOSE, MODE_SIGNAL, shift);

   bollingerUpper = iBands(NULL, 0, BollingerPeriod, BollingerDeviation, 0, PRICE_CLOSE, MODE_UPPER, shift);
   bollingerLower = iBands(NULL, 0, BollingerPeriod, BollingerDeviation, 0, PRICE_CLOSE, MODE_LOWER, shift);
   bollingerMiddle = iBands(NULL, 0, BollingerPeriod, BollingerDeviation, 0, PRICE_CLOSE, MODE_MAIN,  shift);

   stochasticMain = iStochastic(NULL, 0, StochasticKPeriod, StochasticDPeriod, StochasticSlowing, MODE_SMA, 0, MODE_MAIN,   shift);
   stochasticSignal = iStochastic(NULL, 0, StochasticKPeriod, StochasticDPeriod, StochasticSlowing, MODE_SMA, 0, MODE_SIGNAL, shift);

   adxValue = iADX(NULL, 0, ADXPeriod, PRICE_CLOSE, MODE_MAIN, shift);
}

void AnalyzeMarket()
{
   signalDirection = 0;
   signalStrength = 0;

   int buyScore = 0;
   int sellScore = 0;

   double previousClose = iClose(NULL, 0, 1);
   double earlierClose = iClose(NULL, 0, 2);

   bool bullishMAAlignment = (fastEMA > mediumEMA && mediumEMA > slowEMA);
   bool bearishMAAlignment = (fastEMA < mediumEMA && mediumEMA < slowEMA);

   if(bullishMAAlignment) buyScore += 2;
   if(bearishMAAlignment) sellScore += 2;

   bool priceAboveTrend = (previousClose > trendEMA);
   bool priceBelowTrend = (previousClose < trendEMA);

   if(EnableTrendFilter)
   {
      if(priceAboveTrend && bullishMAAlignment) buyScore += 1;
      if(priceBelowTrend && bearishMAAlignment) sellScore += 1;
   }

   double previousRSI = iRSI(NULL, 0, RSIPeriod, PRICE_CLOSE, 2);

   if(rsiValue > OversoldLevel && previousRSI <= OversoldLevel)   buyScore += 2;
   if(rsiValue < OverboughtLevel && previousRSI >= OverboughtLevel) sellScore += 2;
   if(rsiValue > 50 && rsiValue < OverboughtLevel) buyScore += 1;
   if(rsiValue < 50 && rsiValue > OversoldLevel) sellScore += 1;

   double previousMACDMain = iMACD(NULL, 0, MACDFastPeriod, MACDSlowPeriod, MACDSignalPeriod, PRICE_CLOSE, MODE_MAIN,   2);
   double previousMACDSignal = iMACD(NULL, 0, MACDFastPeriod, MACDSlowPeriod, MACDSignalPeriod, PRICE_CLOSE, MODE_SIGNAL, 2);

   if(macdMain > macdSignal && previousMACDMain <= previousMACDSignal) buyScore += 2;

   if(macdMain < macdSignal && previousMACDMain >= previousMACDSignal) sellScore += 2;
   if(macdMain > 0 && macdSignal > 0) buyScore += 1;
   if(macdMain < 0 && macdSignal < 0) sellScore += 1;

   if(previousClose > bollingerLower && earlierClose <= bollingerLower) buyScore += 2;
   if(previousClose < bollingerUpper && earlierClose >= bollingerUpper) sellScore += 2;
   if(previousClose > bollingerMiddle) buyScore += 1;
   if(previousClose < bollingerMiddle) sellScore += 1;

   double previousStochasticMain = iStochastic(NULL, 0, StochasticKPeriod, StochasticDPeriod, StochasticSlowing, MODE_SMA, 0, MODE_MAIN, 2);

   if(stochasticMain > 20 && previousStochasticMain <= 20 && stochasticMain > stochasticSignal) buyScore += 1;
   if(stochasticMain < 80 && previousStochasticMain >= 80 && stochasticMain < stochasticSignal) sellScore += 1;

   bool strongTrend = (adxValue >= MinADXStrength);

   int maxPossibleScore = 12;

   if(buyScore > sellScore && buyScore >= 4)
   {
      if(!EnableTrendFilter || (EnableTrendFilter && (priceAboveTrend || bullishMAAlignment)))
      {
         signalDirection = 1;
         signalStrength = MathMin(5, (int)MathRound((double)buyScore / maxPossibleScore * 5));
         if(strongTrend) signalStrength = MathMin(5, signalStrength + 1);
      }
   }
   else if(sellScore > buyScore && sellScore >= 4)
   {
      if(!EnableTrendFilter || (EnableTrendFilter && (priceBelowTrend || bearishMAAlignment)))
      {
         signalDirection = -1;
         signalStrength = MathMin(5, (int)MathRound((double)sellScore / maxPossibleScore * 5));
         if(strongTrend) signalStrength = MathMin(5, signalStrength + 1);
      }
   }

   if(signalDirection != 0)
   {
      string signalDirectionText = (signalDirection == 1) ? "Buy (long)" : "Sell (short)";
      Print("Signal analysis | ", signalDirectionText,
            " | Strength: ", signalStrength, " / 5",
            " | Buy score: ", buyScore, " | Sell score: ", sellScore,
            " | ADX: ", DoubleToString(adxValue, 1));
   }
}

void ExecuteTrade()
{
   if(HasPositionInDirection(signalDirection)) return;

   double stopLossDistance = atrValue * StopLossATRMultiplier;
   double takeProfitDistance = atrValue * TakeProfitATRMultiplier;

   double openPrice, stopLossPrice, takeProfitPrice;
   int    orderType;

   if(signalDirection == 1)
   {
      openPrice = Ask;
      stopLossPrice = NormalizeDouble(openPrice - stopLossDistance, Digits);
      takeProfitPrice = NormalizeDouble(openPrice + takeProfitDistance, Digits);
      orderType = OP_BUY;
   }
   else
   {
      openPrice = Bid;
      stopLossPrice = NormalizeDouble(openPrice + stopLossDistance, Digits);
      takeProfitPrice = NormalizeDouble(openPrice - takeProfitDistance, Digits);
      orderType = OP_SELL;
   }

   double positionLots = CalculateLots(stopLossDistance);
   if(positionLots <= 0) return;

   double riskRewardRatio = takeProfitDistance / stopLossDistance;
   if(riskRewardRatio < 1.5)
   {
      Print("Risk/reward ratio too low: ", DoubleToString(riskRewardRatio, 2), " | Skipping trade");
      return;
   }

   int ticket = OrderSend(
      Symbol(),
      orderType,
      positionLots,
      openPrice,
      30,
      stopLossPrice,
      takeProfitPrice,
      StringFormat("GoldEA|Strength:%d|ATR:%.2f", signalStrength, atrValue),
      MagicNumber,
      0,
      (signalDirection == 1) ? BuySignalColor : SellSignalColor
   );

   if(ticket > 0)
   {
      string directionText = (signalDirection == 1) ? "Buy long" : "Sell short";
      Print("Position opened | ", directionText,
            " | Ticket: ", ticket,
            " | Lots: ", DoubleToString(positionLots, 2),
            " | Entry: ", DoubleToString(openPrice, Digits),
            " | SL: ", DoubleToString(stopLossPrice, Digits),
            " | TP: ", DoubleToString(t

Показано первые 50% кода (символов: 20903)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
2 090,30₽ ≈ $25.55