ea-the_beast.mq4
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «ea-the_beast.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Советник для платформы MetaTrader 4, предназначенный для автоматической контравариантной торговли. Анализирует ценовой диапазон за заданное количество баров, разделяя его на уровни для определения точек входа и выхода. Включает модуль хеджирования с несколькими методами открытия позиций и систему восстановления после серийных убытков.
Настройки программы
| Настройка | Описание |
|---|---|
| gen | Текстовый параметр — Заголовок группы общих входных настроек |
| Lot | Число — Размер лота для совершения сделок |
| StopTrading | Переключатель — Приостановить всю торговую активность советника |
| TradeLong | Переключатель — Разрешить открытие сделок в длинную сторону |
| TradeShort | Переключатель — Разрешить открытие сделок в короткую сторону |
| MaxTradesAllowedPerPair | Целое число — Максимальное количество сделок на одну валютную пару |
| MaxOpenPairsAllowed | Целое число — Максимальное количество одновременно открытых пар |
| PipsBufferFromTradeLine | Целое число — Дополнительный отступ в пипсах от уровня для фильтрации сделок |
| MinPipsFromLastEntry | Целое число — Минимальное расстояние в пипсах от последнего входа |
| MaxSpread | Число — Максимально допустимый спред для открытия сделок |
| TouchesRequired | Целое число — Количество подтверждений касания уровня перед открытием сделки |
| tts | Текстовый параметр — Заголовок группы выбора стиля торговли |
| ctt | Текстовый параметр — Метка раздела контравариантной торговли |
| CounterTrendTrading | Переключатель — Включить контравариантную торговлю |
| OnlyCtTradeForRecovery | Переключатель — Разрешить контравариантную торговлю только в рамках восстановления |
| UseZeljko | Переключатель — Использовать фильтр сбалансированных пар |
| OnlyTradeCurrencyTwice | Переключатель — Ограничить торговлю каждой валютой не более чем двумя сделками |
| htr | Текстовый параметр — Заголовок группы настроек хеджирования белым ящиком |
| DoWhiteBoxTrading | Переключатель — Включить торговлю методом белого ящика |
| WhiteBoxPips | Целое число — Размер зоны белого ящика в пипсах от центральной линии |
| PendingHedgePips | Целое число — Отступ для отложенных хедж-ордеров в пипсах |
| BoxBreakevenProfit | Целое число — Прибыль в пипсах для перевода хедж-сделки в безубыток |
| CloseBoxTradesAtMagenta | Переключатель — Закрывать сделки белого ящика при достижении магента-уровня |
| CloseBoxTradesAtGold | Переключатель — Закрывать сделки белого ящика при достижении золотого уровня |
| CloseBoxTradesAtGreen | Переключатель — Закрывать сделки белого ящика при достижении зелёного уровня |
| wbts | Текстовый параметр — Заголовок группы стиля торговли белым ящиком |
| UseOriginalMethod | Переключатель — Использовать оригинальный метод открытия сделок белого ящика |
| UseInvertedMethod | Переключатель — Использовать инвертированный метод открытия сделок белого ящика |
| UseSamePriceMethod | Переключатель — Использовать метод открытия по текущей цене |
| SleepSecondsBetweenTrades | Целое число — Пауза в секундах между отправкой ордеров |
| amc | Текстовый параметр — Заголовок группы проверок доступной маржи |
| sco | Текстовый параметр — Метка проверки маржи Scoobs |
| UseScoobsMarginCheck | Переключатель — Включить проверку маржи по методу Scoobs |
| fk | Текстовый параметр — Метка проверки маржи ForexKiwi |
| UseForexKiwi | Переключатель — Включить проверку маржи по методу ForexKiwi |
| FkMinimumMarginPercent | Целое число — Минимальный процент маржи для разрешения торговли ForexKiwi |
| bc | Текстовый параметр — Заголовок группы настроек подсчёта баров |
| BarCount | Целое число — Количество баров для анализа ценового диапазона |
| UseMax | Переключатель — Использовать максимальное значение BarCount для пары |
| UseChaserL | Переключатель — Использовать динамический расчёт BarCount на основе CCI |
| CCIHelp | Текстовый параметр — Подпись периода часового CCI для расчёта |
| CCIPeriod | Целое число — Период индикатора CCI для динамического расчёта BarCount |
| gls | Текстовый параметр — Заголовок группы настроек золотой линии |
| BreakEvenAtGold | Переключатель — Переводить стоп-лосс в безубыток при достижении золотого уровня |
| GoldLineBEP | Целое число — Отступ в пипсах для установки безубытка на золотой линии |
| acc | Текстовый параметр — Заголовок группы настроек закрытия сделок |
| CloseTradeAtGold | Переключатель — Закрывать сделку при достижении золотого уровня |
| CloseTradeAtGreen | Переключатель — Закрывать сделку при достижении зелёного уровня |
| CloseTradeAtMiddleWhiteLine | Переключатель — Закрывать сделку при достижении среднего белого уровня |
| acc1 | Текстовый параметр — Метка автоматического расчёта линии закрытия |
| AutoCalcTradeClosureLine | Переключатель — Автоматически рассчитывать линию закрытия сделок на основе волатильности |
| vs | Текстовый параметр — Заголовок группы входов волатильности |
| LookBackDays | Целое число — Количество дней для расчёта волатильности |
| LowVolatility | Целое число — Порог низкой волатильности |
| MediumVolatility | Целое число — Порог средней волатильности |
| HighVolatility | Целое число — Порог высокой волатильности |
| PsychoticallyDeranged | Целое число — Порог крайней волатильности |
| pts | Текстовый параметр — Заголовок группы фильтра по свопу |
| CadPairsPositiveOnly | Переключатель — Торговать CAD-парами только при положительном свопе |
| AudPairsPositiveOnly | Переключатель — Торговать AUD-парами только при положительном свопе |
| NzdPairsPositiveOnly | Переключатель — Торговать NZD-парами только при положительном свопе |
| rec | Текстовый параметр — Заголовок группы настроек восстановления |
| UseRecovery | Переключатель — Включить модуль восстановления позиций |
| DC (Start_Recovery_at_trades) | Целое число — Начать восстановление после указанного количества заполненных сделок |
| Use1_1_3_3_Recovery | Переключатель — Использовать метод восстановления 1-1-3-3 |
| Use1_1_2_4_Recovery | Переключатель — Использовать метод восстановления 1-1-2-4 |
| Pippo's idea (Use1_2_6_Recovery) | Переключатель — Использовать метод восстановления 1-2-6 |
| ReEntryLineColour | Цвет — Цвет линии ре-entries на графике |
| BreakEvenLineColour | Цвет — Цвет линии безубытка на графике |
| ReEntryLinePips | Целое число — Отступ линии ре-entries в пипсах от цены входа |
| RecoveryBreakEvenProfitPips | Целое число — Прибыль в пипсах для перевода в безубыток при восстановлении |
| UseRecoveryTradeProfitLockin | Переключатель — Фиксировать прибыль успешных сделок восстановления |
| rts | Текстовый параметр — Заголовок группы восстановительного трейлинг-стопа |
| UseRecoveryTrailingStop | Переключатель — Использовать трейлинг-стоп для восстановления |
| AutomateRtsChoice | Целое число — Автоматический выбор трейлинг-стопа восстановления |
| RecoveryTrailingStopAt | Целое число — Уровень активации трейлинг-стопа восстановления в пипсах |
| RecoveryStopLossLineColour | Цвет — Цвет линии стоп-лосса восстановления на графике |
| msh | Текстовый параметр — Заголовок группы ручного управления внешними линиями |
| ManuallySetHiLo | Переключатель — Вручную задавать верхнюю и нижнюю границы ценового диапазона |
| AutoAdjustToNewHiLo | Переключатель — Автоматически подстраивать границы под новые максимумы и минимумы |
| sli | Текстовый параметр — Заголовок группы настроек стоп-лосса |
| UseStopLoss | Переключатель — Использовать стоп-лосс для сделок |
| StopLoss | Целое число — Стоп-лосс в пипсах от цены входа |
| tmm | Текстовый параметр — Заголовок группы модуля управления сделками |
| BE | Текстовый параметр — Метка настроек безубытка |
| BreakEven | Переключатель — Включить перевод стоп-лосса в безубыток |
| BreakEvenPips | Целое число — Расстояние в пипсах для перевода стоп-лосса в безубыток |
| BreakEvenProfit | Целое число — Прибыль в пипсах для установки безубытка |
| HideBreakEvenStop | Переключатель — Скрывать визуальный уровень стоп-лосса безубытка |
| PipsAwayFromVisualBE | Целое число — Отступ в пипсах от визуального уровня безубытка |
| JSL | Текстовый параметр — Метка настроек джампинг-стопа |
| JumpingStop | Переключатель — Включить джампинг-стоп |
| JumpingStopPips | Целое число — Шаг джампинг-стопа в пипсах |
| AddBEP | Переключатель — Добавлять прибыль безубытка при срабатывании джампинг-стопа |
| JumpAfterBreakevenOnly | Переключатель — Прыгать стоп только после установки безубытка |
| HideJumpingStop | Переключатель — Скрывать визуальный уровень джампинг-стопа |
| PipsAwayFromVisualJS | Целое число — Отступ в пипсах от визуального уровня джампинг-стопа |
| TSL | Текстовый параметр — Метка настроек трейлинг-стопа |
| TrailingStop | Переключатель — Включить трейлинг-стоп |
| TrailingStopPips | Целое число — Расстояние в пипсах для трейлинг-стопа |
Поиск по коду файла
???//+------------------------------------------------------------------+
#include <WinUser32.mqh>
#include <stdlib.mqh>
#define NL "\n"
#define GvPrefix "macman "
#define breakevenlinename "Break even line"
#define reentrylinename "Re entry line"
#define takeprofitlinename "Take profit line"
#define up "Market is trending up"
#define down "Market is trending down"
#define ranging "Market is ranging"
#define ct "Counter Trend"
#define wb "White Box"
#define SYMBOLS_MAX 1024
#define DEALS 0
#define BUY_LOTS 1
#define BUY_PRICE 2
#define SELL_LOTS 3
#define SELL_PRICE 4
#define NET_LOTS 5
#define PROFIT 6
/*
ChicagoRob's pairs: eurusd - usdjpy - gbpusd - audusd - eurjpy - usdcad - nzdusd - audjpy
int init()
int deinit()
int start()
void DisplayUserFeedback()
void GetSixths()
int GetBarCount()
void CalculateTrades()
void WhiteBoxTrading()
void TradeSlowkey()
bool IsTradingAllowed(string style)
bool PairsNotAtMaximumCheck()
bool DoesTradeExist(double price)
double CalculateStop(double price, int type)
bool SendSingleTrade(int type, string comment, double lotsize, double price, double stop, double take, int magic)
double CalculateStop(double price, int type)
void LookForTradeClosure()
void CloseAllTrades()
void CountPendingTrades()
void DrawTakeProfitLine(int type) not used
Void DoIdiotChecks()
void TradeDirectionBySwap()
void CalculateTradeClosureLine()
bool IsThisPairTradable()
----Indicator readings----
void ReadIndicatorValues()
double GetMa(int tf, int period, int FastMaShift, int method, int ap, int shift)
----Matt's Order Reliable library code
bool O_R_CheckForHistory(int ticket) Cheers Matt, You are a star.
void O_R_Sleep(double mean_time, double max_time)
----Volatility----
double CalculateVolatility(int period, int LookBack)
----Re-entry line----
void AddReEntryLine(double price)
void CalculateReEntryLinePips()
void ReplaceReEntryLine()
----Recovery----
void RecoveryModule()
void CountOpenTrades()
void CheckRecoveryTakeProfit()
int Analyze()
int SymbolsIndex(string SymbolName)
void RecoveryCandlesticktrailingStop()
void LockInRecoveryProfit()
----Trade management module----
void TradeManagementModule()
void BreakEvenStopLoss()
bool CheckForHiddenStopLossHit(int type, int iPipsAboveVisual, double stop )
void JumpingStopLoss()
void HiddenTakeProfit()
void HiddenStopLoss()
void TrailingStopLoss()
void CandlestickTrailingStopLoss()
bool CleanUpCtPendings()
void CloseAtGold()
void CloseAtGreen()
void CloseAtMiddle()
bool DeletePartnerPendingTrade(int type)
----Hedging----
void HedgingModule()
bool IsTradeAlreadyHedged(int ticket)
double GetRsi(int tf, int period, int shift)
*/
extern string gen="----General inputs----";
extern double Lot=0.08;
extern bool StopTrading=false;
extern bool TradeLong=true;
extern bool TradeShort=true;
extern int MaxTradesAllowedPerPair=5;
extern int MaxOpenPairsAllowed=5;
extern int PipsBufferFromTradeLine=5;
extern int MinPipsFromLastEntry=50;
extern double MaxSpread=120;
extern int TouchesRequired=0;
extern string tts="----Trade style choices----";
extern string ctt="Counter trend tradin";
extern bool CounterTrendTrading=true;
extern bool OnlyCtTradeForRecovery=false;
extern bool UseZeljko=true;
extern bool OnlyTradeCurrencyTwice=true;
extern string htr="White box hedge trading";
extern bool DoWhiteBoxTrading=true;
extern int WhiteBoxPips=10;
extern int PendingHedgePips=10;
extern int BoxBreakevenProfit=10;
extern bool CloseBoxTradesAtMagenta=true;
extern bool CloseBoxTradesAtGold=false;
extern bool CloseBoxTradesAtGreen=false;
extern string wbts="White box trading style";
extern bool UseOriginalMethod=true;
extern bool UseInvertedMethod=false;
extern bool UseSamePriceMethod=false;
extern bool UseSlowkey=false;
extern int SleepSecondsBetweenTrades=5;
extern string amc="----Available Margin checks----";
extern string sco="Scoobs";
extern bool UseScoobsMarginCheck=false;
extern string fk="ForexKiwi";
extern bool UseForexKiwi=true;
extern int FkMinimumMarginPercent=1500;
extern string bc="----BarCount----";
extern int BarCount=0;
extern bool UseMax=false;
extern bool UseChaserL=true;
extern string CCIHelp = "Hourly Period for CCI MA";
extern int CCIPeriod=120;
extern string gls="----Gold line stuff----";
extern bool BreakEvenAtGold=false;
extern int GoldLineBEP=10;
extern string acc="----Trade closure----";
extern bool CloseTradeAtGold=false;
extern bool CloseTradeAtGreen=false;
extern bool CloseTradeAtMiddleWhiteLine=false;
extern string acc1="AutoCalc over rides the above";
extern bool AutoCalcTradeClosureLine=true;
extern string vs="----Volatility inputs----";
extern int LookBackDays=20;
extern int LowVolatility=100;
extern int MediumVolatility=150;
extern int HighVolatility=200;
extern int PsychoticallyDeranged=250;
/*
extern string tpi="----Take profit----";
extern bool UseTplTp=false;
extern color TakeProfitLineColour=Blue;
*/
extern string pts="----Swap filter----";
extern bool CadPairsPositiveOnly=true;
extern bool AudPairsPositiveOnly=true;
extern bool NzdPairsPositiveOnly=true;
extern string rec="----Recovery----";
extern bool UseRecovery=true;
extern int Start_Recovery_at_trades=2; //DC
extern bool Use1_1_3_3_Recovery=false;
extern bool Use1_1_2_4_Recovery=false;
extern bool Use1_2_6_Recovery=true;//Pippo's idea
extern color ReEntryLineColour=Turquoise;
extern color BreakEvenLineColour=Blue;
extern int ReEntryLinePips=0;
extern int RecoveryBreakEvenProfitPips=20;
extern bool UseRecoveryTradeProfitLockin=false;
extern string rts="Recovery trailing stop";
extern bool UseRecoveryTrailingStop=false;
extern int AutomateRtsChoice=true;
extern int RecoveryTrailingStopAt=10;
extern color RecoveryStopLossLineColour=Red;
bool UseHardRecoveryStop=false;
extern string msh="----Manual control of outer lines----";
extern bool ManuallySetHiLo=false;
extern bool AutoAdjustToNewHiLo=false;
extern string sli="----Stop loss----";
extern bool UseStopLoss=false;
extern int StopLoss=0;
extern string tmm="----Trade management module----";
extern string BE="Break even settings";
extern bool BreakEven=false;
extern int BreakEvenPips=40;
extern int BreakEvenProfit=30;
extern bool HideBreakEvenStop=false;
extern int PipsAwayFromVisualBE=5;
extern string JSL="Jumping stop loss settings";
extern bool JumpingStop=false;
extern int JumpingStopPips=30;
extern bool AddBEP=false;
extern bool JumpAfterBreakevenOnly=true;
extern bool HideJumpingStop=false;
extern int PipsAwayFromVisualJS=10;
extern string TSL="Trailing stop loss settings";
extern bool TrailingStop=false;
extern int TrailingStopPips=50;
extern bool HideTrailingStop=false;
extern int PipsAwayFromVisualTS=10;
extern bool TrailAfterBreakevenOnly=false;
extern bool StopTrailAtPipsProfit=false;
extern int StopTrailPips=0;
extern string tcs="Candle trailing stop settings";
extern bool UseCandleTS=false;
extern string hsl1="Hidden stop loss settings";
extern bool HideStopLossEnabled=false;
extern int HiddenStopLossPips=20;
extern string htp="Hidden take profit settings";
extern bool HideTakeProfitEnabled=false;
extern int HiddenTakeProfitPips=20;
extern string hed="----Hedging----";
extern bool UseHedging=false;
extern bool MptmWillControlHedging=false;
extern int HedgeAtLossPips=500;
extern double HedgeLotsMiltiplier=2;
extern string atrh="Atr hedging";
extern bool UseAtrHedging=false;
extern int HedgeAtrPeriod=20;
extern int HedgeAtrTf=1440;
extern int HedgeAtrMultiplier=1;
extern string tt="----Trading hours----";
extern string Trade_Hours= "Set Morning & Evening Hours";
extern string Trade_Hoursi= "Use 24 hour, local time clock";
extern string Trade_Hours_M= "Morning Hours 0-12";
extern int start_hourm = 0;
extern int end_hourm = 12;
extern string Trade_Hours_E= "Evening Hours 12-24";
extern int start_houre = 12;
extern int end_houre = 24;
extern string fmai="----Moving averages----";
extern string fma="Fast MA";
extern int FastMaTF=0;//Time frame defaults to current chart
extern int FastMaPeriod=100;
extern int FastMaShift=0;//The MA Shift input
extern string fmame="Method: 0=sma; 1=ema; 2=smma; 3=lwma";
extern int FastMaMethod=0;
extern string fmaap="Applied price: 0=Close; 1=Open; 2=High";
extern string fmaap1="3=Low; 4=Median; 5=Typical; 6=Weighted";
extern int FastMaAppliedPrice=0;
extern string sma="Slow MA";
extern int SlowMaTF=0;//Time frame defaults to current chart
extern int SlowMaPeriod=200;
extern int SlowMaShift=0;//The MA Shift input
extern string smame="Method: 0=sma; 1=ema; 2=smma; 3=lwma";
extern int SlowMaMethod=0;
extern string smaap="Applie0 price: 0=Close; 1=Open; 2=High";
extern string smaap1="3=Low; 4=Median; 5=Typical; 6=Weighted";
extern int SlowMaAppliedPrice=0;
extern string mis="----Odds and ends----";
extern bool ShowManagementAlerts=true;
extern int DisplayGapSize=30;
int CurBars;
double BottomGoldLine;//Bottom, gold line
double BottomGreenLine;//Bottom, green line
double MiddleWhiteLine;//Middle, white line
double TopGreenLine;//Top, green line
double TopGoldLine;//Top, gold line
double TopLine, BottomLine;
double HalfTopLine, HalfBottomLine;
double WhiteBoxHigh, WhiteBoxLow;//For hedge trade entry
double MagentaCtBufferHigh, MagentaCtBufferLow;
bool ForcePendingTradeDeletion;
bool ForceAllTradeDeletion;
string Gap, ScreenMessage;
double TpLinePrice1;
int TpLinePipsFromWhite=10;
int TicketNo = -1;//Save the ticket no of a pending trade
bool BuyOpen, SellOpen;
int Touches=0;//Count the number of touches of the outer lines to trigger a trade
double OldBid;
double TradeNumber; //DC to use with recovery module
double BasketUpl;//Fopr keeping track of the upl of whether a group of trades should be in Recovery
double MostRecentTradePrice;//For making sure new trades are sent a min pips distance from an existing open trade
double RsiVal;
string trend;
bool HedgingInProgress;
int PipsMove=1;//Pips the market must move before a pending is modified
int OldCountOpenTrades;//From Jose Luis to help with keeping track of Recovery
int NoOfPairsTrading;//Keeps a tally of the number of pairs with open trades
string TradeDirection;//For White Box Slowkey trading method
int OldBars, OpenTrades, PendingTrades, Old5Bars, OldRecoverTrailBars;
bool BoxBuyOpen, BoxSellOpen;
int BoxBuyTicketNumber, BoxSellTicketNumber;
int TotalBuyTrades, TotalSellTrades;
bool CanTradeThisPair;//Will be false when this pair fails the currency can only trade twice filter, or the balanced trade filter
string BoxBuyTicketGv, BoxSellTicketGv;
int TicketStore;//Used by sendsinglegrade to store the ticket number of the most recent trade, for use in box trade gv setting
double FastMaVal, SlowMaVal;
double Volatility;
int D1Bars = 0;
int O_R_Setting_max_retries = 10;
double O_R_Setting_sleep_time = 4.0; /* seconds */
double O_R_Setting_sleep_max = 15.0; /* seconds */
int UserRelp;//Save the user's ReEntryLinePips in case user is not allowing auto-calc.
bool RecoveryInProgress, TpMoved;
int RecoveryLockProfitsAt=50;
int RecoveryLockInPips=10;
string ExtSymbols[SYMBOLS_MAX];
int ExtSymbolsTotal=0;
double ExtSymbolsSummaries[SYMBOLS_MAX][7];
int ExtLines=-1;
string ExtCols[8]={"Symbol",
"Deals",
"Buy lots",
"Buy price",
"Sell lots",
"Sell price",
"Net lots",
"Profit"};
int ExtShifts[8]={ 10, 80, 130, 180, 260, 310, 390, 460 };
int ExtVertShift=14;
double buy_price=0.0;
double sell_price=0.0;
void DisplayUserFeedback()
{
if (IsTesting() && !IsVisualMode()) return (0);
if (IsTesting() ) return (0);
ScreenMessage = "";
ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
double i;
int m,s;
m=Time[0]+Period()*60-CurTime();
i=m/60.0;
s=m%60;
m=(m-m%60)/60;
ScreenMessage = StringConcatenate(ScreenMessage,Gap, m + " minutes " + s + " seconds left to bar end", NL);
/*
extern bool Primary_trades=true;
extern int PipsBufferFromTradeLine=5;
extern bool Secondary_trades=true;
extern bool Tertiary_trades=true;
extern double Lot=0.02;
extern double Secondary_trade_Lot_size=0.02;
extern double Tertiary_trade_Lot_size=0.01;
*/
ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Lot: ", Lot);
ScreenMessage = StringConcatenate(ScreenMessage, ": PipsBufferFromTradeLine: ", PipsBufferFromTradeLine, NL);
if (TouchesRequired > 1) ScreenMessage = StringConcatenate(ScreenMessage, ": Touches required to trigger trades: ", TouchesRequired, ": Touches so far ", Touches, NL);
if (TradeLong == true) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading long ", NL);
if (TradeShort == true) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading short ", NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Criminal's minimum lot size: ", MarketInfo(Symbol(), MODE_MINLOT), NL);
if (MarketInfo(Symbol(), MODE_SPREAD) <= MaxSpread) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "MaxSpread: ", MaxSpread, " Spread is ", MarketInfo(Symbol(), MODE_SPREAD), NL);
else ScreenMessage = StringConcatenate(ScreenMessage,Gap, "MaxSpread: ", MaxSpread, " &&&&& SPREAD IS ", MarketInfo(Symbol(), MODE_SPREAD), " &&&&&", NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Criminal's swap for long trades: ", MarketInfo(Symbol(), MODE_SWAPLONG), NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Criminal's swap for short trades: ", MarketInfo(Symbol(), MODE_SWAPSHORT), NL);
static int Old5minbars;
if (Old5minbars != iBars(Symbol(), PERIOD_M5) )
{
PairsNotAtMaximumCheck();
Old5minbars = iBars(Symbol(), PERIOD_M5);
}//if (Old5minbars != iBars(Symbol(), PERIOD_M5)
if (NoOfPairsTrading >= MaxOpenPairsAllowed) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading only allowed for Recovery and Hedging, if enabled. Pairs trading: ", NoOfPairsTrading, NL, NL);
else ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Pairs trading: ", NoOfPairsTrading, NL, NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading hours", NL);
if (start_hourm == 0 && end_hourm == 12 && start_houre && end_houre == 24) ScreenMessage = StringConcatenate(ScreenMessage,Gap, " 24H trading", NL);
else
{
ScreenMessage = StringConcatenate(ScreenMessage,Gap, " start_hourm: ", DoubleToStr(start_hourm, 2),
": end_hourm: ", DoubleToStr(end_hourm, 2), NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, " end_houre: ", DoubleToStr(start_hourm, 2),
": end_houre: ", DoubleToStr(end_hourm, 2), NL);
}//else
ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "BarCount = ", BarCount, NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Recovery starts at ", Start_Recovery_at_trades, " filled trades", NL);
if (RecoveryInProgress) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Recovery is in progress", NL);
if(Digits == 2 || Digits == 4) m = 1;
if(Digits == 3 || Digits == 5) m = 10;
if(Digits == 6) m = 100;
if(Digits == 7) m = 1000;
ScreenMessage = StringConcatenate(ScreenMessage, Gap, "Volatility = ", Volatility * m, ": ReEntryLinePips = ", ReEntryLinePips, NL);
if (UseRecoveryTrailingStop) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Using Recovery trailing stop. RecoveryTrailingStopAt = ", RecoveryTrailingStopAt, NL);
if (StopTrading) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading suspended", NL);
if (DoWhiteBoxTrading)
{
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading the white box", NL);
if (UseOriginalMethod) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Using the Original method", NL);
if (UseInvertedMethod) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Using the Inverted method", NL);
if (UseSamePriceMethod) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Using the Immediate Hedge method", NL);
if (UseSlowkey) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Using the UseSlowkey single trade method", NL);
if ( CloseBoxTradesAtMagenta) ScreenMessage =StringConcatenate(ScreenMessage,Gap, "Close trades at Magenta", NL);
if ( CloseBoxTradesAtGold) ScreenMessage =StringConcatenate(ScreenMessage,Gap, "Close trades at Gold", NL);
if ( CloseBoxTradesAtGreen) ScreenMessage =StringConcatenate(ScreenMessage,Gap, "Close trades at Green", NL);
}//if (WhiteBoxTrading)
ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trade management: ", NL);
if (BreakEvenAtGold) ScreenMessage = StringConcatenate(ScreenMessage,Gap, " BreakEvenAtGold = true. GoldLineBEP = ", GoldLineBEP, NL);
else ScreenMessage = StringConcatenate(ScreenMessage,Gap, "BreakEvenAtGold = False", NL);
if (CloseTradeAtMiddleWhiteLine) ScreenMessage = StringConcatenate(ScreenMessage, Gap, "CloseTradeAtMiddleWhiteLine = true", NL);
if (CloseTradeAtGreen) ScreenMessage = StringConcatenate(ScreenMessage, Gap, "CloseTradeAtGreen = true", NL);
if (CloseTradeAtGold) ScreenMessage = StringConcatenate(ScreenMessage, Gap, "CloseTradeAtGold = true", NL);
if (!CloseTradeAtMiddleWhiteLine && !CloseTradeAtGreen && !CloseTradeAtGold) ScreenMessage = StringConcatenate(ScreenMessage, Gap, ": No trade closure option selected", NL);
ScreenMessage = StringConcatenate(ScreenMessage, Gap, "BoxBuyTicketNumber: ", BoxBuyTicketNumber, NL);
ScreenMessage = StringConcatenate(ScreenMessage, Gap, "BoxSellTicketNumber: ", BoxSellTicketNumber, NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
if (BreakEven)
{
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Breakeven is set to ", BreakEvenPips, " with BreakEvenProfit = ", BreakEvenProfit, NL);
}//if (BreakEven)
if (JumpingStop)
{
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Jumping stop is set to ", JumpingStopPips);
if (AddBEP) ScreenMessage = StringConcatenate(ScreenMessage,": BreakEvenProfit = ", BreakEvenProfit);
if (JumpAfterBreakevenOnly) ScreenMessage = StringConcatenate(ScreenMessage, ": JumpAfterBreakevenOnly = true");
ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
}//if (JumpingStop)
if (TrailingStop)
{
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trailing stop is set to ", TrailingStopPips, " pips", NL);
}//if (BreakEven)
if (UseCandleTS)
{
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Using candlestick trailing stop", NL);
}//if (UseCandleTS)
if (UseHedging && !MptmWillControlHedging)
{
if (!UseAtrHedging) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Hedging is enabled ", " with HedgeAtLossPips = ", HedgeAtLossPips, ": HedgeLotsMiltiplier = ", HedgeLotsMiltiplier, NL);
if (UseAtrHedging) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Hedging is enabled ",
" using Atr: (Period ", HedgeAtrPeriod, ": Time frame ", HedgeAtrTf,
": Atr multiplier ", HedgeAtrMultiplier, " )", NL);
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Rsi D1 trend: ", trend, ": Val = ", RsiVal, NL);
}//if (UseHedging)
if (UseHedging && MptmWillControlHedging)
{
ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Hedging is enabled. MPTM will control all hedging activities, so make sure it is running.", NL);
}//if (UseHedging && MptmWillControlHedging)
Comment(ScreenMessage);
}//void DisplayUserFeedback()
int init()
{
// код доступен только после оплаты
}
int deinit()
{
Comment("");
ObjectDelete("zerosixth");
ObjectDelete("onesixth");
ObjectDelete("twosixth");
ObjectDelete("threesixth");
ObjectDelete("foursixth");
ObjectDelete("fivesixth");
ObjectDelete("sixsixth");
ObjectDelete("halfbottomsixth");
ObjectDelete("halftopsixth");
ObjectDelete("whitehigh");
ObjectDelete("whitelow");
ObjectDelete("CT buffer high");
ObjectDelete("CT buffer low");
return(0);
}
void DoIdiotChecks()
{
if (Start_Recovery_at_trades < 2) Start_Recovery_at_trades = 2;
if (Lot < MarketInfo(Symbol(), MODE_MINLOT)) Lot = MarketInfo(Symbol(), MODE_MINLOT);
}//End Void DoIdiotChecks()
int GetBarCount()
{
double multiplier=1;
if (Period() == PERIOD_M1) multiplier = 60;
if (Period() == PERIOD_M5) multiplier = 12;
if (Period() == PERIOD_M15) multiplier = 4;
if (Period() == PERIOD_M30) multiplier = 2;
if (Period() == PERIOD_H1) multiplier = 1;
if (Period() == PERIOD_H4) multiplier = 0.25;
if (Period() == PERIOD_D1) multiplier = 0.25 / 6;
if (UseMax)
{
if (StringSubstr(Symbol(), 0, 6) == "AUDCAD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "AUDCHF") { BarCount = 210; }
if (StringSubstr(Symbol(), 0, 6) == "AUDJPY") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "AUDNZD") { BarCount = 20; }
if (StringSubstr(Symbol(), 0, 6) == "AUDSGD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "AUDUSD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "CADCHF") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "CADJPY") { BarCount = 180; }
if (StringSubstr(Symbol(), 0, 6) == "CHFJPY") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "CHFSGD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "EURAUD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "EURCAD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "EURCHF") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "EURGBP") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "EURJPY") { BarCount = 180; }
if (StringSubstr(Symbol(), 0, 6) == "EURNZD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "EURSGD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "EURUSD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "GBPAUD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "GBPCAD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "GBPCHF") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "GBPJPY") { BarCount = 180; }
if (StringSubstr(Symbol(), 0, 6) == "GBPUSD") { BarCount = 155; }
if (StringSubstr(Symbol(), 0, 6) == "NZDCAD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "NZDCHF") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "NZDJPY") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "NZDUSD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "SGDJPY") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "USDCAD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "USDCHF") { BarCount = 180; }
if (StringSubstr(Symbol(), 0, 6) == "USDHKD") { BarCount = 170; }
if (StringSubstr(Symbol(), 0, 6) == "USDJPY") { BarCount = 180; }
if (StringSubstr(Symbol(), 0, 6) == "USDSGD") { BarCount = 170; }
double dBarCount = BarCount;
BarCount = MathRound(dBarCount/Period()*60);
}//if (UseMax)
if (UseChaserL)
{
int IndTimeframe=PERIOD_H1;
int PeriodCount=0;
int PeriodTotal=0;
int TempAbovePer=0;
int TempBelowPer=0;
int CCIPos=0;
int TempCCIPos=0;
CurBars=iBars(NULL,IndTimeframe);
int IndBars=MathMin(720,CurBars);
for(int i=1;i<=IndBars;i++)
{
TempCCIPos=CCIPos;
if(iCCI(NULL,IndTimeframe,CCIPeriod,PRICE_WEIGHTED,i)>100 && CCIPos != 1)
{
TempAbovePer=i;
CCIPos=1;
}
if(iCCI(NULL,IndTimeframe,CCIPeriod,PRICE_WEIGHTED,i)<-100 && CCIPos != -1)
{
TempBelowPer=i;
CCIPos=-1;
}
if(TempAbovePer>0 && TempBelowPer>0 && CCIPos != TempCCIPos && CCIPos!=0)
{
PeriodCount++;
PeriodTotal+=MathAbs(TempAbovePer-TempBelowPer);
}
}
if(PeriodCount==0) BarCount=170*multiplier;
else BarCount=PeriodTotal/PeriodCount*multiplier;
}//if (UseChaserL)
}//End of int GetBarCount()
double GetMa(int tf, int period, int FastMaShift, int method, int ap, int shift)
{
return(iMA(NULL, tf, period, FastMaShift, method, ap, shift) );
}//End double GetMa(int tf, int period, int FastMaShift, int method, int ap, int shift)
void ReadIndicatorValues()
{
FastMaVal = GetMa(FastMaTF, FastMaPeriod, FastMaShift, FastMaMethod, FastMaAppliedPrice, 0);
SlowMaVal = GetMa(SlowMaTF, SlowMaPeriod, SlowMaShift, SlowMaMethod, SlowMaAppliedPrice, 0);
TradeDirection = ranging;
if (FastMaVal > SlowMaVal) TradeDirection = up;
if (FastMaVal < SlowMaVal) TradeDirection = down;
}//void ReadIndicatorValues()
void CalculateTradeClosureLine()
{
CloseTradeAtGold=false;
CloseTradeAtGreen=false;
CloseTradeAtMiddleWhiteLine=false;
int m;
if(Digits == 2 || Digits == 4) m = 1;
if(Digits == 3 || Digits == 5) m = 10;
if(Digits == 6) m = 100;
if(Digits == 7) m = 1000;
Volatility*= m;
if (Volatility < LowVolatility) CloseTradeAtGold = true;
if (Volatility >= LowVolatility && Volatility < PsychoticallyDeranged) CloseTradeAtGreen = true;
if (Volatility >= PsychoticallyDeranged) CloseTradeAtMiddleWhiteLine = true;
Volatility/= m;
}//void CalculateTradeClosureLine()
void GetSixths()
{
double ctgl = TopGoldLine;
double cbgl = BottomGoldLine;
bool DrawLines = false;
if (ObjectFind("sixsixth") == -1 || ObjectFind("zerosixth") == -1) DrawLines = true;//Forces a line draw on initialisation
if (!ManuallySetHiLo || DrawLines)
{
TopLine = High[iHighest(NULL,0,MODE_HIGH,BarCount,1)];
if (High[0] > TopLine) TopLine = NormalizeDouble(High[0], Digits);
BottomLine = Low[iLowest(NULL,0,MODE_LOW,BarCount,1)];
if (Low[0] < BottomLine) BottomLine = NormalizeDouble(Low[0], Digits);
}//if (!ManuallySetHiLo)
if (ManuallySetHiLo && ObjectFind("sixsixth") > -1)
{
TopLine = ObjectGet("sixsixth", OBJPROP_PRICE1);
if (AutoAdjustToNewHiLo && High[0] > TopLine) TopLine = NormalizeDouble(High[0], Digits);
BottomLine = ObjectGet("zerosixth", OBJPROP_PRICE1);
if (AutoAdjustToNewHiLo && Low[0] < BottomLine) BottomLine = NormalizeDouble(Low[0], Digits);
}//if (!ManuallySetHiLo)
double value = TopLine - BottomLine;
double sixth = value/6;
double valueS = (value*(MathPow(10,Digits)));
double sixthS = (sixth*(MathPow(10,Digits)));
HalfTopLine = NormalizeDouble(BottomLine+sixth+sixth+sixth+sixth+sixth+(sixth / 2), Digits);
HalfBottomLine = NormalizeDouble(BottomLine+(sixth / 2),Digits);
BottomGoldLine = NormalizeDouble(BottomLine+sixth, Digits);
BottomGreenLine = NormalizeDouble(BottomLine+sixth+sixth, Digits);
MiddleWhiteLine = NormalizeDouble(BottomLine+sixth+sixth+sixth, Digits);
TopGreenLine = NormalizeDouble(BottomLine+sixth+sixth+sixth+sixth, Digits);
TopGoldLine = NormalizeDouble(BottomLine+sixth+sixth+sixth+sixth+sixth, Digits);
MagentaCtBufferHigh = NormalizeDouble(TopLine - (PipsBufferFromTradeLine * Point), Digits);
MagentaCtBufferLow = NormalizeDouble(BottomLine + (PipsBufferFromTradeLine * Point), Digits);
if (DoWhiteBoxTrading)
{
WhiteBoxHigh = NormalizeDouble(MiddleWhiteLine + (WhiteBoxPips * Point), Digits);
WhiteBoxLow = NormalizeDouble(MiddleWhiteLine - (WhiteBoxPips * Point), Digits);
}//if (DoWhiteBoxTrading)
if((ctgl != TopGoldLine || cbgl != BottomGoldLine) && TicketNo > -1)
{
if (OrderSelect(TicketNo, SELECT_BY_TICKET) )
{
bool result = true;
if (OrderType() == OP_BUYSTOP && CounterTrendTrading)
{
if (OrderOpenPrice() - HalfBottomLine >= PipsMove * Point) result = OrderModify(OrderTicket(), HalfBottomLine, OrderStopLoss(), OrderTakeProfit(), 0, Green);
CalculateReEntryLinePips();
if (ReEntryLinePips == 0) Emergency_RELP_fix();//Fix for zero value ReEntryLinePips
if (result) AddReEntryLine(NormalizeDouble(HalfBottomLine - (ReEntryLinePips * Point), Digits) );
}//if (OrderType() == OP_BUYSTOP)
if (OrderType() == OP_SELLSTOP && CounterTrendTrading)
{
if (HalfTopLine - OrderOpenPrice() >= PipsMove * Point) result = OrderModify(OrderTicket(), HalfTopLine, OrderStopLoss(), OrderTakeProfit(), 0, Red);
CalculateReEntryLinePips();
if (ReEntryLinePips == 0) Emergency_RELP_fix();//Fix for zero value ReEntryLinePips
if (result) AddReEntryLine(NormalizeDouble(HalfTopLine + (ReEntryLinePips * Point), Digits) );
}//if (OrderType() == OP_SELLSTOP
if (!result)
{
int err=GetLastError();
if (ShowManagementAlerts==true) Alert("Order open price mod ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//if (OrderSelect(TicketNo, SELECT_BY_TICKET) )
if (OrderSelect(BoxBuyTicketNumber, SELECT_BY_TICKET) && OrderType() == OP_BUYSTOP)
{
double price = NormalizeDouble(WhiteBoxHigh + (PendingHedgePips * Point), Digits);
result = OrderModify(OrderTicket(),price,OrderStopLoss(),OrderTakeProfit(),0,CLR_NONE);
if (!result)
{
err=GetLastError();
Alert("Box trade price mod ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Box trade price mod ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//if (OrderSelect(BoxBuyTicketNumber, SELECT_BY_TICKET)
if (OrderSelect(BoxSellTicketNumber, SELECT_BY_TICKET) && OrderType() == OP_SELLSTOP)
{
price = NormalizeDouble(WhiteBoxLow - (PendingHedgePips * Point), Digits);
result = OrderModify(OrderTicket(),price,OrderStopLoss(),OrderTakeProfit(),0,CLR_NONE);
if (!result)
{
err=GetLastError();
Alert("Box trade price mod ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Box trade price mod ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//if (OrderSelect(BoxSellTicketNumber, SELECT_BY_TICKET) && OrderType() == OP_SELLSTOP)
}//if((ctgl != TopGoldLine || cbgl != BottomGoldLine) && TicketNo > -1)
if (!IsTesting() || IsVisualMode() )
{
double tl = ObjectGet("fivesixth", OBJPROP_PRICE1);
double bl = ObjectGet("onesixth", OBJPROP_PRICE1);
if(tl != TopGoldLine || bl != BottomGoldLine)
{
if (ObjectFind("zerosixth") == -1)
{
ObjectCreate("zerosixth",1,0,TimeCurrent(),BottomLine);
ObjectSet("zerosixth",OBJPROP_COLOR,Magenta);
ObjectSet("zerosixth",OBJPROP_STYLE,STYLE_SOLID);
ObjectSet("zerosixth",OBJPROP_WIDTH,2);
}//if (ObjectFind("zerosixth") == -1)
else ObjectMove("zerosixth",0,TimeCurrent(),BottomLine);
if (ObjectFind("halfbottomsixth") == -1)
{
ObjectCreate("halfbottomsixth",1,0,TimeCurrent(),HalfBottomLine);
ObjectSet("halfbottomsixth",OBJPROP_COLOR,Magenta);
ObjectSet("halfbottomsixth",OBJPROP_STYLE,STYLE_DASH);
ObjectSet("halfbottomsixth",OBJPROP_WIDTH,1);
}//if (ObjectFind("halfbottomsixth") == -1)
else ObjectMove("halfbottomsixth",0,TimeCurrent(),HalfBottomLine);
if (ObjectFind("onesixth") == -1)
{
ObjectCreate("onesixth",1,0,TimeCurrent(),BottomGoldLine);
ObjectSet("onesixth",OBJPROP_COLOR,Gold);
ObjectSet("onesixth",OBJPROP_STYLE,STYLE_SOLID);
ObjectSet("onesixth",OBJPROP_WIDTH,2);
}//if (ObjectFind("onesixth") == -1)
else ObjectMove("onesixth",0,TimeCurrent(),BottomGoldLine);
if (ObjectFind("twosixth") == -1)
{
ObjectCreate("twosixth",1,0,TimeCurrent(),BottomGreenLine);
ObjectSet("twosixth",OBJPROP_COLOR,Green);
ObjectSet("twosixth",OBJPROP_STYLE,STYLE_SOLID);
ObjectSet("twosixth",OBJPROP_WIDTH,2);
}//if (ObjectFind(
else ObjectMove("twosixth",0,TimeCurrent(),BottomGreenLine);
if (ObjectFind("threesixth") == -1)
{
ObjectCreate("threesixth",1,0,TimeCurrent(),MiddleWhiteLine);
ObjectSet("threesixth",OBJPROP_COLOR,White);
ObjectSet("threesixth",OBJPROP_STYLE,STYLE_SOLID);
ObjectSet("threesixth",OBJPROP_WIDTH,2);
}//if (ObjectFind(
else ObjectMove("threesixth",0,TimeCurrent(),MiddleWhiteLine);
if (ObjectFind("foursixth") == -1)
{
ObjectCreate("foursixth",1,0,TimeCurrent(),TopGreenLine);
ObjectSet("foursixth",OBJPROP_COLOR,Green);
ObjectSet("foursixth",OBJPROP_STYLE,STYLE_SOLID);
ObjectSet("foursixth",OBJPROP_WIDTH,2);
}//if (ObjectFind(
else ObjectMove("foursixth",0,TimeCurrent(),TopGreenLine);
if (ObjectFind("fivesixth") == -1)
{
ObjectCreate("fivesixth",1,0,TimeCurrent(),TopGoldLine);
ObjectSet("fivesixth",OBJPROP_COLOR,Gold);
ObjectSet("fivesixth",OBJPROP_STYLE,STYLE_SOLID);
ObjectSet("fivesixth",OBJPROP_WIDTH,2);
}//if (ObjectFind(
else ObjectMove("fivesixth",0,TimeCurrent(),TopGoldLine);
if (ObjectFind("halftopsixth") == -1)
{
ObjectCreate("halftopsixth",1,0,TimeCurrent(),HalfTopLine);
ObjectSet("halftopsixth",OBJPROP_COLOR,Magenta);
ObjectSet("halftopsixth",OBJPROP_STYLE,STYLE_DASH);
ObjectSet("halftopsixth",OBJPROP_WIDTH,1);
}//if (ObjectFind("halftopsixth") == -1)
else ObjectMove("halftopsixth",0,TimeCurrent(),HalfTopLine);
if (ObjectFind("sixsixth") == -1)
{
ObjectCreate("sixsixth",1,0,TimeCurrent(),TopLine);
ObjectSet("sixsixth",OBJPROP_COLOR,Magenta);
ObjectSet("sixsixth",OBJPROP_STYLE,STYLE_SOLID);
ObjectSet("sixsixth",OBJPROP_WIDTH,2);
}//if (ObjectFind("sixsixth") == -1)
else ObjectMove("sixsixth",0,TimeCurrent(),TopLine);
if (ObjectFind("CT buffer high") == -1)
{
ObjectCreate("CT buffer high",1,0,TimeCurrent(),MagentaCtBufferHigh);
ObjectSet("CT buffer high",OBJPROP_COLOR,Magenta);
ObjectSet("CT buffer high",OBJPROP_STYLE,STYLE_DOT);
ObjectSet("CT buffer high",OBJPROP_WIDTH,1);
}//if (ObjectFind("CT buffer high") == -1)
else ObjectMove("CT buffer high",0,TimeCurrent(),MagentaCtBufferHigh);
if (ObjectFind("CT buffer low") == -1)
{
ObjectCreate("CT buffer low",1,0,TimeCurrent(),MagentaCtBufferLow);
ObjectSet("CT buffer low",OBJPROP_COLOR,Magenta);
ObjectSet("CT buffer low",OBJPROP_STYLE,STYLE_DOT);
ObjectSet("CT buffer low",OBJPROP_WIDTH,1);
}//if (ObjectFind("CT buffer low") == -1)
else ObjectMove("CT buffer low",0,TimeCurrent(),MagentaCtBufferLow);
if (DoWhiteBoxTrading)
{
if (ObjectFind("whitehigh") == -1)
{
ObjectCreate("whitehigh",1,0,TimeCurrent(),WhiteBoxHigh);
ObjectSet("whitehigh",OBJPROP_COLOR,White);
ObjectSet("whitehigh",OBJPROP_STYLE,STYLE_DOT);
ObjectSet("whitehigh",OBJPROP_WIDTH,1);
}//if (ObjectFind("whitehigh") == -1)
else ObjectMove("whitehigh",0,TimeCurrent(),WhiteBoxHigh);
if (ObjectFind("whitelow") == -1)
{
ObjectCreate("whitelow",1,0,TimeCurrent(),WhiteBoxLow);
ObjectSet("whitelow",OBJPROP_COLOR,White);
ObjectSet("whitelow",OBJPROP_STYLE,STYLE_DOT);
ObjectSet("whitelow",OBJPROP_WIDTH,1);
}//if (ObjectFind("whitelow") == -1)
else ObjectMove("whitelow",0,TimeCurrent(),WhiteBoxLow);
}//if (DoWhiteBoxTrading)
}//if(ctgl != TopGoldLine || cbgl != BottomGoldLine)
}//if (!IsTesting() && !IsVisualMode() )
}//void GetSixths()
bool CleanUpCtPendings()
{
bool success = true, result = true;
int cc;
if (PendingTrades > 1)
{
bool PrimaryFound=false;
for (cc = OrdersTotal() - 1; cc >= 0; cc--)
{
if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
if (OrderSymbol() == Symbol() && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP))
{
if (!PrimaryFound)
{
PrimaryFound = true;
int type = OrderType();
}
else
{
if (PrimaryFound)
{
if (OrderType() != type) return (0);//Stops deletion of opposite-direction box pending
result = OrderDelete(OrderTicket());
Sleep(1000);
if (result)
{
PendingTrades--;
if (PendingTrades == 1) return(success);
}//if (result)
else return(false);
}//if (PrimaryFound)
}//else
}//if (OrderSymbol() == Symbol() && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP))
}//for (cc = OrdersTotal() - 1; cc >= 0; cc--)
}//if (PendingTrades > 1)
else return(success);
}//End bool CleanUpCtPendings()
bool CheckForHiddenStopLossHit(int type, int iPipsAboveVisual, double stop )
{
if (type == OP_BUY)
{
double sl = NormalizeDouble(stop + (iPipsAboveVisual * Point), Digits);
if (Bid <= sl)
{
while(IsTradeContextBusy()) Sleep(100);
bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5000, CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());
}//if (result)
else
{
int err=GetLastError();
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//else
}//if (Bid <= sl)
}//if (type = OP_BUY)
if (type == OP_SELL)
{
sl = NormalizeDouble(stop - (iPipsAboveVisual * Point), Digits);
if (Ask >= sl)
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5000, CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());
}//if (result)
else
{
err=GetLastError();
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//else
}//if (Ask >= sl)
}//if (type = OP_SELL)
return(result);
}//End bool CheckForHiddenStopLossHit(int type, int iPipsAboveVisual, double stop )
void BreakEvenStopLoss() // Move stop loss to breakeven
{
if (HideBreakEvenStop)
{
bool TradeClosed = CheckForHiddenStopLossHit(OrderType(), PipsAwayFromVisualBE, OrderStopLoss() );
if (TradeClosed) return (0);//Trade has closed, so nothing else to do
}//if (HideBreakEvenStop)
bool result;
if (OrderType()==OP_BUY)
{
if (Ask >= OrderOpenPrice() + (Point*BreakEvenPips) &&
OrderStopLoss()<OrderOpenPrice())
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()+(BreakEvenProfit*Point), Digits),OrderTakeProfit(),0,CLR_NONE);
if (result && ShowManagementAlerts==true) Alert("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
Print("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
if (!result)
{
int err=GetLastError();
if (ShowManagementAlerts==true) Alert("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//if (Ask >= OrderOpenPrice()
} //if (OrderType()==OP_BUY)
if (OrderType()==OP_SELL)
{
if (Bid <= OrderOpenPrice() - (Point*BreakEvenPips) &&
(OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0))
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()-(BreakEvenProfit*Point), Digits),OrderTakeProfit(),0,CLR_NONE);
if (result && ShowManagementAlerts==true) Alert("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
Print("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
if (!result && ShowManagementAlerts)
{
err=GetLastError();
if (ShowManagementAlerts==true) Alert("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//if (Bid <= OrderOpenPrice()
}//if (OrderType()==OP_SELL)
} // End BreakevenStopLoss sub
void JumpingStopLoss()
{
if (JumpAfterBreakevenOnly && OrderType()==OP_BUY)
{
if(OrderStopLoss()<OrderOpenPrice()) return(0);
}
if (JumpAfterBreakevenOnly && OrderType()==OP_SELL)
{
if(OrderStopLoss()>OrderOpenPrice() || OrderStopLoss() == 0) return(0);
}
double sl=OrderStopLoss(); //Stop loss
if (OrderType()==OP_BUY)
{
if (HideJumpingStop)
{
bool TradeClosed = CheckForHiddenStopLossHit(OP_BUY, PipsAwayFromVisualJS, OrderStopLoss() );
if (TradeClosed) return (0);//Trade has closed, so nothing else to do
}//if (HideJumpingStop)
if (sl==0 || sl<OrderOpenPrice())
{
if (Ask >= OrderOpenPrice() + (JumpingStopPips*Point))
{
sl=OrderOpenPrice();
if (AddBEP==true) sl=sl+(BreakEvenProfit*Point); // If user wants to add a profit to the break even
while(IsTradeContextBusy()) Sleep(100);
bool result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Jumping stop set at breakeven ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
Print("Jumping stop set at breakeven: ", OrderSymbol(), ": SL ", sl, ": Ask ", Bid);
}//if (result)
if (!result)
{
int err=GetLastError();
if (ShowManagementAlerts) Alert(OrderSymbol(), "Ticket ", OrderTicket(), " buy trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
Print(OrderSymbol(), " buy trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
}//if (!result)
return(0);
}//if (Ask >= OrderOpenPrice() + (JumpingStopPips*Point))
} //close if (sl==0 || sl<OrderOpenPrice()
if (Bid>= sl + ((JumpingStopPips*2)*Point) && sl>= OrderOpenPrice())
{
sl=sl+(JumpingStopPips*Point);
while(IsTradeContextBusy()) Sleep(100);
result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Jumping stop set at ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
Print("Jumping stop set: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
}//if (result)
if (!result)
{
err=GetLastError();
if (ShowManagementAlerts) Alert(OrderSymbol(), " buy trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
Print(OrderSymbol(), " buy trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
}//if (!result)
}// if (Bid>= sl + (JumpingStopPips*Point) && sl>= OrderOpenPrice())
}//if (OrderType()==OP_BUY)
if (OrderType()==OP_SELL)
{
if (HideJumpingStop)
{
TradeClosed = CheckForHiddenStopLossHit(OP_SELL, PipsAwayFromVisualJS, OrderStopLoss() );
if (TradeClosed) return (0);//Trade has closed, so nothing else to do
}//if (HideJumpingStop)
if (sl==0 || sl>OrderOpenPrice())
{
if (Ask <= OrderOpenPrice() - (JumpingStopPips*Point))
{
sl = OrderOpenPrice();
if (AddBEP==true) sl=sl-(BreakEvenProfit*Point); // If user wants to add a profit to the break even
while(IsTradeContextBusy()) Sleep(100);
result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
if (result)
{
}//if (result)
if (!result)
{
err=GetLastError();
if (ShowManagementAlerts) Alert(OrderSymbol(), " sell trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
Print(OrderSymbol(), " sell trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
}//if (!result)
return(0);
}//if (Ask <= OrderOpenPrice() - (JumpingStopPips*Point))
} // if (sl==0 || sl>OrderOpenPrice()
if (Bid<= sl - ((JumpingStopPips*2)*Point) && sl<= OrderOpenPrice())
{
sl=sl-(JumpingStopPips*Point);
while(IsTradeContextBusy()) Sleep(100);
result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Jumping stop set at ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
Print("Jumping stop set: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
}//if (result)
if (!result)
{
err=GetLastError();
if (ShowManagementAlerts) Alert(OrderSymbol(), " sell trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
Print(OrderSymbol(), " sell trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
}//if (!result)
}// close if (Bid>= sl + (JumpingStopPips*Point) && sl>= OrderOpenPrice())
}//if (OrderType()==OP_SELL)
} //End of JumpingStopLoss sub
void HiddenStopLoss()
{
if (OrderType() == OP_BUY)
{
double sl = NormalizeDouble(OrderOpenPrice() - (HiddenStopLossPips * Point), Digits);
if (Bid <= sl)
{
while(IsTradeContextBusy()) Sleep(100);
bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());
}//if (result)
else
{
int err=GetLastError();
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//else
}//if (Bid <= sl)
}//if (OrderType() == OP_BUY)
if (OrderType() == OP_SELL)
{
sl = NormalizeDouble(OrderOpenPrice() + (HiddenStopLossPips * Point), Digits);
if (Ask >= sl)
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());
}//if (result)
else
{
err=GetLastError();
if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//else
}//if (Ask >= sl)
}//if (OrderType() == OP_SELL)
}//End void HiddenStopLoss()
void HiddenTakeProfit()
{
if (OrderType() == OP_BUY)
{
double tp = NormalizeDouble(OrderOpenPrice() + (HiddenTakeProfitPips * Point), Digits);
if (Bid >= tp)
{
while(IsTradeContextBusy()) Sleep(100);
bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());
}//if (result)
else
{
int err=GetLastError();
if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//else
}//if (Ask >= tp)
}//if (OrderType() == OP_BUY)
if (OrderType() == OP_SELL)
{
tp = NormalizeDouble(OrderOpenPrice() - (HiddenTakeProfitPips * Point), Digits);
if (Ask <= tp)
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
if (result)
{
if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());
}//if (result)
else
{
err=GetLastError();
if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//else
}//if (Bid <= tp)
}//if (OrderType() == OP_SELL)
}//End void HiddenTakeProfit()
void TrailingStopLoss()
{
if (TrailAfterBreakevenOnly && OrderType()==OP_BUY)
{
if(OrderStopLoss()<OrderOpenPrice()) return(0);
}
if (TrailAfterBreakevenOnly && OrderType()==OP_SELL)
{
if(OrderStopLoss()>OrderOpenPrice()) return(0);
}
bool result;
double sl=OrderStopLoss(); //Stop loss
double BuyStop=0, SellStop=0;
if (OrderType()==OP_BUY)
{
if (HideTrailingStop)
{
bool TradeClosed = CheckForHiddenStopLossHit(OP_BUY, PipsAwayFromVisualTS, OrderStopLoss() );
if (TradeClosed) return (0);//Trade has closed, so nothing else to do
}//if (HideJumpingStop)
if (Bid >= OrderOpenPrice() + (TrailingStopPips*Point))
{
if (OrderStopLoss() == 0) sl = OrderOpenPrice();
if (Bid > sl + (TrailingStopPips*Point))
{
sl= Bid - (TrailingStopPips*Point);
if (StopTrailAtPipsProfit && sl>= OrderOpenPrice() + (StopTrailPips*Point)) return (0);
while(IsTradeContextBusy()) Sleep(100);
result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
if (result)
{
Print("Trailing stop updated: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
}//if (result)
else
{
int err=GetLastError();
Print(OrderSymbol(), " order modify failed with error(",err,"): ",ErrorDescription(err));
}//else
}//if (Bid > sl + (TrailingStopPips*Point))
}//if (Bid >= OrderOpenPrice() + (TrailingStopPips*Point))
}//if (OrderType()==OP_BUY)
if (OrderType()==OP_SELL)
{
if (Ask <= OrderOpenPrice() - (TrailingStopPips*Point))
{
if (HideTrailingStop)
{
TradeClosed = CheckForHiddenStopLossHit(OP_SELL, PipsAwayFromVisualTS, OrderStopLoss() );
if (TradeClosed) return (0);//Trade has closed, so nothing else to do
}//if (HideJumpingStop)
if (OrderStopLoss() == 0) sl = OrderOpenPrice();
if (Ask < sl - (TrailingStopPips*Point))
{
sl= Ask + (TrailingStopPips*Point);
if (StopTrailAtPipsProfit && sl<= OrderOpenPrice() - (StopTrailPips*Point)) return (0);
while(IsTradeContextBusy()) Sleep(100);
result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
if (result)
{
Print("Trailing stop updated: ", OrderSymbol(), ": SL ", sl, ": Bid ", Bid);
}//if (result)
else
{
err=GetLastError();
Print(OrderSymbol(), " order modify failed with error(",err,"): ",ErrorDescription(err));
}//else
}//if (Ask < sl - (TrailingStopPips*Point))
}//if (Ask <= OrderOpenPrice() - (TrailingStopPips*Point))
}//if (OrderType()==OP_SELL)
} // End of TrailingStopLoss sub
void BreakEvenAtGold()
{
bool result = true;
double stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL) * Point;
while(IsTradeContextBusy()) Sleep(100);
RefreshRates();
if (OrderType() == OP_BUY)
{
if (Ask >= BottomGoldLine && OrderStopLoss() == 0 && Ask - (OrderOpenPrice() + (GoldLineBEP * Point)) >= stoplevel)
{
result = OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice() + (GoldLineBEP * Point), Digits),
OrderTakeProfit(), OrderExpiration(), CLR_NONE);
}//if (Ask >= BottomGoldLine && OrderStopLoss() == 0)
}//if (OrderType() == OP_BUY)
if (OrderType() == OP_SELL)
{
if (Bid <= TopGoldLine && OrderStopLoss() == 0 && OrderOpenPrice() - (GoldLineBEP * Point) - Bid >= stoplevel)
{
result = OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(OrderOpenPrice() - (GoldLineBEP * Point), Digits),
OrderTakeProfit(), OrderExpiration(), CLR_NONE);
}//if (Bid <= TopGoldLine && OrderStopLoss() == 0)
}//if (OrderType() == OP_SELL)
if (!result)
{
int err=GetLastError();
if (ShowManagementAlerts==true) Alert("TOB setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("AEB setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//void BreakEvenAtGold()
void CloseAtGold()
{
bool result = true;
if (OrderType() == OP_BUY)
{
if (Ask >= BottomGoldLine && OrderStopLoss() == 0)
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 10000, CLR_NONE);
}//if (Ask >= BottomGoldLine && OrderStopLoss() == 0)
}//if (OrderType() == OP_BUY)
if (OrderType() == OP_SELL)
{
if (Bid <= TopGoldLine && OrderStopLoss() == 0)
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 10000, CLR_NONE);
}//if (Bid <= TopGoldLine && OrderStopLoss() == 0)
}//if (OrderType() == OP_SELL)
if (!result)
{
int err=GetLastError();
Alert("TOB order close at Gold ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("TOB order close at Gold ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//void CloseAtGold()
void CloseAtGreen()
{
bool result = true;
if (OrderType() == OP_BUY)
{
if (Ask >= BottomGreenLine )
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 10000, CLR_NONE);
}//if (Ask >= BottomGreenLine && OrderStopLoss() == 0)
}//if (OrderType() == OP_BUY)
if (OrderType() == OP_SELL)
{
if (Bid <= TopGreenLine)
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 10000, CLR_NONE);
}//if (Bid <= TopGreenLine && OrderStopLoss() == 0)
}//if (OrderType() == OP_SELL)
if (!result)
{
int err=GetLastError();
Alert("TOB order close at Green ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
Print("TOB order close at Green ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
}//if !result && ShowManagementAlerts)
}//void CloseAtGreen()
void CloseAtMiddle()
{
bool result = true;
if (OrderType() == OP_BUY)
{
if (Ask >= MiddleWhiteLine)
{
while(IsTradeContextBusy()) Sleep(100);
result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 10000, CLR_NONE);
}//if (Ask >= MiddleWhiteLine && OrderStopLoss() == 0)
}//if (OrderType() == Показано первые 50% кода (символов: 98829)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.