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

XMT-Scalper

xmt-scalper_v2.522.mq4
Вы автор или правообладатель?

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

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

О программе

XMT-Scalper — это Expert Advisor (советник) для платформы MetaTrader 4, написанный на языке MQL4. Программа предназначена для автоматической торговли на основе стратегии тикового скальпинга с использованием канала цены. Стратегия основана на обнаружении пробоя ценового канала и открытии сделок в направлении реверса от этого пробоя.

В качестве канала цены используется один из трёх индикаторов: скользящая средняя (Moving Average), полосы Боллинджера (Bollinger Bands) или каналы Envelopes, выбор которого настраивается пользователем. Торговые сигналы формируются при выходе цены за пределы канала с дополнительной проверкой волатильности. Программа поддерживает как рыночные ордера, так и отложенные BUYSTOP и SELLSTOP.

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

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

НастройкаОписание
Configuration Конфигурация — Группа настроек конфигурации
ReverseTrade Обратная торговля — Если TRUE, торговля идёт в противоположном направлении
Magic Магический номер — Если меньше 0, магический номер рассчитывается автоматически
OrderCmt Комментарий ордера — Комментарий, отображаемый в истории сделок
ECN_Mode ECN-режим — Для брокеров, не принимающих SL и TP одновременно с ордером
Debug Отладка — Вывод подробных логов для отладки
Verbose Подробный лог — Дополнительная информация в журнале Expert
TradingSettings Торговые настройки — Группа торговых параметров
TimeFrame Таймфрейм — Таймфрейм торговли должен совпадать с таймфреймом графика
MaxSpread Максимальный спред — Максимально допустимый спред в пунктах
MaxExecution Максимальное время исполнения — Максимально допустимое среднее время исполнения в мс
MaxExecutionMinutes Интервал измерения исполнения — Периодичность отправки фиктивных ордеров для измерения скорости
StopLoss Стоп-лосс — Расстояние стоп-лосса в пунктах
TakeProfit Тейк-профит — Расстояние тейк-профита в пунктах
AddPriceGap Дополнительный зазор — Дополнительный зазор в пунктах для предотвращения ошибки 130
TrailingStart Начало трейлинга — Начало трейлинга прибыли в пунктах
Commission Комиссия — Комиссия брокера в USD за 1 лот
Slippage Допуск проскальзывания — Максимально допустимое проскальзывание в пунктах
MinimumUseStopLevel Минимальный стоп-левел — Минимальный стоп-левел, используемый как максимум между этим значением и стоп-левелом брокера
VolatilitySettings Настройки волатильности — Группа настроек волатильности
UseDynamicVolatilityLimit Динамический лимит волатильности — Лимит рассчитывается на основе спреда и множителя
VolatilityMultiplier Множитель волатильности — Множитель для динамического расчёта лимита волатильности
VolatilityLimit Лимит волатильности — Фиксированное значение лимита волатильности
UseVolatilityPercentage Процентный лимит волатильности — Если TRUE, цена должна пробить порог в процентах
VolatilityPercentageLimit Лимит процента волатильности — Процентное отклонение разницы iHigh-iLow от лимита волатильности
UseIndicatorSet Набор индикаторов — Группа выбора индикатора
UseIndicatorSwitch Выбор индикатора — Выбор индикатора для канала цены
Indicatorperiod Период индикатора — Период в барах для индикатора
BBDeviation Отклонение Боллинджера — Отклонение для индикатора iBands
EnvelopesDeviation Отклонение каналов — Отклонение для индикатора iEnvelopes
OrderExpireSeconds Время жизни ордера — Ордеры удаляются через указанное количество секунд
Money_Management Управление капиталом — Группа настроек управления капиталом
MoneyManagement Управление капиталом — Если TRUE, размер лота рассчитывается автоматически на основе риска
MinLots Минимальный лот — Минимальный размер лота для торговли
MaxLots Максимальный лот — Максимально допустимый размер лота
Risk Риск — Процент риска от equity для расчёта размера лота
ManualLotsize Ручной размер лота — Фиксированный размер лота при отключённом управлении капиталом
MinMarginLevel Минимальный уровень маржи — Минимально допустимый уровень маржи для открытия позиций
Screen_Shooter Скриншотер — Группа настроек сохранения скриншотов
TakeShots Сделать скриншот — Сохранять скриншоты для каждого открытого ордера
DelayTicks Задержка тиков — Задержка в тиках после нового бара
ShotsPerBar Скриншотов на бар — Количество скриншотов на один бар
DisplayGraphics Отображение графики — Настройки цветов и отображения информации на графике
Heading_Size Размер заголовка — Размер шрифта для заголовка
Text_Size Размер текста — Размер шрифта для текстовых строк
Color_Heading Цвет заголовка — Цвет текста заголовка
Color_Section1 Цвет секции 1 — Цвет текстовых строк первой секции
Color_Section2 Цвет секции 2 — Цвет текстовых строк второй секции
Color_Section3 Цвет секции 3 — Цвет текстовых строк третьей секции
Color_Section4 Цвет секции 4 — Цвет текстовых строк четвёртой секции
Получить полный код

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

#property version       "2.522"

#property description   "This is a FREE Shareware Expert Advisor for MetaTrader 4."
#property description   "Please do not remove the property section and version history."
#property description   "XMT-Scalper is a Tick Scalper originally made for EURUSD M1, but can also work on other pairs, Gold and CFD's and timeframes"
#property description   "It's extremely broker sensitive and requires tight spread when used on M1."
#property description   "Read the PDF-file for explanations and settings."
#property strict

#include "stdlib.mqh"        // "stdlib.mqh" or "<sdlib.mqh> 
#include "stderror.mqh"      // "stderror.mqh" or <stderror.mqh>

extern string	Configuration 					= "==== Configuration ====";
extern bool 	ReverseTrade 					= FALSE; // ReverseTrade: If TRUE, then trade in opposite direction
extern int 		Magic 							= -1;	// Magic: If set to a number less than 0 it will calculate MagicNumber automatically
extern string 	OrderCmt 						= "XMT-Scalper 2.522"; // OrderCmt. Trade comments that appears in the Trade and Account History tab
extern bool 	ECN_Mode 						= FALSE;	// ECN_Mode: True for brokers that don't accept SL and TP to be sent at the same time as the order
extern bool 	Debug 							= FALSE;	// Debug: Print huge log files with info, only for debugging purposes
extern bool 	Verbose 							= FALSE;	// Verbose: Additional log information printed in the Expert tab
extern string 	TradingSettings 				= "==== Trade settings ====";
extern ENUM_TIMEFRAMES TimeFrame          = PERIOD_M1; // TimeFrame: Trading timeframe must matrch the timeframe of the chart
extern double 	MaxSpread 						= 30.0; // MaxSprea: Max allowed spread in points (1 / 10 pip)
extern int 		MaxExecution 					= 0; // MaxExecution: Max allowed average execution time in ms (0 means no restrictions)
extern int 		MaxExecutionMinutes 			= 5; // MaxExecutionMinutes: How often in minutes should fake orders be sent to measure execution speed
extern double 	StopLoss 						= 60;	// StopLoss: SL from as many points. Default 60 (= 6 pips)
extern double 	TakeProfit 						= 100; // TakeProfit: TP from as many points. Default 100 (= 10 pip)
extern double 	AddPriceGap 					= 0; // AddPriceGap: Additional price gap in points added to SL and TP in order to avoid Error 130
extern double 	TrailingStart 					= 20;	// TrailingStart: Start trailing profit from as so many points. 
extern double 	Commission 						= 0; // Commission: Some broker accounts charge commission in USD per 1.0 lot. Commission in dollar per lot
extern int 		Slippage 						= 3; // Slippage: Maximum allowed Slippage of price in points
extern double 	MinimumUseStopLevel 			= 0; // MinimumUseStopLevel: Stoplevel to use will be max value of either this value or broker stoplevel 
extern string 	VolatilitySettings 			= "==== Volatility Settings ====";
extern bool 	UseDynamicVolatilityLimit 	= TRUE; // UseDynamicVolatilityLimit: Calculated based on INT (spread * VolatilityMultiplier)
extern double 	VolatilityMultiplier 		= 125; // VolatilityMultiplier: A multiplier that only is used if UseDynamicVolatilityLimit is set to TRUE
extern double 	VolatilityLimit 				= 180; // VolatilityLimit: A fix value that only is used if UseDynamicVolatilityLimit is set to FALSE
extern bool 	UseVolatilityPercentage 	= TRUE; // UseVolatilityPercentage: If true, then price must break out more than a specific percentage
extern double 	VolatilityPercentageLimit	= 0; // VolatilityPercentageLimit: Percentage of how much iHigh-iLow difference must differ from VolatilityLimit. 
extern string 	UseIndicatorSet 				= "=== Indicators: 1 = Moving Average, 2 = BollingerBand, 3 = Envelopes";
extern int 		UseIndicatorSwitch 			= 1; // UseIndicatorSwitch: Choose of indicator for price channel. 
extern int 		Indicatorperiod 				= 3; // Indicatorperiod: Period in bars for indicator
extern double 	BBDeviation 					= 2.0; // BBDeviation: Deviation for the iBands indicator only
extern double 	EnvelopesDeviation 			= 0.07; // EnvelopesDeviation: Deviation for the iEnvelopes indicator only
extern int 		OrderExpireSeconds 			= 3600; // OrderExpireSeconds: Orders are deleted after so many seconds
extern string 	Money_Management 				= "==== Money Management ====";
extern bool 	MoneyManagement 				= TRUE; // MoneyManagement: If TRUE then calculate lotsize automaticallay based on Risk, if False then use ManualLotsize below
extern double 	MinLots 							= 0.01; // MinLots: Minimum lot-size to trade with
extern double 	MaxLots 							= 100.0;	// MaxLots : Maximum allowed lot-size to trade with
extern double 	Risk 								= 2.0; // Risk: Risk setting in percentage, For 10.000 in Equity 10% Risk and 60 StopLoss lotsize = 16.66
extern double 	ManualLotsize 					= 0.1; // ManualLotsize: Fix lot size to trade with if MoneyManagement above is set to FALSE
extern double 	MinMarginLevel 				= 100; // MinMarginLevel: Lowest allowed Margin level for new positions to be opened 
extern string 	Screen_Shooter 				= "==== Screen Shooter ====";
extern bool 	TakeShots 						= FALSE; // TakeShots: Save screen shots for each opened order
extern int 		DelayTicks 						= 1; // DelayTicks: Delay so many ticks after new bar
extern int 		ShotsPerBar 					= 1; // ShotsPerBar: How many screen shots per bar
extern string 	DisplayGraphics				= "=== Display Graphics ==="; // Colors for sub_Display at upper left
extern int 		Heading_Size 					= 13;  // Heading_Size: Font size for headline
extern int 		Text_Size 						= 12;  // Text_Size: Font size for texts
extern color 	Color_Heading 					= Lime;	 // Color for text lines
extern color 	Color_Section1 				= Yellow; // Color for text lines
extern color 	Color_Section2 				= Aqua;	 // Color for text lines
extern color 	Color_Section3 				= Orange; // Color for text lines
extern color 	Color_Section4 				= Magenta;// Color for text lines

string EA_version = "XMT-Scalper v. 2.522";

datetime StartTime;			// Initial time
datetime LastTime;   		// For measuring tics

int BrokerDigits = 0;		// Nnumber of digits that the broker uses for this currency pair
int GlobalError = 0;			// To keep track on number of added errors
int TickCounter = 0;			// Counting tics
int UpTo30Counter = 0;		// For calculating average spread
int Execution = -1;			// For Execution speed, -1 means no speed
int Avg_execution = 0;		// Average Execution speed
int Execution_samples = 0;	// For calculating average Execution speed
int Leverage;					// Account Leverage in percentage
int Err_unchangedvalues;	// Error count for unchanged values (modify to the same values)
int Err_busyserver;			// Error count for busy server
int Err_lostconnection;		// Error count for lost connection
int Err_toomanyrequest;		// Error count for too many requests
int Err_invalidprice;		// Error count for invalid price
int Err_invalidstops;		// Error count for invalid SL and/or TP
int Err_invalidtradevolume;// Error count for invalid lot size
int Err_pricechange;			// Error count for change of price
int Err_brokerbuzy;			// Error count for broker is buzy
int Err_requotes;				// Error count for requotes
int Err_toomanyrequests;	// Error count for too many requests
int Err_trademodifydenied;	// Error count for modify orders is denied
int Err_tradecontextbuzy;	// error count for trade context is buzy
int SkippedTicks = 0;		// Used for simulation of latency during backtests, how many tics that should be skipped
int Ticks_samples = 0;		// Used for simulation of latency during backtests, number of tick samples
int Tot_closed_pos;			// Number of closed positions for this EA
int Tot_Orders; 				// Number of open orders disregarding of magic and pairs
int Tot_open_pos;				// Number of open positions for this EA

double LotBase;				// Amount of money in base currency for 1 lot
double Tot_open_profit;		// A summary of the current open profit/loss for this EA
double Tot_open_lots;		// A summary of the current open lots for this EA
double Tot_open_swap;		// A summary of the current charged swaps of the open positions for this EA
double Tot_open_commission;// A summary of the currebt charged commission of the open positions for this EA
double G_equity;				// Current equity for this EA
double Changedmargin;		// Free margin for this account
double Tot_closed_lots;		// A summary of the current closed lots for this EA
double Tot_closed_profit;	// A summary of the current closed profit/loss for this EA 
double Tot_closed_swap;		// A summary of the current closed swaps for this EA
double Tot_closed_comm;		// A summary of the current closed commission for this EA
double G_balance = 0;		// Balance for this EA
double Array_spread[30];	// Store spreads for the last 30 tics
double LotSize;				// Lotsize
double Highest;				// LotSize indicator value
double Lowest;					// Lowest indicator value
double StopLevel;				// Broker StopLevel
double StopOut;				// Broker stoput percentage
double LotStep;				// Broker LotStep
double MarginForOneLot;		// Margin required for 1 lot
double Avg_tickspermin;		// Used for simulation of latency during backtests
double MarginFree;         // Free margin in percentage

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

void OnDeinit( const int reason )
{
	string text = "";

	sub_printsumofbrokererrors();

   sub_DeleteDisplay();	

	sub_CheckThroughAllClosedOrders();

	if ( IsTesting ( ) == TRUE )
	{
		Print ( "Total closed lots = ", DoubleToStr ( Tot_closed_lots, 2 ) );
		Print ( "Total closed swap = ", DoubleToStr ( Tot_closed_swap, 2 ) );
		Print ( "Total closed commission = ", DoubleToStr ( Tot_closed_comm, 2 ) );

	   if ( MaxExecution > 0 )
	   {
		   text = text + "During backtesting " + (string) SkippedTicks + " number of ticks was ";
		   text = text + "skipped to simulate latency of up to " + (string) MaxExecution + " ms";
		   sub_printandcomment ( text );
	   }		
	}

	Print ( EA_version, " has been deinitialized!" );

   Print ( __FUNCTION__, "_Uninitalization reason code = ", reason );

   Print ( __FUNCTION__, "_UninitReason = ", sub_UninitReasonText( _UninitReason ) );

}

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

void sub_trade() 
{
   string textstring;
	string pair;
	string indy;

	datetime orderexpiretime;

	bool select = FALSE;
   bool wasordermodified = FALSE;
	bool ordersenderror = FALSE;	
	bool isbidgreaterthanima = FALSE;	  
	bool isbidgreaterthanibands = FALSE;
	bool isbidgreaterthanenvelopes = FALSE; 
	bool isbidgreaterthanindy = FALSE; 

   int orderticket;
	int loopcount2;	
	int loopcount1;	
	int pricedirection;	
   int counter1;
   int counter2;	
	int askpart;
	int bidpart;

	double ask;
	double bid;		
   double askplusdistance;
   double bidminusdistance;
	double volatilitypercentage = 0;
	double orderprice;
   double orderstoploss;
   double ordertakeprofit;
	double ihigh;	
   double ilow;	
	double imalow = 0;	
   double imahigh = 0;
   double imadiff;	
   double ibandsupper = 0;
   double ibandslower = 0;	
   double ibandsdiff;
   double envelopesupper = 0;
   double envelopeslower = 0;
   double envelopesdiff;	
   double volatility;
   double spread;
   double avgspread;	
   double realavgspread;
	double fakeprice;
	double sumofspreads;	
	double askpluscommission;
   double bidminuscommission;	
   double skipticks;
	double am = 0.000000001;  // Set variable to a very small number
	double marginlevel;
	double tmpexecution;

	MarginFree = AccountFreeMargin();	

	if ( AccountMargin() != 0 )
		am = AccountMargin();
	marginlevel = AccountEquity() / am * 100;	

	if ( marginlevel < MinMarginLevel )
	{
      Print ( "Warning! Free Margin " + DoubleToStr ( marginlevel, 2 ) + " is lower than MinMarginLevel!" );
		Alert ( "Warning! Free Margin " + DoubleToStr ( marginlevel, 2 ) + " is lower than MinMarginLevel!" );
      return;	
	}	

	if ( LastTime < Time[0] ) 
	{

		if ( Ticks_samples < 10 ) 
         Ticks_samples ++; 
		Avg_tickspermin = Avg_tickspermin + ( TickCounter - Avg_tickspermin ) / Ticks_samples;

		LastTime = Time[0];
		TickCounter = 0;
	} 

	else 
		TickCounter ++;

	if ( IsTesting() && MaxExecution != 0 && Execution != -1 ) 
	{
		skipticks = MathRound ( Avg_tickspermin * MaxExecution / ( 60 * 1000 ) );
		if ( SkippedTicks >= skipticks ) 
		{
			Execution = -1;
			SkippedTicks = 0;
		}
		else 
		{
			SkippedTicks ++;
		}
	}

	ask = MarketInfo ( Symbol(), MODE_ASK );
	bid = MarketInfo ( Symbol(), MODE_BID );

	ihigh = iHigh ( Symbol(), TimeFrame, 0 );
	ilow = iLow ( Symbol(), TimeFrame, 0 );
	volatility = ihigh - ilow;  

	indy = "";

	if ( UseIndicatorSwitch == 1 || UseIndicatorSwitch == 4 )
	{
		imalow = iMA ( Symbol(), TimeFrame, Indicatorperiod, 0, MODE_LWMA, PRICE_LOW, 0 );
		imahigh = iMA ( Symbol(), TimeFrame, Indicatorperiod, 0, MODE_LWMA, PRICE_HIGH, 0 );
		imadiff = imahigh - imalow;
		isbidgreaterthanima = bid >= imalow + imadiff / 2.0;  	
		indy = "iMA_low: " + sub_dbl2strbrokerdigits ( imalow ) + ", iMA_high: " + sub_dbl2strbrokerdigits ( imahigh ) + ", iMA_diff: " + sub_dbl2strbrokerdigits ( imadiff );
	}

	if ( UseIndicatorSwitch == 2 )
	{
		ibandsupper = iBands ( Symbol(), TimeFrame, Indicatorperiod, BBDeviation, 0, PRICE_OPEN, MODE_UPPER, 0 );
		ibandslower = iBands ( Symbol(), TimeFrame, Indicatorperiod, BBDeviation, 0, PRICE_OPEN, MODE_LOWER, 0 );
		ibandsdiff = ibandsupper - ibandslower;
		isbidgreaterthanibands = bid >= ibandslower + ibandsdiff / 2.0;
		indy = "iBands_upper: " + sub_dbl2strbrokerdigits ( ibandsupper ) + ", iBands_lower: " + sub_dbl2strbrokerdigits ( ibandslower ) + ", iBands_diff: " + sub_dbl2strbrokerdigits ( ibandsdiff );
	}

	if ( UseIndicatorSwitch == 3 )
	{
		envelopesupper = iEnvelopes ( Symbol(), TimeFrame, Indicatorperiod, MODE_LWMA, 0, PRICE_OPEN, EnvelopesDeviation, MODE_UPPER, 0 );
		envelopeslower = iEnvelopes ( Symbol(), TimeFrame, Indicatorperiod, MODE_LWMA, 0, PRICE_OPEN, EnvelopesDeviation, MODE_LOWER, 0 );
		envelopesdiff = envelopesupper - envelopeslower;
		isbidgreaterthanenvelopes = bid >= envelopeslower + envelopesdiff / 2.0;  
		indy = "iEnvelopes_upper: " + sub_dbl2strbrokerdigits ( envelopesupper ) + ", iEnvelopes_lower: " + sub_dbl2strbrokerdigits ( envelopeslower ) + ", iEnvelopes_diff: " + sub_dbl2strbrokerdigits ( envelopesdiff) ;		
	}	

	isbidgreaterthanindy = FALSE;	

	pricedirection = 0;

	if ( UseIndicatorSwitch == 1 && isbidgreaterthanima == TRUE )
	{
		isbidgreaterthanindy = TRUE; 
		Highest = imahigh;
		Lowest = imalow;
	}

	else if ( UseIndicatorSwitch == 2 && isbidgreaterthanibands == TRUE )
	{
		isbidgreaterthanindy = TRUE;
		Highest = ibandsupper;
		Lowest = ibandslower; 
	}

	else if ( UseIndicatorSwitch == 3 && isbidgreaterthanenvelopes == TRUE )
	{
		isbidgreaterthanindy = TRUE; 
		Highest = envelopesupper;
		Lowest = envelopeslower;
	}	

	spread = ask - bid;

	LotSize = sub_calculatelotsize();

	if ( OrderExpireSeconds != 0 )
		orderexpiretime = TimeCurrent() + OrderExpireSeconds;		
	else
		orderexpiretime = 0;

	ArrayCopy ( Array_spread, Array_spread, 0, 1, 29 );
	Array_spread[29] = spread;
	if ( UpTo30Counter < 30 ) 
		UpTo30Counter ++;
	sumofspreads = 0;
	loopcount2 = 29;
	for ( loopcount1 = 0; loopcount1 < UpTo30Counter; loopcount1 ++ ) 
	{
		sumofspreads += Array_spread[loopcount2];
		loopcount2 --;
	}

	avgspread = sumofspreads / UpTo30Counter;

	askpluscommission = sub_normalizebrokerdigits ( ask + Commission );
	bidminuscommission = sub_normalizebrokerdigits ( bid - Commission );
	realavgspread = avgspread + Commission;

	if ( UseDynamicVolatilityLimit == TRUE )
		VolatilityLimit = realavgspread * VolatilityMultiplier;

	if ( volatility && VolatilityLimit && Lowest && Highest && UseIndicatorSwitch != 4 )
	{ 

		if ( volatility > VolatilityLimit )
		{

			volatilitypercentage = volatility / VolatilityLimit;

			if ( ( UseVolatilityPercentage == FALSE ) || ( UseVolatilityPercentage == TRUE && volatilitypercentage > VolatilityPercentageLimit ) )
			{
				if ( bid < Lowest ) 
				{
					if ( ReverseTrade == FALSE )       	
						pricedirection = -1; // BUY or BUYSTOP
					else // ReverseTrade == true
						pricedirection = 1; // SELL or SELLSTOP
				}
				else if ( bid > Highest )    	
				{
					if ( ReverseTrade == FALSE )
						pricedirection = 1;  // SELL or SELLSTOP
					else // ReverseTrade == true
						pricedirection = -1; // BUY or BUYSTOP
				}
			}
		}

		else
			volatilitypercentage = 0;
	}    

	if ( AccountEquity() <= 0.0 ) 
	{
		Print ( "ERROR -- Account Equity is " + DoubleToStr ( MathRound ( AccountEquity() ), 0 ) );
		return;
	}

	Execution = -1; 

	counter1 = 0;
	counter2 = 0;

	for ( loopcount2 = 0; loopcount2 < OrdersTotal(); loopcount2 ++ ) 
	{

		select = OrderSelect ( loopcount2, SELECT_BY_POS, MODE_TRADES );

		if ( OrderMagicNumber() == Magic && OrderCloseTime() == 0 ) 
		{

			if ( OrderSymbol() != Symbol() ) 
			{

				counter2 ++;
				continue;
			}

			switch ( OrderType() ) 
			{

			case OP_BUY:

				while ( TRUE )  
				{

					RefreshRates();

					orderstoploss = OrderStopLoss();
					ordertakeprofit = OrderTakeProfit();	

					if ( ordertakeprofit < sub_normalizebrokerdigits ( askpluscommission + TakeProfit * Point + AddPriceGap ) && askpluscommission + TakeProfit * Point + AddPriceGap - ordertakeprofit > TrailingStart ) 
					{

						orderstoploss = sub_normalizebrokerdigits ( bid - StopLoss * Point - AddPriceGap );
						ordertakeprofit = sub_normalizebrokerdigits ( askpluscommission + TakeProfit * Point + AddPriceGap );

						if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
						{

							Execution = (int) GetTickCount();

							wasordermodified = OrderModify ( OrderTicket(), 0, orderstoploss, ordertakeprofit, orderexpiretime, Lime );
						}

						if ( wasordermodified == TRUE ) 
						{ 

							Execution = (int) GetTickCount() - Execution;

							if ( TakeShots && !IsTesting() ) 
								sub_takesnapshot();

							break; 
						}

						else 
						{

							Execution = -1;

							sub_errormessages();

							if ( Debug || Verbose ) 
								Print ( "Order could not be modified because of ", ErrorDescription ( GetLastError() ) );

							if ( orderstoploss == 0 )

								wasordermodified = OrderModify ( OrderTicket(), 0, NormalizeDouble ( Bid - 30, BrokerDigits ), 0, 0, Red );
						}
					}	

					break; 
				}

				counter1 ++;

				break;

			case OP_SELL:

				while ( TRUE ) 
				{

					RefreshRates();

					orderstoploss = OrderStopLoss();
					ordertakeprofit = OrderTakeProfit();

					if ( ordertakeprofit > sub_normalizebrokerdigits ( bidminuscommission - TakeProfit * Point - AddPriceGap ) && ordertakeprofit - bidminuscommission + TakeProfit * Point - AddPriceGap > TrailingStart ) 
					{					

						orderstoploss = sub_normalizebrokerdigits ( ask + StopLoss * Point + AddPriceGap );
						ordertakeprofit = sub_normalizebrokerdigits ( bidminuscommission - TakeProfit * Point - AddPriceGap );

						if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
						{

							Execution = (int) GetTickCount(); 
							wasordermodified = OrderModify ( OrderTicket(), 0, orderstoploss, ordertakeprofit, orderexpiretime, Orange );
						}

						if ( wasordermodified == TRUE ) 
						{ 

							Execution = (int) GetTickCount() - Execution;

							if ( TakeShots && !IsTesting() ) 
								sub_takesnapshot();

							break;
						}

						else 
						{

							Execution = -1;

							sub_errormessages();

							if ( Debug || Verbose ) 
								Print ( "Order could not be modified because of ", ErrorDescription ( GetLastError() ) );

							Sleep ( 1000 ); 

							if ( orderstoploss == 0 )

								wasordermodified = OrderModify ( OrderTicket(), 0, NormalizeDouble ( Ask + 30, BrokerDigits), 0, 0, Red );
						}
					}	

					break; 
				}

				counter1 ++;

				break;

			case OP_BUYSTOP:

				if ( isbidgreaterthanindy == FALSE ) 
				{

					orderprice = sub_normalizebrokerdigits ( ask + StopLevel + AddPriceGap );
					orderstoploss = sub_normalizebrokerdigits ( orderprice - spread - StopLoss * Point - AddPriceGap );
					ordertakeprofit = sub_normalizebrokerdigits ( orderprice + Commission + TakeProfit * Point + AddPriceGap );

					while ( TRUE ) 
					{

						if ( orderprice < OrderOpenPrice() && OrderOpenPrice() - orderprice > TrailingStart ) 
						{

					   	if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
					   	{
								RefreshRates();

								Execution = (int) GetTickCount();
								wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, 0, Lime );
							}

							if ( wasordermodified == TRUE ) 
							{

								Execution = (int) GetTickCount() - Execution;

								if ( Debug || Verbose ) 
								   Print ( "Order executed in " + (string) Execution + " ms" );		   
							}

							else 
							{

								Execution = -1;

								sub_errormessages();
							}
						}

						break;
					}

					counter1 ++;
				} 

				else 

					select = OrderDelete ( OrderTicket() );

				break;

			case OP_SELLSTOP:

				if ( isbidgreaterthanindy == TRUE ) 
				{

					orderprice = sub_normalizebrokerdigits ( bid - StopLevel - AddPriceGap );
					orderstoploss = sub_normalizebrokerdigits ( orderprice + spread + StopLoss * Point + AddPriceGap );
					ordertakeprofit = sub_normalizebrokerdigits ( orderprice - Commission - TakeProfit * Point - AddPriceGap );									

					while ( TRUE ) 
					{

						if ( orderprice > OrderOpenPrice() && orderprice - OrderOpenPrice() > TrailingStart) 
						{

					   	if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
					   	{
								RefreshRates();

								Execution = (int) GetTickCount(); 
								wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, 0, Orange );
							}

							if ( wasordermodified == TRUE )
							{

								Execution = (int) GetTickCount() - Execution;

								if ( Debug || Verbose ) 
  									Print ( "Order executed in " + (string) Execution + " ms" );
							}

							else 
							{

								Execution = -1;

								sub_errormessages();
							}
						}

						break;
					}

					counter1 ++;
				} 

				else 
					select = OrderDelete ( OrderTicket() );
			} // end of switch
		}  // end if OrderMagicNumber
	} // end for loopcount2 - end of loop through open orders

	if ( GlobalError >= 0 || GlobalError == -2 ) 
	{
		bidpart = (int) NormalizeDouble ( bid / Point, 0 );
		askpart = (int) NormalizeDouble ( ask / Point, 0 );
		if ( bidpart % 10 != 0 || askpart % 10 != 0 ) 
			GlobalError = -1;
		else 
		{
			if ( GlobalError >= 0 && GlobalError < 10 ) 
				GlobalError ++;
			else 
				GlobalError = -2;
		}
	}

	ordersenderror = FALSE;

	if ( pricedirection != 0 && MaxExecution > 0 && Avg_execution > MaxExecution ) 
	{   
		pricedirection = 0; // Ignore the order opening triger
		if ( Debug || Verbose )
			Print ( "Server is too Slow. Average Execution: " + (string) Avg_execution );
	}

	askplusdistance = ask + StopLevel;
	bidminusdistance = bid - StopLevel;

	if ( counter1 == 0 && pricedirection != 0 && sub_normalizebrokerdigits ( realavgspread) <= sub_normalizebrokerdigits ( MaxSpread * Point ) && GlobalError == -1 ) 
	{		

		if ( pricedirection == -1 || pricedirection == 2 ) // Send a BUYSTOP
		{			

			orderprice = ask + StopLevel;

			if ( ECN_Mode == TRUE ) 
			{

				orderprice = askplusdistance;
				orderstoploss =  0;
				ordertakeprofit = 0;

				Execution = (int) GetTickCount(); 

				orderticket = OrderSend ( Symbol(), OP_BUYSTOP, LotSize, orderprice, Slippage, orderstoploss, ordertakeprofit, OrderCmt, Magic, 0, Lime );             

				if ( orderticket > 0 ) 
				{

					Execution = (int) GetTickCount() - Execution;
					if ( Debug || Verbose ) 
						Print ( "Order executed in " + (string) Execution + " ms" );

					if ( TakeShots && !IsTesting() ) 
						sub_takesnapshot();
				}  // end if ordersend

				else
				{
					ordersenderror = TRUE;
					Execution = -1;

					sub_errormessages();
				} 

				if ( OrderSelect ( orderticket, SELECT_BY_TICKET ) )  
				{		
					RefreshRates();

					orderprice = OrderOpenPrice();
					orderstoploss =  sub_normalizebrokerdigits ( orderprice - spread - StopLoss * Point - AddPriceGap );
					ordertakeprofit = sub_normalizebrokerdigits ( orderprice + TakeProfit * Point + AddPriceGap );

		       	Execution = (int) GetTickCount(); 

					wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, orderexpiretime, Lime );

					if ( wasordermodified == TRUE ) 				
					{

						Execution = (int) GetTickCount() - Execution;
						if ( Debug || Verbose ) 
							Print ( "Order executed in " + (string) Execution + " ms" );

						if ( TakeShots && !IsTesting() ) 
							sub_takesnapshot();
					} // end successful ordermodiify

					else
					{
						ordersenderror = TRUE;
						Execution = -1;

						sub_errormessages();
					} // end if-else					
				}  // end if ordermodify					
			} // end if ECN_Mode

			else 
			{
				RefreshRates();

				orderprice = askplusdistance;//ask+StopLevel
			   orderstoploss =  sub_normalizebrokerdigits ( orderprice - spread - StopLoss * Point - AddPriceGap );
				ordertakeprofit = sub_normalizebrokerdigits ( orderprice + TakeProfit * Point + AddPriceGap );

				Execution = (int) GetTickCount(); 

				orderticket = OrderSend ( Symbol(), OP_BUYSTOP, LotSize, orderprice, Slippage, orderstoploss, ordertakeprofit, OrderCmt, Magic, orderexpiretime, Lime );
				if ( orderticket > 0 ) // OrderSend was executed suxxessfully
				{

					Execution = (int) GetTickCount() - Execution;
					if ( Debug || Verbose

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

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

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

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

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

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

Стоимость полного кода
4 225,80₽ ≈ $51.65