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

XU XARDFX49

xu xardfx49.mq5
Вы автор или правообладатель?

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

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

О программе

XU XARDFX49 — торговый советник для MetaTrader 5, предоставляющий на графике интерактивную панель с кнопками для ручного открытия и закрытия позиций. Советник поддерживает покупку и продажу с настраиваемыми параметрами объёма, стоп-лосса и тейк-профита, а также включает систему виртуального стоп-лосса на уровне 2% от баланса с визуальным индикатором на чарте.

Программа позволяет работать с различными классами активов: валютные пары, акции, криптовалюты, индексы и товары. Для каждого символа предусмотрены индивидуальные коэффициенты масштабирования лотов. Встроена функция создания снимков графика с настройкой разрешения, а также режим отладки с логированием в журнал.

Советник не осуществляет автоматическую торговлю по сигналам индикаторов — все сделки выполняются вручную через нажатие кнопок на графике. Виртуальный стоп-лосс отслеживается в реальном времени: при достижении ценой уровня виртуального стопа панель меняет цвет, сигнализируя трейдеру.

Настройки программы

НастройкаОписание
ScreenshotWidth Ширина создаваемого снимка графика в пикселях
ScreenshotHeight Высота создаваемого снимка графика в пикселях
lotMode Режим управления размером лота: фиксированный или расчёт по проценту риска от капитала
fixedLotSize Фиксированный размер лота при ручном режиме управления объёмом
riskPercent Процент риска от equity для расчёта размера лота при режиме риска на капитал
slMode Режим расчёта стоп-лосса: фиксированные пипсы или процент от ATR
fixedPipsSL Фиксированное расстояние стоп-лосса в пунктах при фиксированном режиме
atrPercentSL Процент от значения ATR для расчёта стоп-лосса (например, 150% = 1.5x ATR)
tpMode Режим расчёта тейк-профита: фиксированные пипсы, процент от ATR или соотношение риск/прибыль
fixedPipsTP Фиксированное расстояние тейк-профита в пунктах при фиксированном режиме
atrPercentTP Процент от значения ATR для расчёта тейк-профита (например, 200% = 2x ATR)
riskRewardRatio Соотношение риска к прибыли для расчёта тейк-профита в режиме RR
atrPeriod Период усреднения индикатора ATR
atrTimeframe Таймфрейм для расчёта индикатора ATR
slippage Допустимое проскальзывание в пунктах при размещении торговых ордеров
BOXtest Отображение тестовой панели фиктивного стоп-лосса для проверки работы виртуального стопа
StopBOX_X Горизонтальное смещение панели виртуального стоп-лосса в пикселях
StopBOX_Y Вертикальное смещение панели виртуального стоп-лосса в пикселях
minLots Минимально допустимый размер лота
maxLots Максимально допустимый размер лота
ShowStopLossMessage Отображение сообщения с ценой виртуального стоп-лосса в комментарии на графике
DebugWithSquealers Включение подробного отладочного логирования в журнал MetaTrader

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

/*
      ███████╗ ██████╗ ██████╗ ███████╗██╗  ██╗     ███████╗████████╗ █████╗ ████████╗██╗ ██████╗ ███╗   ██╗
      ██╔════╝██╔═══██╗██╔══██╗██╔════╝╚██╗██╔╝     ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
      █████╗  ██║   ██║██████╔╝█████╗   ╚███╔╝█████╗███████╗   ██║   ███████║   ██║   ██║██║   ██║██╔██╗ ██║
      ██╔══╝  ██║   ██║██╔══██╗██╔══╝   ██╔██╗╚════╝╚════██║   ██║   ██╔══██║   ██║   ██║██║   ██║██║╚██╗██║
      ██║     ╚██████╔╝██║  ██║███████╗██╔╝ ██╗     ███████║   ██║   ██║  ██║   ██║   ██║╚██████╔╝██║ ╚████║
      ╚═╝      ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝     ╚══════╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝
*/

#property version     "1.49"
#property description "                      "
#property description "       What stands in the way becomes the way--This is the way (Aurelius)"
#property description "                      "
#property description "              THIS IS A FREE INDICATOR WITH NO TIME RESTRICTIONS"
#property description "                      "
#property description "                          Welcome to the XARD UNIVERSE"
#property description "             Let the light shine and illuminate your trading world"
#property description "                      "
#property description "               forex-station.com/post1295563064.html#p1295563064"
#property description "                      "

#define Version "XU XARDFX49"

#include <Trade\Trade.mqh>

string Name = MQLInfoString(MQL_PROGRAM_NAME), MyName = "XU XARDFX49";

const string INDICATOR_NAME = Version;
const int BUTTON_HEIGHT = 25;
const int FONT_SIZE = 9;
const int FONT_SIZE_BIG = FONT_SIZE + 3;
const string FONT_TYPE = "Arial Black";
const color FONT_COLOR = clrWhite;
const color PANEL_BORDER_COLOR = clrSnow;
const color PANEL_BG_COLOR = C'30,40,50';
const color BUTTON_BG_COLOR_BUY = clrBlue;
const color BUTTON_BG_COLOR_SELL = clrMediumVioletRed;
const int PANEL_BORDER_WIDTH = 1;
const ENUM_BASE_CORNER INFO_BOX_CORNER = CORNER_RIGHT_UPPER;
const int WINDOW = 0;
const int POS_LR = 6;
const int POS_UD = -100;

int stopPanelX = 824; // Right of bias panel
int stopPanelY = 1;
const int stopPanelWidth = 310;
const int stopPanelHeight = 24;
int stopLabelX = 979; // Centered in panel
int stopLabelY = 13;  // Centered vertically
const string stopPanelName = "XU-XARDFX13_STOP_PANEL";
const string stopLabelName = "XU-XARDFX13_STOP_LABEL";
const color upBiasColor = clrDodgerBlue;
const color downBiasColor = clrCrimson;
const color stopHitColor = clrGold;

input int ScreenshotWidth = 3840;  // Screenshot Width
input int ScreenshotHeight = 720;  // Screenshot Height

enum LOT_MODE
{
   FIXED_LOT,      // Fixed Lot
   RISK_ON_EQUITY  // Risk% on Equity
};
input LOT_MODE lotMode = RISK_ON_EQUITY; // Lot Mode
input double fixedLotSize = 0.01;        // Fixed Lot Size
input double riskPercent = 1.0;          // Risk% on Equity
double lotsTraded = 10000;               // Scaling factor (now global, adjustable)

enum SL_MODE
{
   FIXED_PIPS,     // Fixed Pips
   ATR_PERCENT,    // ATR%
};
input SL_MODE slMode = FIXED_PIPS;  // StopLoss Mode
input int fixedPipsSL = 50;         // Fixed Pips for SL
input double atrPercentSL = 150.0;  // ATR% for SL (e.g., 150% = 1.5x ATR)

enum TP_MODE
{
   FIXED_PIPS_TP,  // Fixed Pips
   ATR_PERCENT_TP, // ATR%
   RR_TP           // RR
};
input TP_MODE tpMode = FIXED_PIPS_TP; // TakeProfit Mode
input int fixedPipsTP = 100;          // Fixed Pips for TP
input double atrPercentTP = 200.0;    // ATR% for TP (e.g., 200% = 2x ATR)
input double riskRewardRatio = 2.0;   // RR for TP

input int atrPeriod = 14;             // ATR Period
input ENUM_TIMEFRAMES atrTimeframe = PERIOD_CURRENT; // ATR Timeframe

input int slippage = 5; // Slippage in points
input bool BOXtest = false; // Display fake stop box for testing
input int StopBOX_X = 0; // X position adjustment
input int StopBOX_Y = 0; // Y position adjustment
input double minLots = 0.01;  // Minimum lot size
input double maxLots = 10000; // Maximum lot size
input bool ShowStopLossMessage = true; // Show virtual stop message
input bool DebugWithSquealers = false; // Enable debug logging

ulong tradeTicket;
string display = "";
string symbolPair = "";
double Lots;
const int Move_X = -2;
const int Move_Y =  6;
ENUM_BASE_CORNER Corner = CORNER_RIGHT_UPPER;
int Button_Width = 100;
bool showINFOBOX = false;
const string ID = "FX PANEL 3";
color clrPanel = C'35,40,45';
CTrade trade;
long chartID;
const long magicNumber = 123456;
int tradeType = -1; // -1: No trade, 0: BUY, 1: SELL
double virtualStopPrice = 0.0;
bool stopHit = false;
bool tradeJustOpened = false;

void SetSymbolAdjustments()
{
        if (StringFind(symbolPair, "TSLA.nas", 0) == 0) { lotsTraded =  9000; } 
   else if (StringFind(symbolPair, "META.nas", 0) == 0) { lotsTraded =  9000; } 

   else if (StringFind(symbolPair, "XRPUSD", 0) == 0)   { lotsTraded =  8000; } // XRPUSD Updated
   else if (StringFind(symbolPair, "BTCUSD", 0) == 0)   { lotsTraded =  8000; } // BTCUSD Updated
   else if (StringFind(symbolPair, "WS30", 0) == 0)     { lotsTraded =  1300; } // WS30 Updated
   else if (StringFind(symbolPair, "US500", 0) == 0)    { lotsTraded =  5000; } // US500 Updated
   else if (StringFind(symbolPair, "XAGUSD", 0) == 0)   { lotsTraded = 30000; } // Silver Updated
   else if (StringFind(symbolPair, "XAUUSD", 0) == 0)   { lotsTraded = 30000; } // Gold Updated

   else if (StringFind(symbolPair, "JP225", 0) == 0)    { lotsTraded =  2500; } // JP225 tuned
   else if (StringFind(symbolPair, "NET.NYSE", 0) == 0) { lotsTraded =  9000; } // Cloud tuned

   else if (StringFind(symbolPair, "ETHUSD", 0) == 0)   { lotsTraded =  6000; } // ETHUSD tuned
   else if (StringFind(symbolPair, "NDX100", 0) == 0)   { lotsTraded =  1000; } // NDX100 tuned
   else if (StringFind(symbolPair, "ASX200", 0) == 0)   { lotsTraded =   300; } // ASX200 tuned
   else if (StringFind(symbolPair, "HK50", 0) == 0)     { lotsTraded =  1000; } // HK50 tuned

   else if (StringFind(symbolPair, "DAX40", 0) == 0)    { lotsTraded =   700; } // DAX40 tuned
   else if (StringFind(symbolPair, "USOUSD", 0) == 0)   { lotsTraded =   500; } // USOUSD tuned
   else if (StringFind(symbolPair, "USDCNH", 0) == 0)   { lotsTraded = 12000; } // USDCHN tuned

   else if (StringFind(symbolPair, "GBPJPY", 0) == 0)   { lotsTraded =  3000; } // GBPJPY tuned
   else if (StringFind(symbolPair, "GBPUSD", 0) == 0)   { lotsTraded =  3000; } // GBPJPY tuned
   else { lotsTraded = 12000; } // Default
}

double CalculatePipValue(string symbol, double lots)
{
   double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
   double tickValue = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE);
   double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
   double pipSize = (StringFind(symbol, "TSLA.nas", 0) == 0) ? 1.00 : 1.00; // Stocks use 1 point = $1
   double pipValuePerLot = (tickValue / tickSize) * pipSize;
   double pipValue = pipValuePerLot * lots;

   double conversionRate = 1.0;
   string accountCurrency = AccountInfoString(ACCOUNT_CURRENCY);
   string quoteCurrency = StringSubstr(symbol, 3, 3);
   if (quoteCurrency != accountCurrency)
   {
      string conversionPair = quoteCurrency + accountCurrency;
      conversionRate = SymbolInfoDouble(conversionPair, SYMBOL_BID);
      if (conversionRate == 0)
      {
         conversionPair = accountCurrency + quoteCurrency;
         conversionRate = SymbolInfoDouble(conversionPair, SYMBOL_BID);
         if (conversionRate != 0) conversionRate = 1.0 / conversionRate;
         else conversionRate = 1.3; // GBP/USD ≈ 1.3 fallback
      }
      pipValue *= conversionRate;
   }

   if (DebugWithSquealers)
   {
      Print("Pip Value - Symbol: ", symbol, ", Tick Size: ", tickSize, ", Tick Value: ", tickValue, 
            ", Point: ", point, ", Pip Value: ", pipValue);
   }
   return pipValue;
}

double GetATRValue()
{
   double atrArray[];
   int atrHandle = iATR(symbolPair, atrTimeframe, atrPeriod);
   if (atrHandle == INVALID_HANDLE)
   {
      Print("Error: Unable to create ATR handle");
      return 0;
   }
   if (CopyBuffer(atrHandle, 0, 0, 1, atrArray) <= 0)
   {
      Print("Error: Unable to copy ATR buffer");
      return 0;
   }
   return atrArray[0];
}

double CalculateSLPrice(int tradeDirection, double entryPrice)
{
   double slPrice = 0;
   if (slMode == FIXED_PIPS)
   {
      double pipSize = SymbolInfoDouble(symbolPair, SYMBOL_POINT);
      slPrice = (tradeDirection == 0) ? entryPrice - fixedPipsSL * pipSize : entryPrice + fixedPipsSL * pipSize;
   }
   else if (slMode == ATR_PERCENT)
   {
      double atrValue = GetATRValue();
      if (atrValue == 0) return 0;
      double slDistance = (atrPercentSL / 100.0) * atrValue;
      slPrice = (tradeDirection == 0) ? entryPrice - slDistance : entryPrice + slDistance;
   }
   return NormalizeDouble(slPrice, _Digits);
}

double CalculateTPPrice(int tradeDirection, double entryPrice, double slPrice)
{
   double tpPrice = 0;
   if (tpMode == FIXED_PIPS_TP)
   {
      double pipSize = SymbolInfoDouble(symbolPair, SYMBOL_POINT);
      tpPrice = (tradeDirection == 0) ? entryPrice + fixedPipsTP * pipSize : entryPrice - fixedPipsTP * pipSize;
   }
   else if (tpMode == ATR_PERCENT_TP)
   {
      double atrValue = GetATRValue();
      if (atrValue == 0) return 0;
      double tpDistance = (atrPercentTP / 100.0) * atrValue;
      tpPrice = (tradeDirection == 0) ? entryPrice + tpDistance : entryPrice - tpDistance;
   }
   else if (tpMode == RR_TP)
   {
      if (slPrice == 0) return 0;
      double slDistance = MathAbs(entryPrice - slPrice);
      double tpDistance = slDistance * riskRewardRatio;
      tpPrice = (tradeDirection == 0) ? entryPrice + tpDistance : entryPrice - tpDistance;
   }
   return NormalizeDouble(tpPrice, _Digits);
}

double CalculateLotSize(double entryPrice, double slPrice)
{
   double lots = 0;
   SetSymbolAdjustments(); // Adjust lotsTraded per symbol
   if (lotMode == FIXED_LOT)
   {
      lots = fixedLotSize;
      if (DebugWithSquealers) Print("SQUEALER: FIXED_LOT - Lots: ", lots);
   }
   else if (lotMode == RISK_ON_EQUITY)
   {
      double equity = AccountInfoDouble(ACCOUNT_EQUITY);
      lots = (equity * (riskPercent / 100.0)) / (lotsTraded / 100); // Raw: 0.04 for £400 on forex, ~0.019 shares TSLA
      if (StringFind(symbolPair, "TSLA.nas", 0) == 0) lots = MathMax(1, MathRound(lots * 100)); // Convert to shares, min 1
      if (StringFind(symbolPair, "META.nas", 0) == 0) lots = MathMax(1, MathRound(lots * 100)); // Convert to shares, min 1
      if (DebugWithSquealers) Print("SQUEALER: RISK_ON_EQUITY - Equity: ", equity, ", Risk%: ", riskPercent, 
                                    ", LotsTraded: ", lotsTraded, ", Raw Lots/Shares: ", lots);
   }
   double minLotsLocal = SymbolInfoDouble(symbolPair, SYMBOL_VOLUME_MIN);
   double maxLotsLocal = SymbolInfoDouble(symbolPair, SYMBOL_VOLUME_MAX);
   double step = SymbolInfoDouble(symbolPair, SYMBOL_VOLUME_STEP);
   if (step > 0)
   {
      lots = NormalizeDouble(MathRound(lots / step) * step, 2);
      if (DebugWithSquealers) Print("SQUEALER: Step Adjusted - Step: ", step, ", Lots: ", lots);
   }
   if (lots < minLotsLocal)
   {
      lots = minLotsLocal;
      if (DebugWithSquealers) Print("SQUEALER: Adjusted to Broker Min - Raw: ", lots, ", New: ", minLotsLocal);
   }
   lots = MathMax(minLots, MathMin(maxLots, lots));
   if (DebugWithSquealers) Print("SQUEALER: Final - Broker Min: ", minLotsLocal, ", Max: ", maxLotsLocal, ", Final Lots/Shares: ", lots);
   return lots;
}

void TakeSnapshot(const string action)
{
   datetime time = TimeLocal();
   MqlDateTime dt;
   TimeToStruct(time, dt);
   string screenshotFilename = StringFormat("Snapshot %s %d %s %d-%02d-%02d %02d%02d%02d.png",
                                            Symbol(), Period(), action, dt.year, dt.mon, dt.day,
                                            dt.hour, dt.min, dt.sec);
   if (!ChartScreenShot(ChartID(), screenshotFilename, ScreenshotWidth, ScreenshotHeight, ALIGN_RIGHT))
   {
      Print("Failed to take screenshot: ", GetLastError());
   }
   else
   {
      if (DebugWithSquealers) Print("SQUEALER: Screenshot taken: ", screenshotFilename);
   }
}

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

void OnDeinit(const int reason)
{
   DeleteButtons();
   CleanUpOnAisle1();
   ObjectDelete(chartID, "Lot_Edit");
   ObjectDelete(chartID, stopPanelName);
   ObjectDelete(chartID, stopLabelName);
   if (DebugWithSquealers) Print("OnDeinit Complete - Chart ", chartID);
}

void OnTick()
{
      // код доступен только после оплаты
   }
   if (Name != MyName)
   {
      Comment("\n                The name of this EA cannot be changed\n            ''" + MyName + "''");
      return;
   }
   bool tradeOpen = false;
   for (int i = 0; i < PositionsTotal(); i++)
   {
      ulong ticket = PositionGetTicket(i);
      if (PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_MAGIC) == magicNumber && PositionGetString(POSITION_SYMBOL) == symbolPair)
      {
         tradeOpen = true;
         if (tradeJustOpened)
         {
            tradeJustOpened = false;
            break;
         }
         double currentPrice = (tradeType == 0) ? SymbolInfoDouble(symbolPair, SYMBOL_BID) : SymbolInfoDouble(symbolPair, SYMBOL_ASK);
         if (tradeType == 0 && virtualStopPrice > 0 && currentPrice <= virtualStopPrice)
         {
            stopHit = true;
            ObjectSetInteger(chartID, stopPanelName, OBJPROP_BGCOLOR, stopHitColor);
            ObjectSetInteger(chartID, stopLabelName, OBJPROP_COLOR, clrBlack);
         }
         else if (tradeType == 1 && virtualStopPrice > 0 && currentPrice >= virtualStopPrice)
         {
            stopHit = true;
            ObjectSetInteger(chartID, stopPanelName, OBJPROP_BGCOLOR, stopHitColor);
            ObjectSetInteger(chartID, stopLabelName, OBJPROP_COLOR, clrBlack);
         }
         break;
      }
   }
   if (!tradeOpen)
   {
      if (BOXtest)
      {
         CreateRectanglePanel(chartID, stopPanelName, 0, stopPanelX, stopPanelY, stopPanelWidth, sto

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