XMT-Scalper
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «xmt-scalper_v2.461.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
XMT-Scalper — это торговый советник для MetaTrader 4, написанный на языке MQL4. Советник работает преимущеально на таймфрейме M1 и ориентирован на скальпинг, используя анализ волатильности и технических индикаторов для открытия позиций через отложенные ордера BUYSTOP и SELLSTOP.
Советник поддерживает три режима индикаторов: скользящая средняя (iMA), полосы Боллинджера (iBands) и огибающие (iEnvelopes). Торговые сигналы генерируются при пробое цены за пределы канала, рассчитанного по выбранному индикатору. Доступен режим ECN, при котором SL и TP добавляются через OrderModify после отправки ордера.
Встроена система управления рисками: расчёт объёма позиции на основе процента риска от собственного капитала, ограничения по спреду, времени исполнения, маржинальному уровню и уровню стоп-лосса. Также реализована функция отслеживания ордеров без стоп-лосса и функция создания скриншотов графика.
Настройки программы
| Настройка | Описание |
|---|---|
| Configuration | Конфигурация — Текстовый параметр конфигурации. |
| If TRUE, then trade in opposite direction (ReverseTrade) | Обратная торговля — При значении TRUE торговля ведётся в противоположном направлении. |
| If set to a number less than 0 it will calculate MagicNumber automatically (Magic) | Магический номер — Магический номер ордеров. Если задано значение меньше 0, магический номер рассчитывается автоматически. |
| Trade comments that appears in the Trade and Account History tab (OrderCmt) | Комментарий ордера — Комментарий к сделкам, отображаемый во вкладках «Торговля» и «История аккаунта». |
| True for brokers that don't accept SL and TP to be sent at the same time as the order (ECN_Mode) | ECN-режим — Включает режим ECN для брокеров, которые не принимают одновременную отправку StopLoss и TakeProfit с ордером. |
| Print huge log files with info, only for debugging purposes (Debug) | Режим отладки — Включает подробное логирование информации в журнал для целей отладки. |
| Additional information printed in the chart (Verbose) | Подробный вывод — Выводит дополнительную информацию на график для мониторинга. |
| TradingSettings | Торговые настройки — Текстовый параметр торговых настроек. |
| Max allowed spread in points (1 / 10 pip) (MaxSpread) | Максимальный спред — Максимально допустимый спред в пунктах (1/10 пипса). |
| Max allowed average execution time in ms (0 means no restrictions) (MaxExecution) | Максимальное время исполнения — Максимально допустимое среднее время исполнения ордера в миллисекундах. Значение 0 означает отсутствие ограничений. |
| How often in minutes should fake orders be sent to measure execution speed (MaxExecutionMinutes) | Период измерения скорости — Периодичность в минутах отправки тестовых ордеров для измерения скорости исполнения. |
| StopLoss from as many points. Default 60 (= 6 pips) (StopLoss) | Стоп-лосс — Стоп-лосс в пунктах. По умолчанию 60 (= 6 пипсов). |
| TakeProfit from as many points. Default 100 (= 10 pip) (TakeProfit) | Тейк-профит — Тейк-профит в пунктах. По умолчанию 100 (= 10 пипсов). |
| Additional price gap in points added to SL and TP in order to avoid Error 130 (AddPriceGap) | Дополнительный ценовой зазор — Дополнительный ценовой зазор в пунктах, добавляемый к StopLoss и TakeProfit для предотвращения ошибки 130 (невалидные стопы). |
| Start trailing profit from as so many points. (TrailingStart) | Начало трейлинга — Начало трейлинга прибыли, когда прибыль достигает указанного количества пунктов. |
| Some broker accounts charge commission in USD per 1.0 lot. Commission in dollar (Commission) | Комиссия брокера — Комиссия брокера в долларах за 1.0 лот для аккаунтов, где комиссия списывается в USD. |
| Maximum allowed Slippage in points (Slippage) | Проскальзывание — Максимально допустимое проскальзывание в пунктах. |
| Minimum stop level. Stoplevel to use will be max value of either this value or broker stoplevel (MinimumUseStopLevel) | Минимальный уровень стопа — Минимальный уровень стопа. Используемый StopLevel будет максимальным значением из этого параметра или стоп-уровня брокера. |
| VolatilitySettings | Настройки волатильности — Текстовый параметр настроек волатильности. |
| Calculate VolatilityLimit based on INT (spread * VolatilityMultiplier) (UseDynamicVolatilityLimit) | Динамический предел волатильности — При значении TRUE предел волатильности рассчитывается динамически на основе спреда и множителя волатильности. |
| Dynamic value, only used if UseDynamicVolatilityLimit is set to TRUE (VolatilityMultiplier) | Множитель волатильности — Множитель волатильности, используется для динамического расчёта предела при включённом UseDynamicVolatilityLimit. |
| Fix value, only used if UseDynamicVolatilityLimit is set to FALSE (VolatilityLimit) | Предел волатильности — Фиксированный предел волатильности, используется при отключённом динамическом расчёте. |
| If true, then price must break out more than a specific percentage (UseVolatilityPercentage) | Процент пробоя волатильности — При значении TRUE цена должна пробить предел волатильности на определённый процент для генерации сигнала. |
| Percentage of how much iHigh-iLow difference must differ from VolatilityLimit. 0 is risky, 60 means (VolatilityPercentag | Процентный предел волатильности — Процент, на который разница между iHigh-iLow и VolatilityLimit должна отличаться для генерации торгового сигнала. Значение 0 рискованно, 60 — безопасное. |
| UseIndicatorSet | Набор индикаторов — Текстовый параметр набора индикаторов. |
| Switch User indicators. (UseIndicatorSwitch) | Переключатель индикаторов — Переключатель индикаторов: 1 — скользящая средняя, 2 — полосы Боллинджера, 3 — огибающие, 4 — ATR. |
| Period in bars for indicators (Indicatorperiod) | Период индикаторов — Период в барах для расчёта индикаторов. |
| Deviation for the iBands indicator (BBDeviation) | Отклонение полос Боллинджера — Отклонение для индикатора полос Боллинджера (iBands). |
| Deviation for the iEnvelopes indicator (EnvelopesDeviation) | Отклонение огибающих — Отклонение для индикатора огибающих (iEnvelopes). |
| Orders are deleted after so many seconds (OrderExpireSeconds) | Время жизни ордера — Время в секундах после которого неисполненные отложенные ордера удаляются. |
| Money_Management | Управление денежными средствами — Текстовый параметр управления денежными средствами. |
| If TRUE then calculate lotsize automaticallay based on Risk, if False then use ManualLotsize below (MoneyManagement) | Автоматическое управление лотом — Включает автоматический расчёт размера лота на основе процента риска. При значении FALSE используется ручной размер лота. |
| Minimum lot-size to trade with (MinLots) | Минимальный лот — Минимально допустимый размер лота для торговли. |
| Maximum allowed lot-size to trade with (MaxLots) | Максимальный лот — Максимально допустимый размер лота для торговли. |
| Risk setting in percentage, For 10.000 in Equity 10% Risk and 60 StopLoss lotsize = 16.66 (Risk) | Процент риска — Процент риска для расчёта размера лота. Например, при риске 2% от капитала и стоп-лоссе в 60 пунктов лот рассчитывается автоматически. |
| Manual lotsize to trade with if MoneyManagement above is set to FALSE (ManualLotsize) | Ручной размер лота — Ручной размер лота, используемый при отключённом автоматическом управлении денежными средствами. |
| Lowest allowed Margin level for new positions to be opened. (MinMarginLevel) | Минимальный уровень маржи — Минимально допустимый уровень маржи в процентах для открытия новых позиций. Торговля запрещена при свободной марже ниже этого уровня. |
| Screen_Shooter | Скриншоты — Текстовый параметр настройки скриншотов. |
| Save screen shots on STOP orders? (TakeShots) | Создание скриншотов — Включает сохранение скриншотов при размещении стоп-ордеров. |
| Delay so many ticks after new bar (DelayTicks) | Задержка тиков — Задержка в тиках после появления нового бара для создания скриншотов. |
| How many screen shots per bar (ShotsPerBar) | Скриншотов на бар — Количество скриншотов, создаваемых на каждый бар. |
| Colors for sub_Display at upper left (DisplayGraphics) | Отображение графики — Текстовый параметр для настройки цветов отображения на графике. |
| Font size for headline (Heading_Size) | Размер шрифта заголовка — Размер шрифта для заголовка на графике. |
| Font size for texts (Text_Size) | Размер шрифта текста — Размер шрифта для текстовых строк на графике. |
| Color for text lines (Color_Heading) | Цвет заголовка — Цвет для заголовочных текстовых строк на графике. |
| "- (Color_Section1) | Цвет раздела 1 — Цвет для текстовых строк раздела 1 на графике. |
| "- (Color_Section2) | Цвет раздела 2 — Цвет для текстовых строк раздела 2 на графике. |
| "- (Color_Section3) | Цвет раздела 3 — Цвет для текстовых строк раздела 3 на графике. |
| "- (Color_Section4) | Цвет раздела 4 — Цвет для текстовых строк раздела 4 на графике. |
Поиск по коду файла
#property version "2.46"
#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 for EURUSD M1, but can also work on other pairs, Gold and CFD's"
#property description "It's extremely broker sensitive and requires tight spread."
#property description "Read the PDF-file for explanations and settings."
#include "stdlib.mqh" // "stdlib.mqh" or "<sdlib.mqh>
#include "stderror.mqh" // "stderror.mqh" or <stderror.mqh>
extern string Configuration = "==== Configuration ====";
extern bool ReverseTrade = FALSE; // If TRUE, then trade in opposite direction
extern int Magic = -1; // If set to a number less than 0 it will calculate MagicNumber automatically
extern string OrderCmt = "XMT-Scalper 2.46"; // Trade comments that appears in the Trade and Account History tab
extern bool ECN_Mode = FALSE; // True for brokers that don't accept SL and TP to be sent at the same time as the order
extern bool Debug = FALSE; // Print huge log files with info, only for debugging purposes
extern bool Verbose = FALSE; // Additional information printed in the chart
extern string TradingSettings = "==== Trade settings ====";
extern double MaxSpread = 30.0; // Max allowed spread in points (1 / 10 pip)
extern int MaxExecution = 0; // Max allowed average execution time in ms (0 means no restrictions)
extern int MaxExecutionMinutes = 5; // How often in minutes should fake orders be sent to measure execution speed
extern double StopLoss = 60; // StopLoss from as many points. Default 60 (= 6 pips)
extern double TakeProfit = 100; // TakeProfit from as many points. Default 100 (= 10 pip)
extern double AddPriceGap = 0; // Additional price gap in points added to SL and TP in order to avoid Error 130
extern double TrailingStart = 20; // Start trailing profit from as so many points.
extern double Commission = 0; // Some broker accounts charge commission in USD per 1.0 lot. Commission in dollar
extern int Slippage = 3; // Maximum allowed Slippage in points
extern double MinimumUseStopLevel = 0; // Minimum stop level. Stoplevel to use will be max value of either this value or broker stoplevel
extern string VolatilitySettings = "==== Volatility Settings ====";
extern bool UseDynamicVolatilityLimit = TRUE; // Calculate VolatilityLimit based on INT (spread * VolatilityMultiplier)
extern double VolatilityMultiplier = 125; // Dynamic value, only used if UseDynamicVolatilityLimit is set to TRUE
extern double VolatilityLimit = 180; // Fix value, only used if UseDynamicVolatilityLimit is set to FALSE
extern bool UseVolatilityPercentage = TRUE; // If true, then price must break out more than a specific percentage
extern double VolatilityPercentageLimit = 0; // Percentage of how much iHigh-iLow difference must differ from VolatilityLimit. 0 is risky, 60 means a safe value
extern string UseIndicatorSet = "=== Indicators: 1 = Moving Average, 2 = BollingerBand, 3 = Envelopes";
extern int UseIndicatorSwitch = 1; // Switch User indicators.
extern int Indicatorperiod = 3; // Period in bars for indicators
extern double BBDeviation = 2.0; // Deviation for the iBands indicator
extern double EnvelopesDeviation = 0.07; // Deviation for the iEnvelopes indicator
extern int OrderExpireSeconds = 3600; // Orders are deleted after so many seconds
extern string Money_Management = "==== Money Management ====";
extern bool MoneyManagement = TRUE; // If TRUE then calculate lotsize automaticallay based on Risk, if False then use ManualLotsize below
extern double MinLots = 0.01; // Minimum lot-size to trade with
extern double MaxLots = 100.0; // Maximum allowed lot-size to trade with
extern double Risk = 2.0; // Risk setting in percentage, For 10.000 in Equity 10% Risk and 60 StopLoss lotsize = 16.66
extern double ManualLotsize = 0.1; // Manual lotsize to trade with if MoneyManagement above is set to FALSE
extern double MinMarginLevel = 100; // Lowest allowed Margin level for new positions to be opened.
extern string Screen_Shooter = "==== Screen Shooter ====";
extern bool TakeShots = FALSE; // Save screen shots on STOP orders?
extern int DelayTicks = 1; // Delay so many ticks after new bar
extern int ShotsPerBar = 1; // How many screen shots per bar
extern string DisplayGraphics = "=== Display Graphics ==="; // Colors for sub_Display at upper left
extern int Heading_Size = 13; // Font size for headline
extern int Text_Size = 12; // Font size for texts
extern color Color_Heading = Lime; // Color for text lines
extern color Color_Section1 = Yellow; // -"-
extern color Color_Section2 = Aqua; // -"-
extern color Color_Section3 = Orange; // -"-
extern color Color_Section4 = Magenta; // -"-
string EA_version = "XMT-Scalper v. 2.46";
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 LastTime = 0; // For measuring tics
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 StartTime; // Initial time
int Leverage; // Account Leverage in percentage
int LotBase; // Amount of money in base currency for 1 lot
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 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
int init()
{
// код доступен только после оплаты
}
int deinit()
{
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 " + SkippedTicks + " number of ticks was ";
text = text + "skipped to simulate latency of up to " + MaxExecution + " ms";
sub_printandcomment ( text );
}
}
Print ( EA_version, " has been deinitialized!" );
return ( 0 );
}
int start()
{
// код доступен только после оплаты
}
void sub_trade()
{
string textstring;
string pair;
string indy;
bool select;
bool wasordermodified;
bool ordersenderror;
bool isbidgreaterthanima;
bool isbidgreaterthanibands;
bool isbidgreaterthanenvelopes;
bool isbidgreaterthanindy;
int orderticket;
int orderexpiretime;
int loopcount2;
int loopcount1;
int pricedirection;
int counter1;
int counter2;
int askpart;
int bidpart;
double ask;
double bid;
double askplusdistance;
double bidminusdistance;
double volatilitypercentage;
double orderprice;
double orderstoploss;
double ordertakeprofit;
double ihigh;
double ilow;
double imalow;
double imahigh;
double imadiff;
double ibandsupper;
double ibandslower;
double ibandsdiff;
double envelopesupper;
double envelopeslower;
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;
MarginFree = AccountFreeMargin();
if ( AccountMargin() != 0 )
am = AccountMargin();
marginlevel = AccountEquity() / am * 100;
if ( marginlevel < MinMarginLevel )
{
Comment ( "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(), PERIOD_M1, 0 );
ilow = iLow ( Symbol(), PERIOD_M1, 0 );
volatility = ihigh - ilow;
indy = "";
if ( UseIndicatorSwitch == 1 || UseIndicatorSwitch == 4 )
{
imalow = iMA ( Symbol(), PERIOD_M1, Indicatorperiod, 0, MODE_LWMA, PRICE_LOW, 0 );
imahigh = iMA ( Symbol(), PERIOD_M1, 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(), PERIOD_M1, Indicatorperiod, BBDeviation, 0, PRICE_OPEN, MODE_UPPER, 0 );
ibandslower = iBands ( Symbol(), PERIOD_M1, 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(), PERIOD_M1, Indicatorperiod, MODE_LWMA, 0, PRICE_OPEN, EnvelopesDeviation, MODE_UPPER, 0 );
envelopeslower = iEnvelopes ( Symbol(), PERIOD_M1, 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 )
{
Comment ( "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 = GetTickCount();
wasordermodified = OrderModify ( OrderTicket(), 0, orderstoploss, ordertakeprofit, orderexpiretime, Lime );
}
if ( wasordermodified == TRUE )
{
Execution = 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 = GetTickCount();
wasordermodified = OrderModify ( OrderTicket(), 0, orderstoploss, ordertakeprofit, orderexpiretime, Orange );
}
if ( wasordermodified == TRUE )
{
Execution = 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 = GetTickCount();
wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, 0, Lime );
}
if ( wasordermodified == TRUE )
{
Execution = GetTickCount() - Execution;
if ( Debug || Verbose )
Print ( "Order executed in " + 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 = GetTickCount();
wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, 0, Orange );
}
if ( wasordermodified == TRUE )
{
Execution = GetTickCount() - Execution;
if ( Debug || Verbose )
Print ( "Order executed in " + 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 = NormalizeDouble ( bid / Point, 0 );
askpart = 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: " + 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 = GetTickCount();
orderticket = OrderSend ( Symbol(), OP_BUYSTOP, LotSize, orderprice, Slippage, orderstoploss, ordertakeprofit, OrderCmt, Magic, 0, Lime );
if ( orderticket > 0 )
{
Execution = GetTickCount() - Execution;
if ( Debug || Verbose )
Print ( "Order executed in " + 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 = GetTickCount();
wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, orderexpiretime, Lime );
if ( wasordermodified == TRUE )
{
Execution = GetTickCount() - Execution;
if ( Debug || Verbose )
Print ( "Order executed in " + Execution + " ms" );
if ( TakeShots && !IsTesting() )
sub_takesnapshot();
} // end successful ordermoПоказано первые 50% кода (символов: 39249)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.