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

Master Scalping@LifeInDreamsWorld

4_5857493707003010889.mq4
Вы автор или правообладатель?

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

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

О программе

Этот файл представляет собой торговый советник для MetaTrader 4, написанный на языке MQL4. Советник предназначен для автоматической торговли на валютном рынке и использует рыночные и торговые события платформы. В коде присутствуют обработчики инициализации, деинициализации и тика, а также функции для открытия рыночных ордеров и управления позициями. Советник работает по логике пробоя уровней предыдущих свечей и может использовать автоматический расчёт лота в зависимости от средств на счёте.

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

Советник также содержит вспомогательные функции для получения описания ошибок торговых операций и вывода информационных сообщений в журнал. Все торговые операции выполняются с использованием стандартных функций MetaTrader 4. Параметры советника позволяют настроить магический номер, фиксированный лот, режим автоматического расчёта лота, делитель средств для авто-лота, а также уровни тейк-профита и стоп-лосса в пунктах.

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

НастройкаОписание
MagicNumber Уникальный идентификатор (магический номер) советника для различения своих ордеров и позиций. Должен быть положительным числом. Значение по умолчанию 53452134.
FixedLot Фиксированный размер лота, используемый при выключенном автоматическом расчёте. Значение по умолчанию 0.01.
AutoLot Переключатель режима автоматического расчёта размера лота. Если включён, лот вычисляется на основе средств на счёте и делителя LotEquityDivider. Если выключен, используется фиксированный лот FixedLot.
LotEquityDivider Делитель средств для автоматического расчёта лота. Используется только при включённом параметре AutoLot. Значение по умолчанию 10000.0.
TP Уровень тейк-профита в пунктах. Если значение больше нуля, при открытии ордера устанавливается тейк-профит на указанном расстоянии от цены входа. Значение по умолчанию 50.0.
SL Уровень стоп-лосса в пунктах. Если значение больше нуля, при открытии ордера устанавливается стоп-лосс на указанном расстоянии от цены входа. Значение по умолчанию 50.0.
Получить полный код

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

#property version   "1.00"
#property strict

input int    MagicNumber       = 53452134;   // Magic Number
input double FixedLot          = 0.01;       // Fixed Lot Size
input bool   AutoLot           = true;       // Use Auto Lot Calculation
input double LotEquityDivider  = 10000.0;    // Equity Divider for AutoLot
input double TP                = 50.0;       // Take Profit in points
input double SL                = 50.0;       // Stop Loss in points

datetime LastBarTime = 0;

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

void OnDeinit(const int reason)
  {
   Print("Master Scalping@LifeInDreamsWorld EA deinitialized.");
  }

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

double CalculateLotSize()
  {
   double lot = FixedLot;

   if(AutoLot)
     {
      double equity = AccountEquity();
      lot = equity / LotEquityDivider;
     }

   double minLot   = MarketInfo(Symbol(), MODE_MINLOT);
   double maxLot   = MarketInfo(Symbol(), MODE_MAXLOT);
   double lotStep  = MarketInfo(Symbol(), MODE_LOTSTEP);

   lot = MathMax(minLot, MathMin(maxLot, lot));

   if(lotStep > 0)
     {
      lot = NormalizeDouble(MathFloor(lot / lotStep) * lotStep, 8);
     }
   else
     {
      lot = NormalizeDouble(lot, 2);
     }

   if(lot < minLot) lot = 0;

   return(lot);
  }

bool HasOpenPosition()
  {
   for(int i = OrdersTotal()-1; i >= 0; i--)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            return(true);
           }
        }
     }
   return(false);
  }

void OpenBuyOrder(double lotSize)
  {
   int ticket = -1;
   double sl = 0;
   double tp = 0;

   if(SL > 0) sl = Ask - SL * Point;
   if(TP > 0) tp = Ask + TP * Point;

   ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, 3, sl, tp, "MasterScalping Buy", MagicNumber, 0, clrGreen);

   if(ticket > 0)
     {
      Print("Buy order opened successfully. Ticket: ", ticket, " Lots: ", lotSize);
     }
   else
     {
      int error = GetLastError();
      Print("Buy OrderSend failed. Error: ", error, " - ", ErrorDescription(error));
     }
  }

void OpenSellOrder(double lotSize)
  {
   int ticket = -1;
   double sl = 0;
   double tp = 0;

   if(SL > 0) sl = Bid + SL * Point;
   if(TP > 0) tp = Bid - TP * Point;

   ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, 3, sl, tp, "MasterScalping Sell", MagicNumber, 0, clrRed);

   if(ticket > 0)
     {
      Print("Sell order opened successfully. Ticket: ", ticket, " Lots: ", lotSize);
     }
   else
     {
      int error = GetLastError();
      Print("Sell OrderSend failed. Error: ", error, " - ", ErrorDescription(error));
     }
  }

string ErrorDescription(int error_code)
  {
   switch(error_code)
     {
      case 0:   return("No error");
      case 1:   return("No error, trade executed");
      case 2:   return("Common error");
      case 3:   return("Invalid trade parameters");
      case 4:   return("Trade server is busy");
      case 5:   return("Old version of client terminal");
      case 6:   return("No connection with trade server");
      case 7:   return("Not enough rights");
      case 8:   return("Too frequent requests");
      case 9:   return("Malfunctional trade operation");
      case 64:  return("Account disabled");
      case 65:  return("Invalid account");
      case 130: return("Invalid stops");
      case 131: return("Invalid trade volume");
      case 132: return("Market is closed");
      case 133: return("Trade is disabled");
      case 134: return("Not enough money");
      case 135: return("Price changed");
      case 136: return("No prices");
      case 137: return("Broker is busy");
      case 138: return("Requote");
      case 139: return("Order is locked");
      case 140: return("Buy orders only allowed");
      case 141: return("Too many requests");
      case 145: return("Modification denied because order is too close to market");
      case 146: return("Trade context is busy");
      case 147: return("Expiration is denied by broker");
      case 148: return("Amount of open and pending orders has reached the limit");
      default:  return("Unknown error");
     }
  }

/*bool __disabled; // whether or not the block is disabled

		string __block_user_number;
        int __block_number;
		int __block_waiting;
		int __parent_number;
		int __inbound_blocks[];
		int __outbound_blocks[];

		void __addInboundBlock(int id = 0) {
			int size = ArraySize(__inbound_blocks);
			for (int i = 0; i < size; i++) {
				if (__inbound_blocks[i] == id) {
					return;
				}
			}
			ArrayResize(__inbound_blocks, size + 1);
			__inbound_blocks[size] = id;
		}

		void BlockCalls() {
			__disabled          = false;
			__block_user_number = "";
			__block_number      = 0;
			__block_waiting     = 0;
			__parent_number     = 0;
		}

		/**
		   Announce this block to the list of inbound connections of all the blocks to which this block is connected to

		void __announceThisBlock()
		{

			for (int i = 0; i < ArraySize(__outbound_blocks); i++)
			{
				int block = __outbound_blocks[i]; // outbound block number
				int size  = ArraySize(_blocks_[block].__inbound_blocks); // the size of its inbound list

				for (int j = 0; j < size; j++) {
					if (_blocks_[block].__inbound_blocks[j] == __block_number)
					{
						return;
					}
				}

				ArrayResize(_blocks_[block].__inbound_blocks, size + 1);
				_blocks_[block].__inbound_blocks[size] = __block_number;
			}
		}

		virtual void _execute_() = 0;

		/**
			In the derived class this method should be used to set dynamic parameters or other stuff before the main execute.
			This method is automatically called within the main "run" method below, before the execution of the main class.

		virtual void _beforeExecute_() {return;};
		bool _beforeExecuteEnabled; // for speed

		/**
			Same as _beforeExecute_, but to work after the execute method.

		virtual void _afterExecute_() {return;};
		bool _afterExecuteEnabled; // for speed

		/**
			This is the method that is used to run the block

		virtual void run(int _parent_=0) {
			__parent_number = _parent_;
			if (__disabled || FXD_BREAK) {return;}
			FXD_CURRENT_FUNCTION_ID = __block_number;

			if (_beforeExecuteEnabled) {_beforeExecute_();}
			_execute_();
			if (_afterExecuteEnabled) {_afterExecute_();}

			if (__block_waiting && FXD_CURRENT_FUNCTION_ID == __block_number) {fxdWait.Accumulate(FXD_CURRENT_FUNCTION_ID);}
		}

	T20 StopLossPips;
	T21 GridSizeSL;
	T22 dlStopLoss; virtual _T22_ _dlStopLoss_(){return(_T22_)0;}
	T23 dpStopLoss; virtual _T23_ _dpStopLoss_(){return(_T23_)0;}
	T24 ddStopLoss; virtual _T24_ _ddStopLoss_(){return(_T24_)0;}
	T25 gTPmode;
	T26 TakeProfitPips;
	T27 GridSizeTP;
	T28 dlTakeProfit; virtual _T28_ _dlTakeProfit_(){return(_T28_)0;}
	T29 dpTakeProfit; virtual _T29_ _dpTakeProfit_(){return(_T29_)0;}
	T30 ddTakeProfit; virtual _T30_ _ddTakeProfit_(){return(_T30_)0;}
	T31 GridLevelsGradation;
	T32 GridVolumesGradation;
	T33 GridSLgradation;
	T34 GridTPgradation;
	T35 ExpMode;
	T36 ExpDays;
	T37 ExpHours;
	T38 ExpMinutes;
	T39 dExp; virtual _T39_ _dExp_(){return(_T39_)0;}
	T40 Slippage;
	T41 MyComment;
	T42 ArrowColorSell;
	virtual void _callback_(int r) {return;}

	public: /* Constructor *
	MDL_GridPendingSells2()
	{
		Group = (string)"";
		Symbol = (string)CurrentSymbol();
		GridOrdersCount = (int)3;
		GridStart = (string)"bid";
		GridStartOffset = (double)0.0;
		GridStartRoundNumberPips = (double)0.0;
		GridSize = (double)25.0;
		VolumeMode = (string)"fixed";
		VolumeSize = (double)0.1;
		VolumeSizeRisk = (double)50.0;
		VolumeRisk = (double)2.5;
		VolumePercent = (double)100.0;
		VolumeBlockPercent = (double)3.0;
		FixedRatioUnitSize = (double)0.01;
		FixedRatioDelta = (double)20.0;
		VolumeUpperLimit = (double)0.0;
		gSLmode = (string)"fixed";
		StopLossPips = (double)50.0;
		GridSizeSL = (double)100.0;
		gTPmode = (string)"fixed";
		TakeProfitPips = (double)50.0;
		GridSizeTP = (double)100.0;
		GridLevelsGradation = (double)100.0;
		GridVolumesGradation = (double)100.0;
		GridSLgradation = (double)100.0;
		GridTPgradation = (double)100.0;
		ExpMode = (string)"GTC";
		ExpDays = (int)0;
		ExpHours = (int)1;
		ExpMinutes = (int)0;
		Slippage = (ulong)4;
		MyComment = (string)"";
		ArrowColorSell = (color)clrRed;
	}

	public: /* The main method *
	virtual void _execute_()
	{

		double op=0;

		     if (GridStart == "ask")      {op = SymbolAsk(Symbol);}
		else if (GridStart == "bid")      {op = SymbolBid(Symbol);}
		else if (GridStart == "mid")      {op = (SymbolAsk(Symbol) + SymbolBid(Symbol)) / 2;}
		else if (GridStart == "function") {op = _fGridStart_();}

		op = op - toDigits(GridStartOffset, Symbol);

		if (GridStartRoundNumberPips != 0)
		{
			double grid_start_round_number = toDigits(GridStartRoundNumberPips, Symbol);

			op = MathFloor(op / grid_start_round_number) * grid_start_round_number;
		}

		double sll = 0, slp = 0, tpl = 0, tpp = 0;

		     if (gSLmode == "fixed")           {slp = StopLossPips;}
		else if (gSLmode == "gridsize")        {slp = GridSize * (GridSizeSL / 100);}
		else if (gSLmode == "dynamicPips")     {slp = _dpStopLoss_();}
		else if (gSLmode == "dynamicDigits")   {slp = toPips(_ddStopLoss_(), Symbol);}
		else if (gSLmode == "dynamicLevel")    {sll = _dlStopLoss_();}
		else if (gSLmode == "dynamicLevelAll") {sll = _dlStopLoss_();}

		     if (gTPmode == "fixed")           {tpp = TakeProfitPips;}
		else if (gTPmode == "gridsize")        {tpp = GridSize * (GridSizeTP / 100);}
		else if (gTPmode == "dynamicPips")     {tpp = _dpTakeProfit_();}
		else if (gTPmode == "dynamicDigits")   {tpp = toPips(_ddTakeProfit_(), Symbol);}
		else if (gTPmode == "dynamicLevel")    {tpl = _dlTakeProfit_();}
		else if (gTPmode == "dynamicLevelAll") {tpl = _dlTakeProfit_();}

		double lots    = 0;
		double pre_sll = sll;

		if (pre_sll == 0) {pre_sll = op;}

		double pre_sl_pips = toPips((pre_sll + toDigits(slp, Symbol)) - op, Symbol);

		     if (VolumeMode == "fixed")            {lots = DynamicLots(Symbol, VolumeMode, VolumeSize);}
		else if (VolumeMode == "block-equity")     {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
		else if (VolumeMode == "block-balance")    {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
		else if (VolumeMode == "block-freemargin") {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
		else if (VolumeMode == "equity")           {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
		else if (VolumeMode == "balance")          {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
		else if (VolumeMode == "freemargin")       {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
		else if (VolumeMode == "equityRisk")       {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
		else if (VolumeMode == "balanceRisk")      {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
		else if (VolumeMode == "freemarginRisk")   {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
		else if (VolumeMode == "fixedRisk")        {lots = DynamicLots(Symbol, VolumeMode, VolumeSizeRisk, pre_sl_pips);}
		else if (VolumeMode == "fixedRatio")       {lots = DynamicLots(Symbol, VolumeMode, FixedRatioUnitSize, FixedRatioDelta);}
		else if (VolumeMode == "dynamic")          {lots = _dVolumeSize_();}

		lots = AlignLots(Symbol, lots, 0, VolumeUpperLimit);

		datetime exp = ExpirationTime(ExpMode, ExpDays, ExpHours, ExpMinutes, _dExp_());

		long ticket = 0;
		double gSize = GridSize;
		double gSL  = slp;
		double gTP  = tpp;

		if (sll > 0)
		{
			gSL = toPips(sll - op, Symbol);

			if (gSLmode == "dynamicLevelAll")
			{
				gSL = 0;
			}
			else if (gSLmode != "dynamicLevelAll")
			{
				sll = 0;
			}
		}

		if (tpl > 0)
		{
			gTP = toPips(op - tpl, Symbol);

			if (gTPmode == "dynamicLevelAll")
			{
				gTP = 0;
			}
			else if (gTPmode != "dynamicLevelAll")
			{
				tpl = 0;
			}
		}

		for (int cnt = 1; cnt <= GridOrdersCount; cnt++)
		{
			if (cnt == 1)
			{
				if (gSLmode == "gridsize") gSL = gSize * (GridSizeSL / 100);
				if (gTPmode == "gridsize") gTP = gSize * (GridSizeTP / 100);
			}
			else
			{
				if (GridLevelsGradation > 0) gSize = gSize * (GridLevelsGradation / 100);

				lots = lots * (GridVolumesGradation / 100);

				if (gSLmode == "gridsize") gSL = gSize * (GridSizeSL / 100);
				gSL = gSL * (GridSLgradation / 100);

				if (gTPmode == "gridsize") gTP = gSize * (GridSizeTP / 100);
				gTP = gTP * (GridTPgradation / 100);
			}

			op = op - toDigits(gSize, Symbol);
			double lotsAligned = AlignLots(Symbol, lots, 0, VolumeUpperLimit);

			ticket = SellLater(Symbol, lotsAligned, op, sll, tpl, gSL, gTP, Slippage, exp, (MagicStart + (int)Group), MyComment, ArrowColorSell);
		}

		if (ticket > 0) {_callback_(1);} else {_callback_(0);}
	}
};

template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7>
class MDL_ImpulseDn: public BlockCalls
{
	public: /* Input Parameters 
	T1 SignalType;
	T2 QuietBarsCount;
	T3 QuietBarsMinRange;
	T4 ImpulseStrength;
	T5 ImpulseShift;
	T6 Symbol;
	T7 Period;
	/* Static Parameters 
	double QBrange;
	datetime BarTime;
	datetime BarTime2;
	double InpOpen;
	virtual void _callback_(int r) {return;}

	public: /* Constructor *
	MDL_ImpulseDn()
	{
		SignalType = (string)"continuous";
		QuietBarsCount = (int)3;
		QuietBarsMinRange = (double)10.0;
		ImpulseStrength = (double)3.0;
		ImpulseShift = (int)0;
		Symbol = (string)CurrentSymbol();
		Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
		/* Static Parameters (initial value) 
		QBrange = -1;
		BarTime =  0;
		BarTime2 =  0;
		InpOpen =  0;
	}

	public: /* The main method 
	virtual void _execute_()
	{
		int i            = 0;
		double MaxSize   = 0;
		bool NewBarComes = false;
		bool pass        = false;

		if (BarTime < iTime(Symbol,Period,1) || QBrange == -1)
		{
			BarTime = (int)iTime(Symbol,Period,1);
			QBrange = 0;

			for (i=0; i < QuietBarsCount; i++)
			{
				int shift = i + 1 + ImpulseShift;
				MaxSize   = iHigh(Symbol,Period,shift) - iLow(Symbol,Period,shift);

				if (MaxSize > QBrange)
				{
					QBrange = MaxSize;
				}
			}

			InpOpen     = iOpen(Symbol,Period,ImpulseShift);
			NewBarComes = true;
		}

		if (
			   (SignalType == "continuous" || BarTime2 < iTime(Symbol,Period,1))
			&& ((ImpulseShift == 0 && InpOpen > 0) || NewBarComes == true)
			&& QBrange > toDigits(QuietBarsMinRange, Symbol)
		)
		{
			double ImpSize = InpOpen - iClose(Symbol,Period,ImpulseShift);

			if (ImpSize >= QBrange * ImpulseStrength)
			{
				if (SignalType != "continuous")
				{
					BarTime2 = (int)iTime(Symbol,Period,1);
				}

				pass = true;
			}
		}

		if (pass == true) {_callback_(1);} else {_callback_(0);}
	}
};

template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename _T8_,typename T9,typename T10,typename T11,typename T12,typename T13,typename T14,typename T15,typename T16,typename _T16_,typename T17,typename T18,typename T19,typename T20,typename T21,typename _T21_,typename T22>
class MDL_TrailingStopAvgPrice: public BlockCalls
{
	public: /* Input Parameters 
	T1 GroupMode;
	T2 Group;
	T3 Symbol;
	T4 BuysOrSells;
	T5 TrailWhat;
	T6 TrailingStopMode;
	T7 tStopPips;
	T8 ftStop; virtual _T8_ _ftStop_(){return(_T8_)0;}
	T9 tStopMoney;
	T10 TrailingStepMode;
	T11 tStepPips;
	T12 tStepPercentTS;
	T13 TrailingStartMode;
	T14 tStartPips;
	T15 tStartPercentTS;
	T16 ftStart; virtual _T16_ _ftStart_(){return(_T16_)0;}
	T17 resetOnTrade;
	T18 TrailingTPmode;
	T19 tTPpips;
	T20 tTPpercentTS;
	T21 ftTP; virtual _T21_ _ftTP_(){return(_T21_)0;}
	T22 LevelColor;
	/* Static Parameters 
	double avg_lots0;
	double group_stop;
	string change_detect0;
	virtual void _callback_(int r) {return;}

	public: /* Constructor 
	MDL_TrailingStopAvgPrice()
	{
		GroupMode = (string)"group";
		Group = (string)"";
		Symbol = (string)CurrentSymbol();
		BuysOrSells = (string)"both";
		TrailWhat = (int)1;
		TrailingStopMode = (string)"fixed";
		tStopPips = (double)40.0;
		tStopMoney = (double)10.0;
		TrailingStepMode = (string)"fixed";
		tStepPips = (double)1.0;
		tStepPercentTS = (double)10.0;
		TrailingStartMode = (string)"none";
		tStartPips = (double)10.0;
		tStartPercentTS = (double)100.0;
		resetOnTrade = (bool)true;
		TrailingTPmode = (string)"none";
		tTPpips = (double)20.0;
		tTPpercentTS = (double)200.0;
		LevelColor = (color)clrDeepPink;
		/* Static Parameters (initial value) 
		avg_lots0 =  0;
		group_stop =  0;
		change_detect0 =  "";
	}

	public: /* The main method *
	virtual void _execute_()
	{
		int index        = 0;
		double avg_price = 0;
		double avg_load  = 0;
		double avg_lots  = 0; // Average sum of lots - it can be negative
		double profit    = 0;
		double askbid    = 0;
		double bidask    = 0;
		int trades_count = 0; // Count of Trades to work with
		bool resetSL     = false;
		ulong tickets[]; ArrayResize(tickets, 0); // Array with tickets to modify

		string change_detect         = "";

		int total = TradesTotal();

		for (index = 0; index < total; index++)
		{
			if (!TradeSelectByIndex(index, GroupMode, Group, "symbol", Symbol, BuysOrSells)) {continue;}

			if (OrderType() == 0)
			{
				avg_load = avg_load + (OrderOpenPrice() * OrderLots());
				avg_lots = avg_lots + OrderLots();
			}
			else
			{
				avg_load = avg_load - (OrderOpenPrice() * OrderLots());
				avg_lots = avg_lots - OrderLots();
			}

			ArrayEnsureValue(tickets, (ulong)OrderTicket());

			profit        = profit + NormalizeDouble(OrderProfit() + OrderCommission() + OrderSwap(), 2);
			change_detect = (string)OrderTicket() + change_detect;
			trades_count++;
		}

		avg_price = 0;

		if (avg_lots != 0)
		{
			avg_price = avg_load / avg_lots;
		}

		if (change_detect0 != change_detect)
		{
			if (trades_count == 0)
			{
				avg_lots0  = 0;
				group_stop = 0;
			}
			else
			{
				group_stop = 0;

				if (resetOnTrade == true)
				{
					avg_lots0 = avg_lots;
					resetSL   = true;
				}
			}

			change_detect0 = change_detect;
		}

		if (avg_lots != 0)
		{
			int polarity = 0;

			if (avg_lots > 0)
			{
				polarity = 1;
				askbid   = SymbolAsk(Symbol);
				bidask   = SymbolBid(Symbol);
			}
			else
			{
				polarity = -1;
				askbid   = SymbolBid(Symbol);
				bidask   = SymbolAsk(Symbol);
			}

			double t_stop = 0;

			     if (TrailingStopMode == "fixed")       {t_stop = tStopPips;}
			else if (TrailingStopMode == "dynamicSize") {t_stop = _ftStop_();}
			else if (TrailingStopMode == "function")
			{
				t_stop = _ftStop_();
				t_stop = toPips(MathAbs(askbid-t_stop), Symbol);
			}
			else if (TrailingStopMode == "money")
			{
				double tick_value = SymbolInfoDouble(Symbol, SYMBOL_TRADE_TICK_VALUE);
				double tick_size  = SymbolInfoDouble(Symbol, SYMBOL_TRADE_TICK_SIZE);
				double point      = SymbolInfoDouble(Symbol, SYMBOL_POINT);

				double tickvalue = ((tick_value / tick_size) * point);

				t_stop = tStopMoney;
				t_stop = t_stop /  ((MathAbs(avg_lots) * PipValue(Symbol)));
				t_stop = t_stop / tickvalue;
			}

			double t_start = 0;

			     if (TrailingStartMode == "none")      {t_start = -EMPTY_VALUE;}
			else if (TrailingStartMode == "zero")      {t_start = 0;}
			else if (TrailingStartMode == "fixed")     {t_start = tStartPips;}
			else if (TrailingStartMode == "percentTS") {t_start = t_stop * (tStartPercentTS / 100);}
			else if (TrailingStartMode == "function")  {t_start = _ftStart_();}

			double t_step = 0;

			     if (TrailingStepMode == "fixed")      {t_step = tStepPips;}
			else if (TrailingStepMode == "percentTS")  {t_step = t_stop * (tStepPercentTS / 100);}

			double t_opp = -1;

			     if (TrailingTPmode == "none")         {t_opp = -1;}
			else if (TrailingTPmode == "clear")        {t_opp = 0;}
			else if (TrailingTPmode == "fixed")        {t_opp = MathAbs(toPips(avg_price - group_stop, Symbol));}
			else if (TrailingTPmode == "percentTS")    {t_opp = MathAbs(toPips(avg_price - t_stop, Symbol)) * (tTPpercentTS/100);}
			else if (TrailingTPmode == "function")     {t_opp = _ftTP_();}

			bool go_modify = false;

			if (polarity == 1 && TrailWhat * (askbid - avg_price) > toDigits(t_start, Symbol))
			{
				if ((TrailWhat * (askbid - group_stop) >= toDigits(t_stop + t_step, Symbol)) || group_stop==0 || resetSL == true)
				{
					group_stop = (askbid - TrailWhat * toDigits(t_stop, Symbol));
					go_modify  = true;
				}
			}
			else if (polarity == -1 && TrailWhat * (avg_price - askbid) > toDigits(t_start, Symbol))
			{
				if ((TrailWhat * (group_stop - askbid) >= toDigits(t_stop + t_step, Symbol)) || group_stop == 0 || resetSL == true)
				{
					group_stop = (askbid + TrailWhat * toDigits(t_stop, Symbol));
					go_modify  = true;
				}
			}

			if (go_modify==true)
			{
				for (index = ArraySize(tickets) - 1; index >= 0; index--)
				{
					if (TradeSelectByTicket(tickets[index]))
					{
						bool success = true;

						double stopslevel = (double)SymbolInfoInteger(OrderSymbol(), SYMBOL_TRADE_STOPS_LEVEL);
						stopslevel        = toDigits(stopslevel / PipValue(OrderSymbol()), OrderSymbol());
						double fsl        = MathAbs(group_stop); // future SL
						double limit      = 0;

						if (OrderType() == 0)
						{
							limit = bidask - stopslevel * TrailWhat;
							if (fsl > limit) {fsl = limit;}
						}
						else
						{
							limit = bidask + stopslevel * TrailWhat;
							if (fsl < limit) {fsl = limit;}
						}

						if (TrailWhat == 1)
						{
							if (t_opp < 0) {t_opp = attrTakeProfit();}

							if (
								   attrStopLoss() == 0
								|| (OrderType() == 0 && (attrStopLoss() < fsl || resetSL == true))
								|| (OrderType() == 1 && (attrStopLoss() > fsl || resetSL == true))
							)
							{
								success = ModifyStops(OrderTicket(), group_stop, t_opp, LevelColor);
							}
						}

						else
						{
							if (t_opp < 0) {t_opp = attrStopLoss();}

							if (
								   attrTakeProfit() == 0
								|| (OrderType() == 0 && (attrTakeProfit() > fsl || resetSL == true))
								|| (OrderType() == 1 && (attrTakeProfit() < fsl || resetSL == true))
							)
							{
								success = ModifyStops(OrderTicket(), t_opp, group_stop, LevelColor);
							}
						}
					}
				}
			}
		}

		_callback_(1);
	}
};

template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename T10,typename T11,typename T12,typename T13,typename T14,typename _T14_,typename T15,typename _T15_,typename T16,typename T17,typename T18,typename T19,typename T20,typename T21,typename T22,typename T23,typename T24,typename _T24_,typename T25,typename _T25_,typename T26,typename T27,typename T28,typename T29,typename _T29_,typename T30>
class MDL_TrailingStop2: public BlockCalls
{
	public: /* Input Parameters *
	T1 GroupMode;
	T2 Group;
	T3 SymbolMode;
	T4 Symbol;
	T5 BuysOrSells;
	T6 TrailWhat;
	T7 TrailingReferencePrice;
	T8 TrailingStopMode;
	T9 tStopPips;
	T10 tStopMoney;
	T11 tStopMultiple;
	T12 tStopPercentTP;
	T13 tStopPercentProfit;
	T14 ftStop; virtual _T14_ _ftStop_(){return(_T14_)0;}
	T15 ftDigits; virtual _T15_ _ftDigits_(){return(_T15_)0;}
	T16 TrailingStepMode;
	T17 tStepPips;
	T18 tStepPercentTS;
	T19 TrailingStartMode;
	T20 tStartPips;
	T21 tStartPercentTS;
	T22 tStartPercentSL;
	T23 tStartPercentTP;
	T24 ftStart; virtual _T24_ _ftStart_(){return(_T24_)0;}
	T25 ftStartFraction; virtual _T25_ _ftStartFraction_(){return(_T25_)0;}
	T26 TrailingTPmode;
	T27 tTPpips;
	T28 tTPpercentTS;
	T29 ftTP; virtual _T29_ _ftTP_(){return(_T29_)0;}
	T30 LevelColor;
	virtual void _callback_(int r) {return;}

	public: /* Constructor *
	MDL_TrailingStop2()
	{
		GroupMode = (string)"group";
		Group = (string)"";
		SymbolMode = (string)"symbol";
		Symbol = (string)CurrentSymbol();
		BuysOrSells = (string)"both";
		TrailWhat = (int)1;
		TrailingReferencePrice = (int)0;
		TrailingStopMode = (string)"fixed";
		tStopPips = (double)40.0;
		tStopMoney = (double)10.0;
		tStopMultiple = (string)"20/5, 30/10";
		tStopPercentTP = (double)100.0;
		tStopPercentProfit = (double)50.0;
		TrailingStepMode = (string)"fixed";
		tStepPips = (double)1.0;
		tStepPercentTS = (double)10.0;
		TrailingStartMode = (string)"none";
		tStartPips = (double)10.0;
		tStartPercentTS = (double)100.0;
		tStartPercentSL = (double)10.0;
		tStartPercentTP = (double)10.0;
		TrailingTPmode = (string)"none";
		tTPpips = (double)20.0;
		tTPpercentTS = (double)200.0;
		LevelColor = (color)clrDeepPink;
	}

	public: /* The main method *
	virtual void _execute_()
	{
		int total = TradesTotal();

		for (int index = 0; index < total; index++)
		{
			if (TradeSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells))
			{
				string symbol     = OrderSymbol();
				double ask        = SymbolInfoDouble(symbol, SYMBOL_ASK);
				double bid        = SymbolInfoDouble(symbol, SYMBOL_BID);
				double stopslevel = (double)SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL);
				int digits        = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
				int polarity      = 1;   // 1 = buy, -1 = sell
				double askbid     = ask; // could be Ask or Bid
				double bidask     = bid; // the opposite of askbid
				double sltp       = 0;   // could be SL or TP
				double tpsl       = 0;   // the opposite of sltp
				double fsl        = 0;   // Freeze Level
				double limit      = 0;
				double t_stop     = 0;   // trailing STOP
				double t_start    = 0;   // trailing START
				double t_step     = 0;   // trailing STEP
				double t_opp      = 0;   // trailing Opposite (TP when trailing SL or SL when trailing TP)

				if (TrailWhat > 0) {
					sltp = attrStopLoss();
					tpsl = attrTakeProfit();
				}
				else {
					sltp = attrTakeProfit();
					tpsl = attrStopLoss();
				}

				if (OrderType() == 0) {
					polarity = 1;

					if (TrailingReferencePrice == 1)
					{
						askbid = bid;
						bidask = ask;
					}
				}
				else if (OrderType() == 1) {
					polarity = -1;
					askbid   = bid;
					bidask   = ask;

					if (TrailingReferencePrice == 1) {
						askbid = ask;
						bidask = bid;
					}
				}

				if (TrailingReferencePrice == 2) {
					askbid = (ask + bid) / 2;
					bidask = (ask + bid) / 2;
				}

				     if (TrailingStopMode == "fixed")         {t_stop = toDigits(tStopPips, symbol);} 
				else if (TrailingStopMode == "percentTP")     {t_stop = (MathAbs(OrderOpenPrice() - tpsl)) * (tStopPercentTP / 100);}
				else if (TrailingStopMode == "percentProfit") {t_stop = (MathAbs(askbid - OrderOpenPrice())) * (tStopPercentProfit / 100);}
				else if (TrailingStopMode == "dynamicSize")   {t_stop = toDigits(_ftStop_(), symbol);}
				else if (TrailingStopMode == "dynamicDigits") {t_stop = _ftDigits_();}
				else if (TrailingStopMode == "dynamic")
				{

					t_stop = _ftStop_();
					t_stop = (polarity == 1) ? ask - t_stop : t_stop - bid;
				}
				else if (TrailingStopMode == "money")
				{
					t_stop = tStopMoney;

					double lotsize   = SymbolInfoDouble(symbol, SYMBOL_TRADE_CONTRACT_SIZE);
					double tickvalue = (SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE) / SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE)) * SymbolInfoDouble(symbol, SYMBOL_POINT);
					t_stop = t_stop /  (OrderLots() * PipValue(symbol));

					t_stop = toDigits(t_stop / tickvalue, symbol);
				}

				     if (TrailingStartMode == "none")             {t_start = -EMPTY_VALUE;}
				else if (TrailingStartMode == "zero")             {t_start = 0;}
				else if (TrailingStartMode == "fixed")            {t_start = toDigits(tStartPips, symbol);}
				else if (TrailingStartMode == "percentTS")        {t_start = t_stop * (tStartPercentTS / 100);}
				else if (TrailingStartMode == "percentTP")        {t_start = (MathAbs(OrderOpenPrice() - tpsl)) * (tStartPercentTP / 100);}
				else if (TrailingStartMode == "percentSL")        {t_start = (MathAbs(OrderOpenPrice() - sltp)) * (tStartPercentSL / 100);}
				else if (TrailingStartMode == "function")         {t_start = toDigits(_ftStart_(), symbol);}
				else if (TrailingStartMode == "functionFraction") {t_start = _ftStartFraction_();}

				     if (TrailingStepMode == "fixed")     {t_step = toDigits(tStepPips, symbol);}
				else if (TrailingStepMode == "percentTS") {t_step = t_stop * (tStepPercentTS / 100);}

				     if (TrailingTPmode == "none")      {t_opp = tpsl;}
				else if (TrailingTPmode == "clear")     {t_opp = 0;}
				else if (TrailingTPmode == "fixed")     {t_opp = TrailWhat * (OrderOpenPrice() + (polarity * toDigits(tTPpips, symbol)));}
				else if (TrailingTPmode == "percentTS") {t_opp = TrailWhat * (OrderOpenPrice() + (polarity * toDigits(t_stop * (tTPpercentTS / 100), symbol)));}
				else if (TrailingTPmode == "function")  {t_opp = _ftTP_();}

				if (TrailingStopMode == "multiple")
				{
					bool next = false;
					string tmp1[];
					string tmp2[];

					StringExplode(",", tStopMultiple, tmp1);

					for (int i = ArraySize(tmp1)-1; i >= 0; i--)
					{
						StringExplode("/", tmp1[i], tmp2);

						if (ArraySize(tmp2) != 2) {continue;}

						double new_start = toDigits(StringToDouble(StringTrim(tmp2[0])), symbol);

						if (new_start < t_start) {continue;}

						double diff = NormalizeDouble(askbid - OrderOpenPrice(), digits);

						if (polarity * TrailWhat * diff >= new_start)
						{

							t_start = new_start;
							t_stop  = polarity * TrailWhat * diff - toDigits(StringToDouble(StringTrim(tmp2[1])), symbol);

							next = true;
							break;
						}
					}

					if (next == false) {continue;}
				}

				stopslevel   = stopslevel * SymbolInfoDouble(symbol, SYMBOL_POINT);

				if (t_stop <= 0) {continue;}

				if (OrderType() == 0 && TrailWhat * (askbid - OrderOpenPrice()) > t_start)
				{
					if ((TrailWhat * (askbid - sltp) >= t_stop + t_step) || sltp == 0)
					{

						fsl   = MathAbs(askbid - t_stop);
						limit = bidask - stopslevel * TrailWhat;

						if (fsl > limit) {fsl = limit;}

						if (TrailWhat == 1) // trail SL
						{
							if (sltp == 0 || sltp < fsl) {
								ModifyStops(OrderTicket(), askbid - t_stop, t_opp, LevelColor);
							}
						}
						else { // trail TP
							if (sltp == 0 || sltp > fsl) {
								ModifyStops(OrderTicket(), t_opp, askbid + t_stop, LevelColor);
							}
						}
					}
				}
				else if (OrderType() == 1 && TrailWhat * (OrderOpenPrice() - askbid) > t_start)
				{
					if ((TrailWhat * (sltp - askbid) >= t_stop + t_step) || sltp == 0)
					{

						fsl   = MathAbs(askbid + t_stop);
						limit = bidask + stopslevel * TrailWhat;

						if (fsl < limit) {fsl = limit;}

						if (TrailWhat == 1)
						{ // trail SL
							if (sltp == 0 || sltp > fsl)
							{
								ModifyStops(OrderTicket(), askbid + t_stop, t_opp, LevelColor);
							}
						}
						else
						{ // trail TP
							if (sltp == 0 || sltp < fsl)
							{
								ModifyStops(OrderTicket(), t_opp, askbid - t_stop, LevelColor);
							}
						}
					}
				}
			}
		}

		_callback_(1);
	}
};

template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename _T9_,typename T10,typename _T10_,typename T11,typename _T11_,typename T12>
class MDL_TrailingPendingOrders: public BlockCalls
{
	public: /* Input Parameters 
	T1 GroupMode;
	T2 Group;
	T3 SymbolMode;
	T4 Symbol;
	T5 BuysOrSells;
	T6 LimitsOrStops;
	T7 TrailingDistanceMode;
	T8 tDistancePips;
	T9 dtDistancePips; virtual _T9_ _dtDistancePips_(){return(_T9_)0;}
	T10 dtDistanceDigits; virtual _T10_ _dtDistanceDigits_(){return(_T10_)0;}
	T11 dtLevel; virtual _T11_ _dtLevel_(){return(_T11_)0;}
	T12 tStepPips;
	virtual void _callback_(int r) {return;}

	public: /* Constructor *
	MDL_TrailingPendingOrders()
	{
		GroupMode = (string)"group";
		Group = (string)"";
		SymbolMode = (string)"symbol";
		Symbol = (string)CurrentSymbol();
		BuysOrSells = (string)"both";
		LimitsOrStops = (string)"both";
		TrailingDistanceMode = (string)"fixed";
		tDistancePips = (double)30.0;
		tStepPips = (double)1.0;
	}

	public: /* The main method *
	virtual void _execute_()
	{
		for (int index = OrdersTotal()-1; index >= 0; index--)
		{
			if (PendingOrderSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells, LimitsOrStops))
			{
				string symbol   = OrderSymbol();
				double price    = (IsOrderTypeBuy()) ? SymbolAsk(symbol) : SymbolBid(symbol);
				double distance = 0;
				int digits      = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

				     if (TrailingDistanceMode == "fixed")         distance = toDigits(tDistancePips, symbol);
				else if (TrailingDistanceMode == "dynamic")       distance = price - _dtLevel_();
				else if (TrailingDistanceMode == "dynamicPips")   distance = toDigits(_dtDistancePips_(), symbol);
				else if (TrailingDistanceMode == "dynamicDigits") distance = _dtDistanceDigits_();

				distance = NormalizeDouble(MathAbs(distance), digits);

				double old_op = 0, old_sl = 0, old_tp = 0;
				double new_op = 0, new_sl = 0, new_tp = 0;

				if (MathAbs(price - OrderOpenPrice()) >= MathAbs(distance + toDigits(tStepPips, symbol)))         
				{
					old_sl = attrStopLoss();
					old_tp = attrTakeProfit();
					old_op = OrderOpenPrice();

					if (IsOrderTypeBuy() == true)
					{
						new_op = IsOrderTypeStop() ? price + distance : price - distance;

						if (old_sl > 0) new_sl = new_op - (old_op - old_sl);
						if (old_tp > 0) new_tp = new_op + (old_tp - old_op);
					}
					else
					{
						new_op = IsOrderTypeStop() ? price - distance : price + distance;

						if (old_sl > 0) new_sl = new_op + (old_sl - old_op);
						if (old_tp > 0) new_tp = new_op - (old_op - old_tp);
					}

					ModifyOrder(OrderTicket(), new_op, new_sl, new_tp, 0, 0, OrderExpiration(), clrBlack);
				}
			}
		}

		_callback_(1);
	}
};

template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6>
class MDL_NoPendingOrders: public BlockCalls
{
	public: /* Input Parameters *
	T1 GroupMode;
	T2 Group;
	T3 SymbolMode;
	T4 Symbol;
	T5 BuysOrSells;
	T6 LimitsOrStops;
	virtual void _callback_(int r) {return;}

	public: /* Constructor *
	MDL_NoPendingOrders()
	{
		GroupMode = (string)"group";
		Group = (string)"";
		SymbolMode = (string)"symbol";
		Symbol = (string)CurrentSymbol();
		BuysOrSells = (string)"both";
		LimitsOrStops = (string)"both";
	}

	public: /* The main method *
	virtual void _execute_()
	{
		bool exist = false;

		for (int index = OrdersTotal()-1; index >= 0; index--)
		{
			if (PendingOrderSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells, LimitsOrStops))
			{
				exist = true;
				break;
			}
		}

		if (exist == false) {_callback_(1);} else {_callback_(0);}
	}
};

template<typename T1,typename _T1_,typename T2,typename T3,typename _T3_,typename T4>
class MDL_Condition: public BlockCalls
{
	public: /* Input Parameters *
	T1 Lo; virtual _T1_ _Lo_(){return(_T1_)0;}
	T2 compare;
	T3 Ro; virtual _T3_ _Ro_(){return(_T3_)0;}
	T4 crosswidth;
	virtual void _callback_(int r) {return;}

	public: /* Constructor *
	MDL_Condition()
	{
		compare = (string)">";
		crosswidth = (int)1;
	}

	public: /* The main method *
	virtual void _execute_()
	{
		bool output1 = false, output2 = false; // output 1 and output 2
		int crossover = 0;

		if (compare == "x>" || compare == "x<") {crossover = 1;}

		for (int i = 0; i <= crossover; i++)
		{

			FXD_MORE_SHIFT = i * crosswidth;
			_T1_ lo = _Lo_();
			if (MathAbs(lo) == EMPTY_VALUE) {return;}

			FXD_MORE_SHIFT = i * crosswidth;
			_T3_ ro = _Ro_();
			if (MathAbs(ro) == EMPTY_VALUE) {return;}

			if (CompareValues(compare, lo, ro))
			{
				if (i == 0)
				{
					output1 = true;
				}
			}
			else
			{
				if (i == 0)
				{
					output2 = true;
				}
				else
				{
					output2 = false;
				}
			}

			if (crossover == 1)
			{
				if (CompareValues(compare, ro, lo))
				{
					if (i == 0)
					{
						output2 = true;
					}
				}
				else
				{
					if (i == 1)
					{
						output1 = false;
					}
				}
			}
		}

		FXD_MORE_SHIFT = 0; // reset

			  if (output1 == true) {_callback_(1);}
		else if (output2 == true) {_callback_(0);}
	}
};

class MDL_Pass: public BlockCalls
{
	virtual void _callback_(int r) {return;}

	public: /* The main method *
	virtual void _execute_()
	{
		_callback_(1);
	}
};

template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename T10,typename T11,typename T12,typename T13,typename T14,typename 

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

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

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

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

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

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

Стоимость полного кода
5 799,50₽ ≈ $70.88