BlessingLite 3
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «blessinglite-gamma.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
BlessingLite 3 v3.9.6.34 gamma — торговый советник для MetaTrader 4, работающий с корзиной валютных пар по сеточной стратегии. Советник использует набор технических индикаторов для формирования сигналов на вход в сделки и управляет множеством одновременных позиций с configurable levels. Поддерживается как автоматический расчёт сетки и уровней take-profit, так и ручная настройка параметров лотирования.
Настройки программы
| Настройка | Описание |
|---|---|
| Version_3_9_6_34_gamma | Версия — Заголовок раздела настроек советника |
| TradeComment | Комментарий сделки — Текст комментария, добавляемого к открываемым ордерам |
| Notes | Заметки — Поле для пользовательских заметок |
| EA Magic Number (EANumber) | Магический номер EA — Уникальный идентификатор ордеров советника |
| Use the default 28 pairs (UseDefaultPairs) | Использовать пары по умолчанию — Включает торговлю со стандартным набором из 28 пар |
| Comma separated own pair list (OwnPairs) | Собственные пары — Список валютных пар через запятую для ручного выбора |
| Debug | Режим отладки — Включает вывод дополнительной диагностической информации в журнал |
| CLOSE ALL NOW *** (EmergencyCloseAll) | Аварийное закрытие всех — Принудительное закрытие всех открытых позиций и отложенных ордеров |
| . (s1) | Разделитель — Текстовый разделитель в интерфейсе настроек |
| NO NEW TRADES *** (ShutDown) | Остановка торговли — Запрещает открытие новых сделок при включении |
| . (s2) | Разделитель — Текстовый разделитель в интерфейсе настроек |
| == ACCOUNT SETTINGS == (LabelAcc) | Настройки аккаунта — Метка раздела настроек аккаунта |
| Percentage of balance lost before trading stops (StopTradePercent) | Процент остановки торговли — Процент потери баланса, при котором советник прекращает торговлю |
| Percentage of account you want to trade (on this pair) -->divided by Numer of Pairs? (PortionPC) | Доля аккаунта для торговли — Процент баланса, выделяемый на торговлю по каждой паре |
| Permitted Portion change with open basket (PortionChange) | Изменение доли — Разрешённое изменение доли при открытой корзине сделок |
| Percent of portion for max drawdown level. (MaxDDPercent) | Максимальная просадка — Процент порога максимальной допустимой просадки |
| Maximum allowed spread while placing trades (MaxSpread) | Максимальный спред — Допустимый максимальный спред для размещения сделок |
| Enable holiday shut-downs (UseHolidayShutdown) | Праздничная пауза — Включает автоматическую остановку торговли в праздничные даты |
| Comma-separated holiday list (format: [day]/[mth]-[day]/[mth]) (Holidays) | Праздничные даты — Список праздников в формате день/месяц-день/месяц через запятую |
| Audible alerts (PlaySounds) | Звуковые оповещения — Включает воспроизведение звуковых сигналов при событиях |
| Alert sound (AlertSound) | Звук оповещения — Имя файла звука для оповещений |
| Opt. with 'Open prices only' -- (eopb) | Фильтр тиков — Опциональный параметр для фильтрации тиков |
| EnableOncePerBar | Одно действие на бар — Ограничивает открытие ордеров одним раз в бар |
| UseMinMarginPercent | Проверка минимального маржа — Включает контроль минимального уровня маржа перед открытием сделки |
| MinMarginPercent | Минимальный уровень маржа — Процентный порог маржа для разрешения новой сделки |
| . (eopb1) | Разделитель — Текстовый разделитель в интерфейсе настроек |
| Stop/Limits for entry if true, Buys/Sells if false (B3Traditional) | Традиционный режим — При true используется стоп-лимит для входа, при false — маркет-ордера на покупку/продажу |
| true = ANY entry can be used to open orders, false = ALL entries used to open orders (UseAnyEntry) | Любой сигнал на вход — true — любая индикаторная проверка разрешает вход, false — требуются все проверки |
| LOT SIZE ----------- (LabelLS) | Размер лота — Метка раздела настроек размера лота |
| UseMM (Money Management) (UseMM) | Управление капиталом — Включает автоматический расчёт размера лота в зависимости от баланса |
| Adjusts MM base lot for large accounts (LAF) | Коэффициент лота — Корректировка базового лота для крупных аккаунтов |
| Starting lots if Money Management is off (Lot) | Начальный лот — Начальный размер лота при отключённом управлении капиталом |
| Multiplier on each level (Multiplier) | Множитель уровня — Множитель размера лота на каждом уровне сетки |
| GRID SETTINGS ------ (LabelGS) | Настройки сетки — Метка раздела настроек сетки |
| Auto calculation of TakeProfit and Grid size; (AutoCal) | Автоматический расчёт — Включает автоматический расчёт take-profit и размера сетки на основе ATR |
| TimeFrame for ATR calculation (ATRTF) | Таймфрейм ATR — Таймфрейм для расчёта индикатора ATR |
| Number of periods for the ATR calculation (ATRPeriods) | Период ATR — Количество периодов для расчёта ATR |
| Widens/Squishes Grid in increments/decrements of .1 (GAF) | Коэффициент сетки — Множитель для расширения или сжатия шага сетки |
| Time Grid in seconds, avoid opening lots of levels in fast market (EntryDelay) | Задержка входа — Задержка в секундах между размещением ордеров на разных уровнях |
| In pips, used in conjunction with logic to offset first trade entry (EntryOffset) | Смещение входа — Смещение первого ордера в пипсах от текущей цены |
| True = use RSI/MA calculation for next grid order (UseSmartGrid) | Умная сетка — Использует расчёт RSI/MA для определения следующего ордера сетки |
| ===== TRADING ===== (LabelTS) | Торговля — Метка раздела торговых настроек |
| Maximum number of trades to place (stops placing orders when reaches MaxTrades) (MaxTrades) | Максимум сделок — Максимальное количество сделок, после которого прекращается размещение ордеров |
| Close All level, when reaches this level, doesn't wait for TP to be hit (BreakEvenTrade) | Уровень безубыточности — Количество сделок, при достижении которого активируется переход в безубыточность |
| Pips added to Break Even Point before BE closure (BEPlusPips) | Смещение безубыточности — Количество пипсов, добавляемых к уровню безубыточности перед закрытием |
| True = will close the oldest open trade after CloseTradesLevel is reached (UseCloseOldest) | Закрытие старых сделок — При включении закрывает самую старую сделку при достижении уровня |
| will start closing oldest open trade at this level (CloseTradesLevel) | Уровень закрытия — Количество сделок, при котором начинается закрытие старых позиций |
| Will close the oldest trade whether it has potential profit or not (ForceCloseOldest) | Принудительное закрытие — Закрывает самую старую сделку независимо от наличия прибыли |
| Maximum number of oldest trades to close (MaxCloseTrades) | Максимум закрытий — Максимальное количество закрываемых старых сделок за раз |
| After Oldest Trades have closed, Forces Take Profit to BE +/- xx Pips (CloseTPPips) | ТП после закрытия — Фиксирует take-profit на уровне безубыточности плюс указанное количество пипсов |
| Force Take Profit to BE +/- xx Pips (ForceTPPips) | Принудительный ТП — Принудительно устанавливает take-profit на уровне безубыточности плюс указанные пипсы |
| Ensure Take Profit is at least BE +/- xx Pips (MinTPPips) | Минимальный ТП — Гарантирует минимальное расстояние take-profit от уровня безубыточности |
| EXITS ----------- (LabelES) | Выход — Метка раздела настроек выхода из сделок |
| Turns on TP move and Profit Trailing Stop Feature (MaximizeProfit) | Максимизация прибыли — Включает перемещение take-profit и трейлинг-стоп |
| Profit trailing stop: Lock in profit at set percent of Total Profit Potential (ProfitSet) | Фиксация прибыли — Процент от потенциальной прибыли для фиксации и установки трейлинг-стопа |
| Moves TP this amount in pips (MoveTP) | Перемещение ТП — Размер перемещения take-profit в пипсах |
| Number of times you want TP to move before stopping movement (TotalMoves) | Количество перемещений — Максимальное число перемещений take-profit перед остановкой |
| Use Stop Loss and/or Trailing Stop Loss (UseStopLoss) | Стоп-лосс — Включает использование стоп-лосса и/или трейлинг-стопа |
| Pips for fixed StopLoss from BE, 0=off (SLPips) | Стоп-лосс в пипсах — Фиксированный стоп-лосс в пипсах от безубыточности, 0 отключает |
| Pips for trailing stop loss from BE + TSLPips: +ve = fixed trail; -ve = reducing trail; 0=off (TSLPips) | Трейлинг стоп — Расстояние трейлинг-стопа в пипсах от безубыточности |
| Minimum trailing stop pips if using reducing TS (TSLPipsMin) | Минимальный трейлинг — Минимальное расстояние трейлинг-стопа при использовании уменьшающегося режима |
| Transmits a SL in case of internet loss (UsePowerOutSL) | Стоп при отключении — Устанавливает стоп-лосс при потере интернет-соединения |
| Power Out Stop Loss in pips (POSLPips) | Стоп при отключении пипсы — Размер стоп-лосса в пипсах для режима защиты при потере связи |
| Close trades in FIFO order (UseFIFO) | FIFO закрытие — Закрывает сделки в порядке их открытия |
| EARLY EXITS --------- (LabelEE) | Ранний выход — Метка раздела настроек раннего выхода |
| Reduces ProfitTarget by a percentage over time and number of levels open (UseEarlyExit) | Ранний выход — Включает уменьшение целевой прибыли со временем и по количеству уровней |
| Number of Hours to wait before EE over time starts (EEStartHours) | Часы начала выхода — Количество часов ожидания перед началом снижения цели по времени |
| true = StartHours from FIRST trade: false = StartHours from LAST trade (EEFirstTrade) | Отсчёт от первой сделки — true — отсчёт часов начинается от первой сделки, false — от последней |
| Percentage reduction per hour (0 = OFF) (EEHoursPC) | Процент снижения в час — Процентное снижение целевой прибыли за каждый час |
| Number of Open Trades before EE over levels starts (EEStartLevel) | Уровень начала выхода — Количество открытых сделок, при котором начинается снижение по уровням |
| Percentage reduction at each level (0 = OFF) (EELevelPC) | Процент снижения на уровне — Процентное снижение целевой прибыли на каждом уровне |
| true = Will allow the basket to close at a loss : false = Minimum profit is Break Even (EEAllowLoss) | Разрешить убыток — true — позволяет закрыть корзину с убытком, false — минимальная прибыль равна безубыточности |
| . (LabelAdv) | Дополнительно — Метка раздела дополнительных настроек |
| GRID SIZE --------- (LabelGrid) | Размер сетки — Метка раздела настроек размера сетки |
| Specifies number of open trades in each block (separated by a comma) (SetCountArray) | Количество сделок в блоке — Через запятую указывает число открытых сделок в каждом блоке сетки |
| Specifies number of pips away to issue limit order (separated by a comma) (GridSetArray) | Расстояние сетки — Через запятую указывает расстояние в пипсах для лимитных ордеров каждого блока |
| Take profit for each block (separated by a comma) (TP_SetArray) | ТП по блокам — Через запятую указывает take-profit для каждого блока сетки |
| . (LabelEST0) | Разделитель — Текстовый разделитель в интерфейсе настроек |
| == ENTRY PARAMETERS == (LabelEST) | Параметры входа — Метка раздела параметров входа в сделку |
| MA ------------- (LabelMA) | Скользящая средняя — Метка раздела настроек MA |
| MA Entry (MAEntry) | Вход по MA — Включает, отключает или инвертирует использование скользящей средней для входа |
| Period of MA (H4 = 100, H1 = 400) (MAPeriod) | Период MA — Период расчёта скользящей средней |
| Distance from MA to be treated as Ranging Market (MADistance) | Дистанция MA — Расстояние от MA в пипсах, при котором рынок считается ранжирующим |
| CCI ------------- (LabelCCI) | CCI — Метка раздела настроек CCI |
| CCI Entry (CCIEntry) | Вход по CCI — Включает, отключает или инвертирует использование CCI для входа |
| Period for CCI calculation (CCIPeriod) | Период CCI — Период расчёта индикатора CCI |
| BOLLINGER BANDS ----- (LabelBBS) | Боллинджер Бандс — Метка раздела настроек Боллинджер Бандс |
| Bollinger Entry (BollingerEntry) | Вход по BB — Включает, отключает или инвертирует использование Боллинджер Бандс для входа |
| Period for Bollinger (BollPeriod) | Период Боллинджера — Период расчёта Боллинджер Бандс |
| Up/Down spread (BollDistance) | Дистанция BB — Дополнительное расстояние в пипсах от канала Боллинджера |
| Standard deviation multiplier for channel (BollDeviation) | Отклонение BB — Множитель стандартного отклонения для канала Боллинджера |
| STOCHASTIC -------- (LabelSto) | Стохастик — Метка раздела настроек Стохастик |
| Stochastic Entry (StochEntry) | Вход по Стохастику — Включает, отключает или инвертирует использование Стохастика для входа |
| Determines Overbought and Oversold Zones (BuySellStochZone) | Зоны Стохастика — Определяет зоны перекупленности и перепроданности |
| Stochastic KPeriod (KPeriod) | Период K — Период %K линии Стохастика |
| Stochastic DPeriod (DPeriod) | Период D — Период %D линии Стохастика |
| Stochastic Slowing (Slowing) | Замедление — Параметр замедления Стохастика |
| MACD ------------ (LabelMACD) | MACD — Метка раздела настроек MACD |
| MACD Entry (MACDEntry) | Вход по MACD — Включает, отключает или инвертирует использование MACD для входа |
| Time frame for MACD calculation (MACD_TF) | Таймфрейм MACD — Таймфрейм для расчёта индикатора MACD |
Поиск по коду файла
#property version "396.34"
#property strict
#include <stdlib.mqh>
#include <stderror.mqh>
#include <WinUser32.mqh>
#include <ChartObjects\ChartObjectsTxtControls.mqh>
#define A 1 //All (Basket of all pairs)
#define B 2 //Basket
#define T 4 //Ticket
#define P 5 //Pending
enum portChgs
{
no_change = 0, // No changes
increase = 1, // Increase only
any = -1, // Increase / decrease
};
enum entType
{
disable = 0, // Disabled
enable = 1, // Enabled
reverse = 2 // Reverse
};
enum tFrame
{
current = 0, // Current
m1 = 1, // M1
m5 = 2, // M5
m15 = 3, // M15
m30 = 4, // M30
h1 = 5, // H1
h4 = 6, // H4
d1 = 7, // Daily
w1 = 8, // Weekly
mn1 = 9 // Monthly
};
input string Version_3_9_6_34_gamma = "EA Settings:";
input string TradeComment = "BlessingLite 3.9.6.34 gamma";
input string Notes = "";
input int EANumber = 1681348112; // EA Magic Number
input bool UseDefaultPairs = true; // Use the default 28 pairs
input string OwnPairs = ""; // Comma separated own pair list
input bool Debug = false;
input bool EmergencyCloseAll = false; // *** CLOSE ALL NOW ***
input string s1 = ""; //.
input bool ShutDown = false; // *** NO NEW TRADES ***
input string s2 = ""; //.
input string LabelAcc = ""; // == ACCOUNT SETTINGS ==
input double StopTradePercent = 10; // Percentage of balance lost before trading stops
input bool NanoAccount = false; // Small Lot Account (0.01)
input double PortionPC = 100; // Percentage of account you want to trade (on this pair) -->divided by Numer of Pairs?
input portChgs PortionChange = increase; // Permitted Portion change with open basket
input double MaxDDPercent = 90; // Percent of portion for max drawdown level.
input double MaxSpread = 10; // Maximum allowed spread while placing trades
input bool UseHolidayShutdown = false; // Enable holiday shut-downs
input string Holidays = "18/12-01/01"; // Comma-separated holiday list (format: [day]/[mth]-[day]/[mth])
input bool PlaySounds = false; // Audible alerts
input string AlertSound = "Alert.wav"; // Alert sound
input string eopb = ""; // -- Opt. with 'Open prices only' --
input bool EnableOncePerBar = true;
input bool UseMinMarginPercent = false;
input double MinMarginPercent = 1500;
input string eopb1 = ""; //.
input bool B3Traditional = true; // Stop/Limits for entry if true, Buys/Sells if false
input bool UseAnyEntry = false; // true = ANY entry can be used to open orders, false = ALL entries used to open orders
input string LabelLS = ""; // ----------- LOT SIZE -----------
input bool UseMM = false; // UseMM (Money Management)
input double LAF = 0.5; // Adjusts MM base lot for large accounts
input double Lot = 0.01; // Starting lots if Money Management is off
input double Multiplier = 3.0; // Multiplier on each level
input string LabelGS = ""; // ------ GRID SETTINGS ------
input bool AutoCal = false; // Auto calculation of TakeProfit and Grid size;
input tFrame ATRTF = 0; // TimeFrame for ATR calculation
input int ATRPeriods = 5; // Number of periods for the ATR calculation
input double GAF = 1.1; // Widens/Squishes Grid in increments/decrements of .1
input int EntryDelay = 1200; // Time Grid in seconds, avoid opening lots of levels in fast market
input double EntryOffset = 0; // In pips, used in conjunction with logic to offset first trade entry
input bool UseSmartGrid = false; // True = use RSI/MA calculation for next grid order
input string LabelTS = ""; // ===== TRADING =====
input int MaxTrades = 15; // Maximum number of trades to place (stops placing orders when reaches MaxTrades)
input int BreakEvenTrade = 5; // Close All level, when reaches this level, doesn't wait for TP to be hit
input double BEPlusPips = -5; // Pips added to Break Even Point before BE closure
input bool UseCloseOldest = false; // True = will close the oldest open trade after CloseTradesLevel is reached
input int CloseTradesLevel = 5; // will start closing oldest open trade at this level
input bool ForceCloseOldest = true; // Will close the oldest trade whether it has potential profit or not
input int MaxCloseTrades = 4; // Maximum number of oldest trades to close
input double CloseTPPips = 10; // After Oldest Trades have closed, Forces Take Profit to BE +/- xx Pips
input double ForceTPPips = 0; // Force Take Profit to BE +/- xx Pips
input double MinTPPips = 0; // Ensure Take Profit is at least BE +/- xx Pips
input string LabelES = ""; // ----------- EXITS -----------
input bool MaximizeProfit = true; // Turns on TP move and Profit Trailing Stop Feature
input double ProfitSet = 50; // Profit trailing stop: Lock in profit at set percent of Total Profit Potential
input double MoveTP = 2; // Moves TP this amount in pips
input int TotalMoves = 2; // Number of times you want TP to move before stopping movement
input bool UseStopLoss = false; // Use Stop Loss and/or Trailing Stop Loss
input double SLPips = 30; // Pips for fixed StopLoss from BE, 0=off
input double TSLPips = 10; // Pips for trailing stop loss from BE + TSLPips: +ve = fixed trail; -ve = reducing trail; 0=off
input double TSLPipsMin = 3; // Minimum trailing stop pips if using reducing TS
input bool UsePowerOutSL = false; // Transmits a SL in case of internet loss
input double POSLPips = 600; // Power Out Stop Loss in pips
input bool UseFIFO = false; // Close trades in FIFO order
input string LabelEE = ""; // --------- EARLY EXITS ---------
input bool UseEarlyExit = false; // Reduces ProfitTarget by a percentage over time and number of levels open
input double EEStartHours = 3; // Number of Hours to wait before EE over time starts
input bool EEFirstTrade = true; // true = StartHours from FIRST trade: false = StartHours from LAST trade
input double EEHoursPC = 0.5; // Percentage reduction per hour (0 = OFF)
input int EEStartLevel = 5; // Number of Open Trades before EE over levels starts
input double EELevelPC = 10; // Percentage reduction at each level (0 = OFF)
input bool EEAllowLoss = false; // true = Will allow the basket to close at a loss : false = Minimum profit is Break Even
input string LabelAdv = ""; //.
input string LabelGrid = ""; // --------- GRID SIZE ---------
input string SetCountArray = "3,2,2,2"; // Specifies number of open trades in each block (separated by a comma)
input string GridSetArray = "55,100,115,160"; // Specifies number of pips away to issue limit order (separated by a comma)
input string TP_SetArray = "10,15,15,15"; // Take profit for each block (separated by a comma)
input string LabelEST0 = ""; // .
input string LabelEST = ""; // == ENTRY PARAMETERS ==
input string LabelMA = ""; // ------------- MA -------------
input entType MAEntry = 0; // MA Entry
input int MAPeriod = 100; // Period of MA (H4 = 100, H1 = 400)
input double MADistance = 10; // Distance from MA to be treated as Ranging Market
input string LabelCCI = ""; // ------------- CCI -------------
input entType CCIEntry = 0; // CCI Entry
input int CCIPeriod = 14; // Period for CCI calculation
input string LabelBBS = ""; // ----- BOLLINGER BANDS -----
input entType BollingerEntry = 1; // Bollinger Entry
input int BollPeriod = 20; // Period for Bollinger
input double BollDistance = -1; // Up/Down spread
input double BollDeviation = 3.0; // Standard deviation multiplier for channel
input string LabelSto = ""; // --------- STOCHASTIC --------
input entType StochEntry = 0; // Stochastic Entry
input int BuySellStochZone = 20; // Determines Overbought and Oversold Zones
input int KPeriod = 10; // Stochastic KPeriod
input int DPeriod = 2; // Stochastic DPeriod
input int Slowing = 2; // Stochastic Slowing
input string LabelMACD = ""; // ------------ MACD ------------
input entType MACDEntry = 0; // MACD Entry
input tFrame MACD_TF = 0; // Time frame for MACD calculation
input int FastPeriod = 12; // MACD EMA Fast Period
input int SlowPeriod = 26; // MACD EMA Slow Period
input int SignalPeriod = 9; // MACD EMA Signal Period
input ENUM_APPLIED_PRICE MACDPrice = PRICE_CLOSE; // MACD Applied Price
input string LabelSG = ""; // --------- SMART GRID ---------
input tFrame RSI_TF = 3; // Timeframe for RSI calculation (should be lower than chart TF)
input int RSI_Period = 14; // Period for RSI calculation
input ENUM_APPLIED_PRICE RSI_Price = PRICE_CLOSE; // RSI Applied Price
input int RSI_MA_Period = 10; // Period for MA of RSI calculation
input ENUM_MA_METHOD RSI_MA_Method = MODE_SMA; // RSI MA Method
input string LabelOS0 = ""; //.
input string LabelOS = ""; // ------------ OTHER -----------
input bool RecoupClosedLoss = true; // true = Recoup any CloseOldest losses: false = Use original profit target.
input int Level = 7; // Largest Assumed Basket size. Lower number = higher start lots
int slip = 99;
input bool SaveStats = false; // true = will save equity statistics
input int StatsPeriod = 3600; // seconds between stats entries - off by default
input bool StatsInitialise = true; // true for backtest - false for forward/live to ACCUMULATE equity traces
input string LabelUE = ""; // ------------ EMAIL ------------
input bool UseEmail = false;
input string LabelEDD = "At what DD% would you like Email warnings (Max: 49, Disable: 0)?"; //.
input double EmailDD1 = **;
input double EmailDD2 = **;
input double EmailDD3 = **;
input string LabelEH = "Hours before DD timer resets"; //.
input double EmailHours = **; // Minimum number of hours between emails
string LabelDisplay = ""; // ------------ DISPLAY -----------
bool displayOverlay = true; // Enable display
bool displayLogo = true; // Display copyright and icon
string displayFont = "Courier Bold"; //Display font
int displayFontSize = 9; // Changes size of display characters
int displaySpacing = 14; // Changes space between lines
color displayColorProfit = Green; // default color of profit display characters
color displayColorLoss = Red; // default color of loss display characters
color displayColorFGnd = White; // default color of ForeGround Text display characters
string DefaultPairs[] = {"AUDCAD","AUDCHF","AUDJPY","AUDNZD","AUDUSD","CADCHF","CADJPY","CHFJPY","EURAUD","EURCAD","EURCHF","EURGBP","EURJPY","EURNZD","EURUSD","GBPAUD","GBPCAD","GBPCHF","GBPJPY","GBPNZD","GBPUSD","NZDCAD","NZDCHF","NZDJPY","NZDUSD","USDCAD","USDCHF","USDJPY"};
string TradePairs[];
int Magic;
int AccountType;
double StopTradeBalance;
bool Testing, Visual;
bool AllowTrading;
bool EmergencyWarning;
int Error;
int ca; //close all type
int Set1Level, Set2Level, Set3Level, Set4Level;
int EmailCount;
string sTF;
datetime EmailSent;
int GridArray[, 2];
string CS, UAE;
int HolShutDown;
int HolArray[, 4];
datetime HolFirst, HolLast, NextStats;
int Digit[, 2], TF[10] = { 0, 1, 5, 15, 30, 60, 240, 1440, 10080, 43200 };
double InitialAB; // Initial Account Balance --> global variable?
double Email[3];
double StatLowEquity, StatHighEquity;
datetime EETime;
int EECount, FileHandle;
bool FileClosed, FirstRun, dLabels;
string FileName, ID, StatFile;
bool checkResult;
string suffix="";
string prefix="";
struct pairinf
{
int CbB; // Count buy
int CbS; // Count sell
int CpBL; // Count buy limit
int CpSL; // Count sell limit
int CpBS; // Count buy stop
int CpSS; // Count sell stop
double LbB; // Count buy lots
double LbS; // Count sell lots
double OPpBL; // Buy limit open price
double OPpSL; // Sell limit open price
double SLbB; // stop losses are set to zero if POSL off
double SLbS; // stop losses are set to zero if POSL off
double BCb, BCa; // Broker costs (swap + commission)
double ProfitPot; // The Potential Profit of a basket of Trades
double PipValue, PipVal2, ASK, BID;
double OrderLot;
double OPbL; // last open price
datetime OTbL; // last open time
datetime OTbO;
double g2, tp2, Entry, RSI_MA, OPbO;
int Ticket, IndEntry, TbO;
double Pb, PaC, PbPips, PbTarget, DrawDownPC, BEb, BEa;
bool TradesOpen, BuyMe, SellMe, Success, SetPOSL;
string IndicatorUsed;
double EEpc, OPbN, nLots;
double bSL, TPa, TPbMP;
int Trend;
string ATrend;
double cci_01, cci_02, cci_03, cci_04;
double cci_11, cci_12, cci_13, cci_14;
double StopLevel;
datetime OTbF;
int CaL, CbC, TbF;
double bTS, TPb, LbF, PbC, ClosedPips;
int CbT, CpT; // Count basket Total,Count pending Total
double PbMax, PbMin, PortionBalance, MaxDD, MaxDDPer;
int LotDecimal, MinMult, LotMult;
double Lots[];
double RSI[];
double TargetPips;
double SLbL; // Stop Loss basket Last
double SLb; // Stop Loss
int Moves;
bool PendLot;
datetime OncePerBarTime;
double Pip;
double MoveTP_;
double EntryOffset_;
double MADistance_;
double BollDistance_;
double POSLPips_;
double CloseTPPips_;
double ForceTPPips_;
double MinTPPips_;
double BEPlusPips_;
double SLPips_;
double TSLPips_;
double TSLPipsMin_;
double Lot_;
double MinLotSize, LotStep;
double GridTP;
double BCaL, BEbL;
};
pairinf pairinfo[];
int EANumber_;
double StopTradePercent_;
double ProfitSet_;
double EEHoursPC_;
double EELevelPC_;
double PortionPC_;
bool Debug_; //okay
entType MAEntry_;
entType CCIEntry_;
entType BollingerEntry_;
entType StochEntry_;
entType MACDEntry_;
int MaxCloseTrades_;
double Multiplier_;
string SetCountArray_;
string GridSetArray_;
string TP_SetArray_;
bool EmergencyCloseAll_;
bool ShutDown_;
double LbT = 0; // total lots out
double previous_stop_trade_amount;
double stop_trade_amount;
int OnInit()
{
// код доступен только после оплаты
}
void OnDeinit(const int reason)
{
switch(reason)
{
case REASON_REMOVE:
case REASON_CHARTCLOSE:
case REASON_CHARTCHANGE:
for (int Index=0;Index<ArraySize(TradePairs);Index++){
if(pairinfo[Index].CpT > 0)
{
while(pairinfo[Index].CpT > 0)
pairinfo[Index].CpT -= ExitTrades(P, displayColorLoss, "Blessing Removed",0,ca,TradePairs[Index]+suffix);
}
}
GlobalVariablesDeleteAll(ID);
case REASON_RECOMPILE:
case REASON_PARAMETERS:
case REASON_ACCOUNT:;
Comment("Reason:"+IntegerToString(reason));
}
return;
}
void OnTick()
{
// код доступен только после оплаты
}
int DoStart()
{ if (Debug_) printf("!!!!!!!!!!!!!!!!!!!start!!!!!!!!!!!!");
if(UseHolidayShutdown)
{
if(HolShutDown > 0 && TimeCurrent() >= HolLast && HolLast > 0)
{
Print("Trading has resumed after the ", TimeToStr(HolFirst, TIME_DATE), " - ", TimeToStr(HolLast, TIME_DATE), " holidays.");
HolShutDown = 0;
if(PlaySounds)
PlaySound(AlertSound);
}
if(HolShutDown == 3)
{
return (0);
}
else
if((HolShutDown == 0 && TimeCurrent() >= HolLast) || HolFirst == 0)
{
for(int Index = 0; Index < ArraySize(HolArray); Index++)
{
string tts = (string) Year() + "." + (string) HolArray[Index, 0] + "." + (string) HolArray[Index, 1];
Print("tts: " + tts + " *******************************************************");
HolFirst = StrToTime(tts);
HolLast = StrToTime((string) Year() + "." + (string) HolArray[Index, 2] + "." + (string) HolArray[Index, 3] + " 23:59:59");
if(TimeCurrent() < HolFirst)
{
if(HolFirst > HolLast)
HolLast = StrToTime(DTS(Year() + 1, 0) + "." + (string) HolArray[Index, 2] + "." + (string) HolArray[Index, 3] + " 23:59:59");
break;
}
if(TimeCurrent() < HolLast)
{
if(HolFirst > HolLast)
HolFirst = StrToTime(DTS(Year() - 1, 0) + "." + (string) HolArray[Index, 0] + "." + (string) HolArray[Index, 1]);
break;
}
if(TimeCurrent() > HolFirst && HolFirst > HolLast)
{
HolLast = StrToTime(DTS(Year() + 1, 0) + "." + (string) HolArray[Index, 2] + "." + (string) HolArray[Index, 3] + " 23:59:59");
if(TimeCurrent() < HolLast)
break;
}
}
if(TimeCurrent() >= HolFirst && TimeCurrent() <= HolLast)
{
HolShutDown = 1;
}
}
else
if(HolShutDown == 0 && TimeCurrent() >= HolFirst && TimeCurrent() < HolLast)
HolShutDown = 1;
}
for(int i=0;i<ArraySize(TradePairs);i++){
if (Debug_) printf("TradePair:"+IntegerToString(i)+TradePairs[i]+suffix);
if (Debug_) Print("MinLotSize: ", DTS(pairinfo[i].MinLotSize, 2), " LotStep: ", DTS(pairinfo[i].LotStep, 2), " MinLot: ", DTS(MathMin(pairinfo[i].MinLotSize, pairinfo[i].LotStep), 2), " StartLot: ", DTS(pairinfo[i].Lot_, 2), " LotMult: ", DTS(pairinfo[i].LotMult, 0), " Lot Decimal: ", DTS(pairinfo[i].LotDecimal, 0));
pairinfo[i].CbB =0; // Count buy
pairinfo[i].CbS =0; // Count sell
pairinfo[i].CpBL =0; // Count buy limit
pairinfo[i].CpSL =0; // Count sell limit
pairinfo[i].CpBS =0; // Count buy stop
pairinfo[i].CpSS =0; // Count sell stop
pairinfo[i].LbB =0; // Count buy lots
pairinfo[i].LbS =0; // Count sell lots
pairinfo[i].OPpBL =0; // Buy limit open price
pairinfo[i].OPpSL =0; // Sell limit open price
pairinfo[i].SLbB =0; // stop losses are set to zero if POSL off
pairinfo[i].SLbS =0; // stop losses are set to zero if POSL off
pairinfo[i].ProfitPot =0; // The Potential Profit of a basket of Trades
pairinfo[i].BCb =0;
pairinfo[i].BCa =0; // Broker costs (swap + commission)
pairinfo[i].OPbL = 0;
pairinfo[i].OTbL = 0; // last open time
pairinfo[i].OTbO = 0;
pairinfo[i].RSI_MA = 0;
pairinfo[i].OPbO = 0;
pairinfo[i].Ticket = 0;
pairinfo[i].IndEntry = 0;
pairinfo[i].TbO = 0;
pairinfo[i].Pb = 0;
pairinfo[i].PaC = 0;
pairinfo[i].PbPips = 0;
pairinfo[i].PbTarget = 0;
pairinfo[i].DrawDownPC = 0;
pairinfo[i].BEb = 0;
pairinfo[i].BEa = 0;
pairinfo[i].BuyMe = false;
pairinfo[i].SellMe = false;
pairinfo[i].EEpc = 0;
pairinfo[i].OPbN = 0;
pairinfo[i].nLots = 0;
pairinfo[i].bSL = 0;
pairinfo[i].TPa = 0;
pairinfo[i].TPbMP = 0;
pairinfo[i].Trend = 0;
pairinfo[i].cci_01 = 0;
pairinfo[i].cci_02 = 0;
pairinfo[i].cci_03 = 0;
pairinfo[i].cci_04 = 0;
pairinfo[i].cci_11 = 0;
pairinfo[i].cci_12 = 0;
pairinfo[i].cci_13 = 0;
pairinfo[i].cci_14 = 0;
if (MarketInfo(TradePairs[i]+suffix, MODE_TICKSIZE) !=0) pairinfo[i].PipVal2 = MarketInfo(TradePairs[i]+suffix, MODE_TICKVALUE) / MarketInfo(TradePairs[i]+suffix, MODE_TICKSIZE);
else printf("No MarketInfo for "+TradePairs[i]+suffix+DoubleToStr(MarketInfo(TradePairs[i]+suffix,MODE_TICKSIZE)));
pairinfo[i].PipValue = pairinfo[i].PipVal2 * pairinfo[i].Pip;
pairinfo[i].StopLevel = MarketInfo(TradePairs[i]+suffix, MODE_STOPLEVEL) * Point;
pairinfo[i].ASK = ND(MarketInfo(TradePairs[i]+suffix, MODE_ASK), (int) MarketInfo(TradePairs[i]+suffix, MODE_DIGITS));
pairinfo[i].BID = ND(MarketInfo(TradePairs[i]+suffix, MODE_BID), (int) MarketInfo(TradePairs[i]+suffix, MODE_DIGITS));
if(pairinfo[i].ASK == 0 || pairinfo[i].BID == 0)
return (0);
for(int Order = 0; Order < OrdersTotal(); Order++)
{
if(!OrderSelect(Order, SELECT_BY_POS, MODE_TRADES))
continue;
int Type = OrderType();
if(OrderMagicNumber() != Magic || OrderSymbol() != TradePairs[i]+suffix)
continue;
if(OrderTakeProfit() > 0)
ModifyOrder(OrderOpenPrice(), OrderStopLoss(),0,i);
if(Type <= OP_SELL)
{
pairinfo[i].Pb += OrderProfit();
pairinfo[i].BCb += OrderSwap() + OrderCommission();
pairinfo[i].BEb += OrderLots() * OrderOpenPrice();
if(OrderOpenTime() >= pairinfo[i].OTbL)
{
pairinfo[i].OTbL = OrderOpenTime();
pairinfo[i].OPbL = OrderOpenPrice();
}
if(OrderOpenTime() < pairinfo[i].OTbF || pairinfo[i].TbF == 0)
{
pairinfo[i].OTbF = OrderOpenTime();
pairinfo[i].TbF = OrderTicket();
pairinfo[i].LbF = OrderLots();
}
if(OrderOpenTime() < pairinfo[i].OTbO || pairinfo[i].OTbO == 0)
{
pairinfo[i].OTbO = OrderOpenTime();
pairinfo[i].TbO = OrderTicket();
pairinfo[i].OPbO = OrderOpenPrice();
}
if(UsePowerOutSL && ((pairinfo[i].POSLPips_ > 0 && OrderStopLoss() == 0) || (pairinfo[i].POSLPips_ == 0 && OrderStopLoss() > 0)))
pairinfo[i].SetPOSL = true;
if(Type == OP_BUY)
{
pairinfo[i].CbB++;
pairinfo[i].LbB += OrderLots();
continue;
}
else
{
pairinfo[i].CbS++;
pairinfo[i].LbS += OrderLots();
continue;
}
}
else
{
if(Type == OP_BUYLIMIT)
{
pairinfo[i].CpBL++;
pairinfo[i].OPpBL = OrderOpenPrice();
continue;
}
else
if(Type == OP_SELLLIMIT)
{
pairinfo[i].CpSL++;
pairinfo[i].OPpSL = OrderOpenPrice();
continue;
}
else
if(Type == OP_BUYSTOP)
pairinfo[i].CpBS++;
else
pairinfo[i].CpSS++;
}
}
pairinfo[i].CbT = pairinfo[i].CbB + pairinfo[i].CbS;
LbT = pairinfo[i].LbB + pairinfo[i].LbS;
pairinfo[i].Pb = ND(pairinfo[i].Pb + pairinfo[i].BCb, 2);
pairinfo[i].CpT = pairinfo[i].CpBL + pairinfo[i].CpSL + pairinfo[i].CpBS + pairinfo[i].CpSS;
pairinfo[i].BCa = pairinfo[i].BCb;
if(LbT > 0)
{
pairinfo[i].BEb = ND(pairinfo[i].BEb / LbT, Digits);
if(pairinfo[i].BCa < 0)
pairinfo[i].BEb -= ND(pairinfo[i].BCa / pairinfo[i].PipVal2 / (pairinfo[i].LbB - pairinfo[i].LbS), Digits);
if(pairinfo[i].Pb > pairinfo[i].PbMax || pairinfo[i].PbMax == 0)
pairinfo[i].PbMax = pairinfo[i].Pb;
if(pairinfo[i].Pb < pairinfo[i].PbMin || pairinfo[i].PbMin == 0)
pairinfo[i].PbMin = pairinfo[i].Pb;
if(!pairinfo[i].TradesOpen)
{
FileHandle = FileOpen(FileName, FILE_BIN | FILE_WRITE);
if(FileHandle > -1)
{
FileWriteInteger(FileHandle, pairinfo[i].TbF);
FileClose(FileHandle);
pairinfo[i].TradesOpen = true;
if(Debug_)
Print(FileName, " File Written: ", pairinfo[i].TbF);
}
}
}
else
if(pairinfo[i].TradesOpen)
{
pairinfo[i].TPb = 0;
pairinfo[i].PbMax = 0;
pairinfo[i].PbMin = 0;
pairinfo[i].OTbF = 0; //wirklich Index???? oder alle Index?
pairinfo[i].TbF = 0;
pairinfo[i].LbF = 0;
pairinfo[i].PbC = 0;
pairinfo[i].PaC = 0;
pairinfo[i].ClosedPips = 0;
pairinfo[i].CbC = 0;
pairinfo[i].CaL = 0;
pairinfo[i].bTS = 0;
EmailCount = *;
EmailSent = *;
FileHandle = FileOpen(FileName, FILE_BIN | FILE_READ);
if(FileHandle > -1)
{
FileClose(FileHandle);
Error = GetLastError();
FileDelete(FileName);
Error = GetLastError();
if(Error == ERR_NO_ERROR)
{
if(Debug_)
Print(FileName + " File Deleted");
pairinfo[i].TradesOpen = false;
}
else
Print("Error ", Error, " {", ErrorDescription(Error), ") deleting file ", FileName);
}
else
pairinfo[i].TradesOpen = false;
}
if(pairinfo[i].CbT == 0 && ShutDown_)
{
if(pairinfo[i].CpT > 0)
{
ExitTrades(P, displayColorLoss, "Blessing is shutting down",0,ca,"");
return (0);
}
if(AllowTrading)
{
Print("Blessing has shut down. Set ShutDown = 'false' to resume trading");
if(PlaySounds)
PlaySound(AlertSound);
AllowTrading = false;
}
if(UseEmail && EmailCount < 4 && !Testing)
{
SendMail("Blessing EA", "Blessing has shut down on " + TradePairs[i]+suffix + " " + sTF + ". To resume trading, change ShutDown to false.");
Error = GetLastError();
if(Error > 0)
Print("Error ", Error, " (", ErrorDescription(Error), ") sending email");
else
EmailCount = *;
}
}
double NewPortionBalance = ND(AccountBalance() * PortionPC_, 2);
if(pairinfo[i].CbT == 0 || PortionChange < 0 || (PortionChange > 0 && NewPortionBalance > pairinfo[i].PortionBalance))
pairinfo[i].PortionBalance = NewPortionBalance;
if(OncePerBar(pairinfo[i].OncePerBarTime)&& (pairinfo[i].PortionBalance !=0))
{
if(pairinfo[i].Pb < 0)
pairinfo[i].DrawDownPC = -(pairinfo[i].Pb) / pairinfo[i].PortionBalance; // opb
if(!FirstRun && pairinfo[i].DrawDownPC >= MaxDDPercent / 100)
{
ExitTrades(A, displayColorLoss, "Equity StopLoss Reached",0,ca,"");
if(PlaySounds)
PlaySound(AlertSound);
return (0);
}
if(-(pairinfo[i].Pb) > pairinfo[i].MaxDD)
pairinfo[i].MaxDD = -(pairinfo[i].Pb);
pairinfo[i].MaxDDPer = MathMax(pairinfo[i].MaxDDPer, pairinfo[i].DrawDownPC * 100);
if(SaveStats)
Stats(false, TimeCurrent() < NextStats, pairinfo[i].PortionBalance, pairinfo[i].Pb);
double StepAB = InitialAB * (1 + StopTradePercent_);
double StepSTB = AccountBalance() * (1 - StopTradePercent_);
double NextISTB = StepAB * (1 - StopTradePercent_);
if(StepSTB > NextISTB)
{
InitialAB = StepAB;
StopTradeBalance = StepSTB;
}
double InitialAccountMultiPortion = StopTradeBalance * PortionPC_;
stop_trade_amount = InitialAccountMultiPortion;
if(pairinfo[i].PortionBalance < InitialAccountMultiPortion)
{
if(pairinfo[i].CbT == 0)
{
AllowTrading = false;
if(PlaySounds)
PlaySound(AlertSound);
Print("Portion Balance dropped below stop-trading percentage");
MessageBox("Reset required - account balance dropped below stop-trading percentage on " + DTS(AccountNumber(), 0) + " " + TradePairs[i]+suffix + " " + (string) Period(), "Blessing 3: Warning", 48);
return (0);
}
else
if(!ShutDown_ && !RecoupClosedLoss)
{
ShutDown_ = true;
if(PlaySounds)
PlaySound(AlertSound);
Print("Portion Balance dropped below stop-trading percentage");
return (0);
}
}
double ima_0 = iMA(TradePairs[i]+suffix, 0, MAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
if(pairinfo[i].BID > ima_0 + pairinfo[i].MADistance_)
pairinfo[i].Trend = 0;
else
if(pairinfo[i].ASK < ima_0 - pairinfo[i].MADistance_)
pairinfo[i].Trend = 1;
else
pairinfo[i].Trend = 2;
double Pa = pairinfo[i].Pb;
pairinfo[i].PaC = pairinfo[i].PbC;
if(LbT > 0)
{
if(pairinfo[i].PbC > 0 || (pairinfo[i].PbC < 0 && RecoupClosedLoss))
{
Pa += pairinfo[i].PbC;
pairinfo[i].BEb -= ND(pairinfo[i].PbC / pairinfo[i].PipVal2 / (pairinfo[i].LbB - pairinfo[i].LbS), Digits);
}
}
if(UseCloseOldest && pairinfo[i].CbT >= CloseTradesLevel && pairinfo[i].CbC < MaxCloseTrades_)
{
if(!FirstRun && pairinfo[i].TPb > 0 && (ForceCloseOldest || (pairinfo[i].CbB > 0 && pairinfo[i].OPbO > pairinfo[i].TPb) || (pairinfo[i].CbS > 0 && pairinfo[i].OPbO < pairinfo[i].TPb)))
{
int Index = ExitTrades(T, DarkViolet, "Close Oldest Trade", pairinfo[i].TbO, ca,TradePairs[i]);
if(Index == 1)
{
if(OrderSelect(pairinfo[i].TbO, SELECT_BY_TICKET)) // yoh check return
{
pairinfo[i].PbC += OrderProfit() + OrderSwap() + OrderCommission();
ca = 0;
pairinfo[i].CbC++;
}
else
Print("OrderSelect error ", GetLastError()); // yoh
return (0);
}
}
}
if(AutoCal)
{
double GridATR = iATR(TradePairs[i]+suffix, TF[ATRTF], ATRPeriods, 0) / pairinfo[i].Pip;
if((pairinfo[i].CbT + pairinfo[i].CbC > Set4Level) && Set4Level > 0)
{
pairinfo[i].g2 = GridATR * 12; //GS*2*2*2*1.5
pairinfo[i].tp2 = GridATR * 18; //GS*2*2*2*1.5*1.5
}
else
if((pairinfo[i].CbT + pairinfo[i].CbC > Set3Level) && Set3Level > 0)
{
pairinfo[i].g2 = GridATR * 8; //GS*2*2*2
pairinfo[i].tp2 = GridATR * 12; //GS*2*2*2*1.5
}
else
if((pairinfo[i].CbT + pairinfo[i].CbC > Set2Level) && Set2Level > 0)
{
pairinfo[i].g2 = GridATR * 4; //GS*2*2
pairinfo[i].tp2 = GridATR * 8; //GS*2*2*2
}
else
if((pairinfo[i].CbT + pairinfo[i].CbC > Set1Level) && Set1Level > 0)
{
pairinfo[i].g2 = GridATR * 2; //GS*2
pairinfo[i].tp2 = GridATR * 4; //GS*2*2
}
else
{
pairinfo[i].g2 = GridATR;
pairinfo[i].tp2 = GridATR * 2;
}
pairinfo[i].GridTP = GridATR * 2;
}
else
{
int Index = (int) MathMax(MathMin(pairinfo[i].CbT + pairinfo[i].CbC, MaxTrades) - 1, 0);
pairinfo[i].g2 = GridArray[Index, 0];
pairinfo[i].tp2 = GridArray[Index, 1];
pairinfo[i].GridTP = GridArray[0, 1];
}
pairinfo[i].g2 = ND(MathMax(pairinfo[i].g2 * GAF * pairinfo[i].Pip, pairinfo[i].Pip), Digits);
pairinfo[i].tp2 = ND(pairinfo[i].tp2 * GAF * pairinfo[i].Pip, Digits);
pairinfo[i].GridTP = ND(pairinfo[i].GridTP * GAF * pairinfo[i].Pip, Digits);
if(UseMM)
{
if(pairinfo[i].CbT > 0) // Count basket
{
if(GlobalVariableCheck(ID + "LotMult"))
pairinfo[i].LotMult = (int) GlobalVariableGet(ID + "LotMult");
if(pairinfo[i].LbF != LotSize(pairinfo[i].Lots[0] * pairinfo[i].LotMult,i,pairinfo[i].LotDecimal,pairinfo[i].MinLotSize))
{
pairinfo[i].LotMult = (int)(pairinfo[i].LbF / pairinfo[i].Lots[0]);
GlobalVariableSet(ID + "LotMult", pairinfo[i].LotMult);
Print("LotMult reset to " + DTS(pairinfo[i].LotMult, 0));
}
}
else
if(pairinfo[i].CbT == 0)
{
double Contracts, Factor, Lotsize;
Contracts = pairinfo[i].PortionBalance / 10000; // MarketInfo(TradePairs[i]+suffix, MODE_LOTSIZE); ??
if(Multiplier_ <= 1)
Factor = Level;
else
Factor = (MathPow(Multiplier_, Level) - Multiplier_) / (Multiplier_ - 1);
Lotsize = LAF * AccountType * Contracts / (1 + Factor);
pairinfo[i].LotMult = (int) MathMax(MathFloor(Lotsize / pairinfo[i].Lot_), pairinfo[i].MinMult);
GlobalVariableSet(ID + "LotMult", pairinfo[i].LotMult);
}
}
else
if(pairinfo[i].CbT == 0)
pairinfo[i].LotMult = pairinfo[i].MinMult;
pairinfo[i].nLots = pairinfo[i].LbB - pairinfo[i].LbS;
if(pairinfo[i].CbT > 0 && (pairinfo[i].TPb == 0 || pairinfo[i].CbT != pairinfo[i].CaL || pairinfo[i].BEbL != pairinfo[i].BEb || pairinfo[i].BCa != pairinfo[i].BCaL || FirstRun))
{
string sCalcTP = TradePairs[i]+"Set New TP: BE: " + DTS(pairinfo[i].BEb, Digits);
double NewTP = 0, BasePips=0; //set BasePips to Zero, don't know if this will have an impact
pairinfo[i].CaL = pairinfo[i].CbT;
pairinfo[i].BCaL = pairinfo[i].BCa;
pairinfo[i].BEbL = pairinfo[i].BEb;
if(pairinfo[i].nLots == 0)
{
pairinfo[i].nLots = 1;
} // divide by zero error fix ... r.f.
BasePips = ND(pairinfo[i].Lot_ * pairinfo[i].LotMult * pairinfo[i].GridTP * (pairinfo[i].CbT + pairinfo[i].CbC) / pairinfo[i].nLots, Digits);
if(pairinfo[i].CbB > 0)
{
if(pairinfo[i].ForceTPPips_ > 0)
{
NewTP = pairinfo[i].BEb + pairinfo[i].ForceTPPips_;
sCalcTP = sCalcTP + " +Force TP (" + DTS(pairinfo[i].ForceTPPips_, Digits) + ") ";
}
else
if(pairinfo[i].CbC > 0 && pairinfo[i].CloseTPPips_ > 0)
{
NewTP = pairinfo[i].BEb + pairinfo[i].CloseTPPips_;
sCalcTP = sCalcTP + " +Close TP (" + DTS(pairinfo[i].CloseTPPips_, Digits) + ") ";
}
else
if(pairinfo[i].BEb + BasePips > pairinfo[i].OPbL + pairinfo[i].tp2)
{
NewTP = pairinfo[i].BEb + BasePips;
sCalcTP = sCalcTP + " +Base TP: (" + DTS(BasePips, Digits) + ") ";
}
else
{
NewTP = pairinfo[i].OPbL + pairinfo[i].tp2;
sCalcTP = sCalcTP + " +Grid TP: (" + DTS(pairinfo[i].tp2, Digits) + ") ";
}
if(pairinfo[i].MinTPPips_ > 0)
{
NewTP = MathMax(NewTP, pairinfo[i].BEb + pairinfo[i].MinTPPips_);
sCalcTP = sCalcTP + " >Minimum TP: ";
}
NewTP += pairinfo[i].MoveTP_ * pairinfo[i].Moves;
if(BreakEvenTrade > 0 && pairinfo[i].CbT + pairinfo[i].CbC >= BreakEvenTrade)
{
NewTP = pairinfo[i].BEb + pairinfo[i].BEPlusPips_;
sCalcTP = sCalcTP + " >BreakEven: (" + DTS(pairinfo[i].BEPlusPips_, Digits) + ") ";
}
sCalcTP = (sCalcTP + "Buy: TakeProfit: ");
}
else
if(pairinfo[i].CbS > 0)
{
if(pairinfo[i].ForceTPPips_ > 0)
{
NewTP = pairinfo[i].BEb - pairinfo[i].ForceTPPips_;
sCalcTP = sCalcTP + " -Force TP (" + DTS(pairinfo[i].ForceTPPips_, Digits) + ") ";
}
else
if(pairinfo[i].CbC > 0 && pairinfo[i].CloseTPPips_ > 0)
{
NewTP = pairinfo[i].BEb - pairinfo[i].CloseTPPips_;
sCalcTP = sCalcTP + " -Close TP (" + DTS(pairinfo[i].CloseTPPips_, Digits) + ") ";
}
else
if(pairinfo[i].BEb + BasePips < pairinfo[i].OPbL - pairinfo[i].tp2)
{
NewTP = pairinfo[i].BEb + BasePips;
sCalcTP = sCalcTP + " -Base TP: (" + DTS(BasePips, Digits) + ") ";
}
else
{
NewTP = pairinfo[i].OPbL - pairinfo[i].tp2;
sCalcTP = sCalcTP + " -Grid TP: (" + DTS(pairinfo[i].tp2, Digits) + ") ";
}
if(pairinfo[i].MinTPPips_ > 0)
{
NewTP = MathMin(NewTP, pairinfo[i].BEb - pairinfo[i].MinTPPips_);
sCalcTP = sCalcTP + " >Minimum TP: ";
}
NewTP -= pairinfo[i].MoveTP_ * pairinfo[i].Moves;
if(BreakEvenTrade > 0 && pairinfo[i].CbT + pairinfo[i].CbC >= BreakEvenTrade)
{
NewTP = pairinfo[i].BEb - pairinfo[i].BEPlusPips_;
sCalcTP = sCalcTP + " >BreakEven: (" + DTS(pairinfo[i].BEPlusPips_, Digits) + ") ";
}
sCalcTP = (sCalcTP + "Sell: TakeProfit: ");
}
if(pairinfo[i].TPb != NewTP)
{
pairinfo[i].TPb = NewTP;
if(pairinfo[i].nLots > 0)
pairinfo[i].TargetPips = ND(pairinfo[i].TPb - pairinfo[i].BEb, Digits);
else
pairinfo[i].TargetPips = ND(pairinfo[i].BEb - pairinfo[i].TPb, Digits);
Print(sCalcTP + DTS(NewTP, Digits));
return (0);
}
}
pairinfo[i].PbTarget = pairinfo[i].TargetPips / pairinfo[i].Pip;
pairinfo[i].ProfitPot = ND(pairinfo[i].TargetPips * pairinfo[i].PipVal2 * MathAbs(pairinfo[i].nLots), 2);
if(pairinfo[i].CbB > 0)
pairinfo[i].PbPips = ND((pairinfo[i].BID - pairinfo[i].BEb) / pairinfo[i].Pip, 1);
if(pairinfo[i].CbS > 0)
pairinfo[i].PbPips = ND((pairinfo[i].BEb - pairinfo[i].ASK) / pairinfo[i].Pip, 1);
pairinfo[i].BEa = pairinfo[i].BEb;
pairinfo[i].TPa = pairinfo[i].TPb;
double EEStartTime = 0, TPaF;
if(UseEarlyExit && pairinfo[i].CbT > 0)
{
datetime EEopt;
if(EEFirstTrade)
EEopt = pairinfo[i].OTbF;
else
Показано первые 50% кода (символов: 73630)
Что вы получите после оплаты
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? Адрес передаётся вместе с заказом в магазин и сохраняется для связи заказа с оплатой. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.