London Breakout EA
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «london breakout ea-v7.2.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
London Breakout EA — это советник (Expert Advisor) для платформы MetaTrader 4, реализующий стратегию торговли на основе пробоя лондонской сессии. Советник автоматически выставляет отложенные ордера BuyStop и SellStop в зависимости от диапазона цены в рамках заданного временного окна лондонской сессии. Параметры сессии можно задавать вручную или импортировать из индикатора London Breakout через глобальные переменные.
EA включает комплексное управление открытыми сделками: трейлинг-стоп, перевод стоп-лосса в безубыток, частичное закрытие (half-close), OCO (One Cancels The Other), а также мартингейл — как с фиксированной последовательностью множителей, так и автоматический расчёт для возмещения убытков. Встроены фильтры риска: максимальное количество сделок в день, максимальное число убытков на пару и ограничение размера бокса.
Версия 7.2 добавляет контроль проскальзывания при открытии рыночных ордеров вблизи уровня отложенного ордера, а также возможность независимой настройки параметров сессии без привязки к индикатору. Советник поддерживает автоматическую генерацию уникального MagicNumber для каждой пары и таймфрейма.
Настройки программы
| Настройка | Описание |
|---|---|
| Lot | Фиксированный размер лота для открытия сделок. |
| MaxRisk | Максимальный риск в процентах от свободного маржа. При значении больше 0 размер лота рассчитывается как минимум из Lot и расчётного максимального лота на основе риска и стоп-лосса. |
| MagicNumber | Уникальный идентификатор ордеров. При значении 0 советник автоматически генерирует уникальный MagicNumber для каждой пары и таймфрейма. |
| TradeComment | Комментарий, присваиваемый каждому открытому ордеру. |
| _mta1 | Разделитель-текстовый параметр для группы настроек максимального числа сделок. |
| _mta2 | Разделитель-текстовый параметр для группы настроек максимального числа сделок. |
| MaxTradesAllowedForTheDay | Максимальное количество сделок за торговый день. При значении 0 ограничений нет. |
| _mla1 | Разделитель-текстовый параметр для группы настроек максимальных убытков. |
| _mla2 | Разделитель-текстовый параметр для группы настроек максимальных убытков. |
| MaxLossesAllowedPerPair | Максимальное количество убыточных сделок на пару за сессию. При достижении лимита советник закрывает все отложенные ордера и прекращает торговлю до следующей сессии. |
| objPrefix | Префикс объектов индикатора London Breakout, используемый для импорта настроек из глобальных переменных. |
| _tm | Разделитель-текстовый параметр для группы настроек управления торговлей. |
| UseSelectedManagementFunctions | Включает или отключает функции управления открытыми сделками (half-close, безубыток, OCO, трейлинг-стоп). |
| _hcf | Разделитель-текстовый параметр для группы настроек half-close. |
| AllowHalfClose | Включает или отключает функцию частичного закрытия сделки (half-close) при достижении половины тейк-профита. |
| BreakEvenPips | При значении больше 0 стоп-лосс перемещается в безубыток (BE) после достижения указанного уровня прибыли в пипсах. Работает независимо от half-close. |
| BreakEvenProfitInPips | Количество пипсов фиксированной прибыти, которое фиксируется при срабатывании безубытка или частичного закрытия. |
| TrailingStopPips | Расстояние трейлинг-стопа в пипсах. При значении 0 трейлинг-стоп не применяется. |
| TrailingStopStep | Шаг перемещения трейлинг-стопа в пипсах. Определяет минимальное расстояние между перемещениями стоп-лосса. |
| _oco1 | Разделитель-текстовый параметр для группы настроек OCO. |
| _oco2 | Разделитель-текстовый параметр для группы настроек OCO. |
| OneCancelsTheOther | Включает режим OCO: при заполнении одного из отложенных ордеров (BuyStop или SellStop) второй удаляется. |
| ClosePendingWhenUnload | При выгрузке советника удаляет все отложенные ордера. Открытые сделки остаются без изменений. |
| _mart1 | Разделитель-текстовый параметр для группы настроек мартингейла. |
| _mart2 | Разделитель-текстовый параметр для группы настроек мартингейла. |
| martingale_sequence | Последовательность множителей мартингейла через запятую. Если первый элемент равен 0, мартингейл отключён. |
| AutoMartingale | При включении используется автоматический мартингейл: множитель рассчитывается динамически для возмещения всех предыдущих убытков плюс текущий тейк-профит. |
| RestartMartSeq | При достижении максимального уровня мартингейла: если true — последовательность множителей сбрасывается к началу; если false — сохраняется последний множитель до прибыльной сделки. |
| DisplayGapSize | Количество пробелов для форматирования текста в окне комментариев советника. |
| ImportFromIndicator | При значении true параметры сессии импортируются из глобальных переменных индикатора London Breakout. При false — настраиваются вручную в советнике. |
| StartTime | Время начала окна формирования ценового диапазона (бокса) в формате "чч:мм". |
| EndTime | Время окончания окна формирования ценового диапазона (бокса) в формате "чч:мм". |
| SessionEndTime | Время окончания ежедневной торговой сессии в формате "чч:мм". После этого времени торговля завершается до следующего дня. |
| MaxBoxSizeInPips | Максимальный размер бокса в пипсах. При превышении этого значения советник не открывает сделки и отображает красный индикатор "NO TRADE". |
| EntryFactor | Множитель для расчёта цены входа в сделку относительно размера бокса. |
| TPFactor | Множитель для расчёта тейк-профита относительно размера бокса. |
| SLpips | Фиксированное значение стоп-лосса в пипсах. При значении больше 0 SLFactor игнорируется и стоп-лосс устанавливается фиксированно. |
| SLFactor | Множитель для расчёта стоп-лосса как доли от размера бокса. Используется только если SLpips равен 0. |
| LevelsResizeFactor | Множитель для изменения размера бокса перед расчётом торговых уровней. |
| MinExtentInPips | Минимальный предел фактического размера бокса для расчёта торговых уровней. При значении 0 ограничение не применяется. |
| MaxExtentInPips | Максимальный предел фактического размера бокса для расчёта торговых уровней. При значении 0 используется MaxBoxSizeInPips. |
| Slippage | Допустимое проскальзывание в пипсах. Также используется для проверки возможности открытия рыночного ордера при близости цены к уровню отложенного ордера. |
Поиск по коду файла
/*+------------------------------------------------------------------+
*
* Version history:
*
* V7.2: [Squalou]: (2011.03.26)
* - the EA will open MARKET ORDER when price is too close to the pending entry price;
* in that condition, no pending entry was opened, and therefore no trade was triggered;
* - Added "Slippage" input in pips (it was 0);
* Slippage is also used to check if we can open a market order when price is too close for opening pending orders;
* - FIXED SL_pips bug in V7.0: SL_pips input wasn't used properly;
*
* V7.0: [Squalou]: (2011.03.25)
* - Added "ImportFromIndicator": if true, then session parameters are imported from the Indicator (as before, requires the Indicator to be running),
* if false, then you can set all the session parameters manually directly in the EA, rather than importing them from Global Variables set by the Indicator:
* StartTime,EndTime,SessionEndTime,
* MaxBoxSizeInPips,EntryFactor,TPFactor,SLpips,SLFactor,LevelsResizeFactor,
* MinExtentInPips,MaxExtentInPips
*
* - Added "SLpips" and "SLFactor" inputs: (request from BERT505)
* when SLpips is >0, then the SL is set to this fix amount;
* otherwise, SL is a factor of the box size indicated by SLFactor;
*
* V6.0: [Squalou]: (2010.05.28)
* - Added "AutoMartingale" mode:
* the Martingale factor will be computed dynamically so that the next winning trade
* will recoup all past consecutive losses, plus the current TP.
*
* V5.2: [Squalou]: (2010.05.27)
* - fixed Martingale code: it was moving to the next mart factor at session opening
* if last yesterday's trade was a loss (instead of keeping the same factor)...;
*
* V5.1: [Squalou]: (2010.05.27)
* - debugged and reworked completely the Martingale code;
* - optimized EA -- especially for backtesting (removed useless loops on history; don't print status when backtesting)
* (it's probably at least 10 times faster now...)
* - fixed count of lost trades: it was counting trades older than session start, and even counting-in trades of previous weeks(!)
*
* V5.0: [Squalou]: (2010.05.25)
* - Added Martingale code from Pat1; !!! STILL EXPERIMENTAL CODE !!!
* - FIX: EA should not trade outside of trading hours;
*
* You can setup the Martingale multipliers sequence in the "martingale_sequence" input.
* The default sequence is set to "0,1,2,5,13,34,89,233,610,1597,4181".
* When the first element in the list is 0, the martingale is DISABLED.
* This is the default.
* When a trade is a loss, the next multiplier is used for the next trade.
* When it is a win, we come back to the first multiplier for the next trade.
* When the last multiplier is reached (9 consecutive losses with the default sequence), the multiplier will either remain to the last value (4181 in the default sequence), or come back to the first, depending on "RestartMartSeq" input:
* "RestartMartSeq" set to false (default) will keep last multiplier until a win.
* Set to true will come back to first multiplier.
*
* - REMOVED change done in v4.0 that would close all open/pending trades when the EA is unloaded:
* MT4 "silently" unloads the EAs when you close the MT4 platform, which closes all your open trades as well...
* OPEN trades are now left untouched,
* but pending orders are now controlled by the "ClosePendingWhenUnload" input.
*
* V4.0: [Squalou]: (2010.05.20)
* - Added TRAILING STOP capability:
* new inputs:
* TrailingStopPips(0): pips to trail the StopLoss; when 0 no trailing is applied (fixed SL as before).
* TrailingStopStep(1): trailing SL will jump by this amount instead of trailing at every tick;
* (helps limit the number of sent orders, and therefore order rejections).
*
* - Added profit lock-in at fixed TP:
* when "BreakEvenPips" is >0, SL is moved to BE+"BreakEvenProfitInPips" when price has reached BE+"BreakEvenPips";
* Works independently from "AllowHalfClose" option (but uses the same BreakEvenProfitInPips value);
* Will also be trailed if TrailingStop is selected;
* (inspired from Steve's MPTM EA...)
*
* - Added MaxRisk input: if >0, then order size is the min of Lot input and calculated max Lot based on MaxRisk and Stop-Loss;
*
* - All open/pending trades will be closed when the EA is unloaded;
*
* - when MagicNumber is 0, a unique MagicNumber is created by the EA, MagicNumbers will be different for each pair/TF;
* This helps running the EA on different pairs/TF without having to
*
* - fix: in V3.0, objPrefix default value was not set to "LB-" as it should have been, leading to error 130 "invalid stops";
* - added Alerts when Indicator SETTINGS GlobalVariables cannot be found; EA will stop trading in this case.
*
* V3.0: [Squalou]: (2010.05.11)
* ========== ALLOWS BACKTESTING THE EA ==========
* - the EA now computes the Entry/TP/SL LEVELS by itself, and only imports Indicator SETTINGS
* from the GlobalVariables.
* - EA now starts trading at the END of the bar forming at the Box EndTime, as expected by the Strategy:
* on M15, with EndTime=07:00, EA will start trading at 07:15, not 07:01.
* - fixed recursive alarms playing when price goes out of the "green fields";
* Only valid pending STOP orders are now placed based on market price;
* - Fixed OCO function that was repeatedly trying to delete wrong orders;
* - fixed count of losses for the day: when EA was used on multiple pairs/charts,
* ALL running EAs would "stop trading for the day" when the FIRST one reached MaxLossesAllowedPerPair...
* - fixed Half-close not functionning on SELL side;
*
* V2.0:
* - designed to work with "London BreakoutV8.1.mq4" indicator "exported" GobalVariables:
* grabs "MaxBoxSizeInPips", "StartTime", "EndTime", and "SessionEndTime"
*
* V1: original version from SteveHopwood at forexfactory.com
* - designed to work with "London BreakoutV8.mq4" indicator "exported" GobalVariables:
*
*+------------------------------------------------------------------+
*/
#include <WinUser32.mqh>
#include <stdlib.mqh>
#define EA_VERSION "V7.2 (2011.03.26)"
extern double Lot = 0.02;
extern double MaxRisk = 0; // if 0 then use fixed Lots above
extern int MagicNumber=0; // if 0 then will autocreate a unique MagicNumber
extern string TradeComment="----London breakout";
extern string _mta1="----MaxTradesAllowedForTheDay = 0";
extern string _mta2="----means no limit on trades";
extern int MaxTradesAllowedForTheDay=0;
extern string _mla1="----MaxLossesAllowedPerPair = 0";
extern string _mla2="----means no limit on losses";
extern int MaxLossesAllowedPerPair=2;
extern string objPrefix = "LB-"; // Prefixes of London Breakout Indicator objects;
extern string _tm="----Trade management----";
extern bool UseSelectedManagementFunctions=true;
extern string _hcf="----Half-close function";
extern bool AllowHalfClose=true;
extern int BreakEvenPips=0; // when >0, will move SL to BE+BreakEvenProfitInPips when price has reached BE+BreakEvenPips
extern int BreakEvenProfitInPips=5; // lock-in this amount of pips when HalfClose is hit;
extern int TrailingStopPips = 0;// Pips to trail the StopLoss; if 0 then no trailing stop
extern int TrailingStopStep = 1;// trailing SL jumping step in pips
extern string _oco1="----OCO will delete remaining pending";
extern string _oco2="----when its partner fills";
extern bool OneCancelsTheOther=false;
extern bool ClosePendingWhenUnload=false;
extern string _mart1="----MARTINGALE multipliers sequence:";
extern string _mart2="----not used when first multiplier is 0:";
extern string martingale_sequence="0,1,2,5,13,34,89,233,610,1597,4181";
extern bool AutoMartingale=false;
extern bool RestartMartSeq=false;// If Max Level is exceeded , if false, keep last multiplier till profitable else revert to Mart_Idx=0
extern int DisplayGapSize=10;
extern bool ImportFromIndicator = true; // set this false to allow setting session parameters here rather than importing them from Global Variables set by the Indicator:
extern string StartTime = "05:00";//"04:00"; // time for start of price establishment window
extern string EndTime = "08:00";//"07:00"; // time for end of price establishment window
extern string SessionEndTime= "05:00";//"18:00"; // end of daily session; tomorrow is another day!
extern int MaxBoxSizeInPips = 60;//50; // box size limit to show Red "NO TRADE" box
extern double EntryFactor = 0.8;//0.3;
extern double TPFactor = 2.58;//1.3;
extern int SLpips = 0; // if non-0, then SLFactor is ignored;
extern double SLFactor = 1.000;
extern double LevelsResizeFactor = 1.0;
extern int MinExtentInPips = 0; // actual box extent min limit for computing trade levels;
extern int MaxExtentInPips = 0; // actual box extent max limit for computing trade levels; 0 will default to MaxBoxSizeInPips;
extern int Slippage = 2; // slippage in pips; also used to check if we can open a market order when price is too close for pending orders;
#define NL "\n"
#define Status_initializing "????? I N I T I A L I Z I N G ?????"
#define Status_initialized "..... I N I T I A L I Z E D ....."
#define Status_trading "+++++ T R A D I N G +++++"
#define Status_not_trading "!!!!! N O T T R A D I N G (Box is too large) !!!!!"
#define Status_finished "----- F I N I S H E D F O R T O D A Y -----"
double LongPendingEntryPrice;
double LongTP;
double LongSL;
double ShortPendingEntryPrice;
double ShortTP;
double ShortSL;
int iStartTime,iEndTime,iSessionEndTime;
int _iStartTime,_iEndTime,_iSessionEndTime;
int _MaxBoxSizeInPips; // box size limit to show Red "NO TRADE" box
double _EntryFactor;
double _TPFactor;
double _LevelsResizeFactor;
int _MinExtentInPips; // actual box extent min limit for computing trade levels;
int _MaxExtentInPips; // actual box extent max limit for computing trade levels; 0 will default to MaxBoxSizeInPips;
datetime tBoxStart;
datetime tBoxEnd;
datetime tSessionStart;
datetime tSessionEnd;
double vSellStop;
double vBuyStop;
int SL_pips,TP_pips;
int StartShift;
int EndShift;
double boxHigh;
double boxLow;
double boxExtent;
double boxMedianPrice;
string symbol;
double LondonOpens;
double LondonCloses;
bool TradeHour = false, prev_TradeHour=false;
string TradingStatus;
bool ClosedForFriday;
bool ClosedForSaturday;
bool TradeOpen;
int TicketNo;
int LastOrderProfitable=false;
bool UseMartingale=false;
double MartFactor[];
int MartDepth=0;
int Mart_Idx=0;
int TradesOpen, TradesWon, TradesLost, TradesTotal;
string comment, Gap;
bool RobotDisabled;
string DisabledMessage;
double pip;
int digits;
double minlot;
int maxSL;
string op_str[5] = { "BUY","SELL","BUYLIMIT","SELLLIMIT","BUYSTOP","SELLSTOP"};
void DisplayUserFeedback()
{
static bool alreadyPrinted=false;
if (IsTesting()&& !IsVisualMode() && alreadyPrinted) return; // saves cpu time when backtesting
comment = Gap+WindowExpertName()+ " "+ EA_VERSION+ NL;
if (MaxRisk <= 0) {
comment = comment+Gap+ "Lot size = "+ Lot+ " (MaxRisk not used)"+ NL;
} else {
comment = comment+Gap+ "MaxRisk = "+ MaxRisk+ "% => "+ DoubleToStr(Lot,2)+ "Lots, AccountFreeMargin = "+ DoubleToStr(AccountFreeMargin(),0)+ AccountCurrency()+ NL;
}
comment = comment+Gap+ "Magic number = "+ MagicNumber+ ", objPrefix = "+ objPrefix+ NL
+Gap+ "Trade comment = "+ TradeComment+ NL
+Gap+ "Local time: "+ TimeToStr(TimeLocal())+ " Broker time: "+ TimeToStr(TimeCurrent())+ " Current Bar time: "+ TimeToStr(Time[0])+ NL
+Gap+ "Trading Hours: "+ DoubleToStr(LondonOpens/100,2)+ " - "+ DoubleToStr(LondonCloses/100,2)+ NL
+Gap+ "Box=["+StartTime+"-"+EndTime+"], Box max "+DoubleToStr(MaxBoxSizeInPips,0)+"p, BoxExtent ["+DoubleToStr(boxLow,Digits)+"-"+DoubleToStr(boxHigh,Digits)+"]="+DoubleToStr(boxExtent/pip,1)+"p"+NL
+Gap+ "EntryFactor="+DoubleToStr(EntryFactor,2)+", TPFactor="+DoubleToStr(TPFactor,2)+", LevelsResizeFactor="+DoubleToStr(LevelsResizeFactor,2)+")"+NL
+Gap+ "Long Entry: "+ DoubleToStr(LongPendingEntryPrice, Digits)+ ", TP: "+ DoubleToStr(LongTP, Digits)+ ", SL: "+ DoubleToStr(LongSL, Digits)+ NL
+Gap+ "Short Entry: "+ DoubleToStr(ShortPendingEntryPrice, Digits)+ ", TP: "+ DoubleToStr(ShortTP, Digits)+ ", SL: "+ DoubleToStr(ShortSL, Digits)+ NL
+Gap+ "Slippage="+DoubleToStr(Slippage,0)+NL;
if (UseSelectedManagementFunctions)
{
comment = comment+Gap+ "Using management functions:"+NL;
if (AllowHalfClose) {
comment = comment+ Gap+ " Using half-close, move to BE+"+BreakEvenPips+" pips at half-close"+NL;
} else {
comment = comment+ Gap+ " NOT Using half-close"+NL;
}
if (BreakEvenPips>0) {
comment = comment+Gap+ " lock-in "+BreakEvenProfitInPips+" pips when reached BE+"+BreakEvenPips+" pips profit"+ NL;
}
if (TrailingStopPips>0) {
comment = comment+Gap+ " Trailing stops at "+TrailingStopPips+" pips, by steps of "+TrailingStopStep+" pips"+ NL;
}
if (OneCancelsTheOther) comment = comment+Gap+ " OCO ON: Closing parter pending trade when one fills"+ NL;
else comment = comment+Gap+ " OCO OFF: NOT Closing parter pending trade when one fills"+ NL;
}
if (UseMartingale) {
if (AutoMartingale) {
comment =comment+Gap+" AUTO-MARTINGALE ENABLED"+NL;
} else {
comment =comment+Gap+" MARTINGALE FACTORS: ";
for (int i=0;i<MartDepth;i++) {
if (i==Mart_Idx) comment=comment+" ((";
comment=comment+DoubleToStr(MartFactor[i],0);
if (i==Mart_Idx) comment=comment+")) ";
comment=comment+",";
}
comment=comment+NL;
}
} else {
comment =comment+Gap+" Martingale NOT used"+NL;
}
comment = comment+Gap+ EA_VERSION+ " " + TradingStatus+ NL;
if (IsTesting() && !IsVisualMode()) {
Print(comment);
alreadyPrinted = true;
return;
}
Comment(comment);
}//void DisplayUserFeedback()
int init()
{
// код доступен только после оплаты
}
int deinit()
{
Comment("");
if (ClosePendingWhenUnload) CloseAllPendingTrades();
return(0);
}
int start()
{
// код доступен только после оплаты
}
double servers_min_stop = MarketInfo(symbol, MODE_STOPLEVEL) * MarketInfo(symbol, MODE_POINT);
if (RobotDisabled)
{
Comment("The robot has been suspended. Reason: ", DisabledMessage);
return;
}
if (ImportFromIndicator) {
/* Import SETTINGS input values from GlobalVariables:
* available since "London BreakoutV8.mq4" indicator;
*/
if (!import_LB_Indi_SETTINGS(objPrefix,symbol)) {
DisabledMessage = "Some Indicator SETTINGS are missing;\n Please verify objPrefix in the Indicator and the EA;\n (objPrefix is currently set to "+objPrefix+" in the EA)";
RobotDisabled = true;
_Alert (DisabledMessage);
return;
}
if (update_local_LB_Indi_SETTINGS()) {
CloseAllPendingTrades();
}
}
compute_LB_Indi_LEVELS(Time[0]);
if (!IsTradeAllowed())
{
Comment("Trading disabled by the criminal pillock. Please wait for him to get out of bed.");
return;
}//if (!IsTradeAllowed)
int now = TimeHour(Time[0])*100 + TimeMinute(Time[0]);
prev_TradeHour = TradeHour;
if ( (LondonOpens <= LondonCloses && (now >= LondonOpens && now < LondonCloses))
|| (LondonOpens > LondonCloses && (now >= LondonOpens || now < LondonCloses)) ) {
TradeHour = true;
} else {
TradeHour = false;
}
if (prev_TradeHour==false && TradeHour==true) {
Print ("New Session Starting: "+ TimeToStr(TimeLocal())+NL
+"Long Entry: "+ DoubleToStr(LongPendingEntryPrice, Digits)+ ", TP: "+ DoubleToStr(LongTP, Digits)+ ", SL: "+ DoubleToStr(LongSL, Digits)+ NL
+"Short Entry: "+ DoubleToStr(ShortPendingEntryPrice, Digits)+ ", TP: "+ DoubleToStr(ShortTP, Digits)+ ", SL: "+ DoubleToStr(ShortSL, Digits)+ NL);
}
if (!TradeHour)
{
if (TradingStatus != Status_finished) {
_Alert (Status_finished+" Session End at "+DoubleToStr(LondonCloses/100,2));
CloseAllPendingTrades();
}
TradingStatus = Status_finished;
DisplayUserFeedback();
return;
}//if (!TradeHour)
GetTradingStatus();
if (TradingStatus == Status_not_trading)
{
DisplayUserFeedback();
return;
}
GetAggregatePosition();
if (OrdersTotal() > 0 && UseSelectedManagementFunctions) {
ManageOpenTrades();
}
if (MaxTradesAllowedForTheDay > 0)// 0 means unlimited trades
{
if (TradesTotal >= MaxTradesAllowedForTheDay)
{
if (TradingStatus != Status_finished) {
_Alert (Status_finished+"Reached Max TradesПоказано первые 50% кода (символов: 32988)