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

Blessing 3

blessing_3_v3.9.6.18.mq4

Похожие материалы по тегам

blessing_3_v3_9_6.mq4MQL4 / MetaTrader 4 · 4 общих теговblessing_3_v3.9.6.15.mq4MQL4 / MetaTrader 4 · 4 общих теговblessing_3_v3.9.6.23.mq4MQL4 / MetaTrader 4 · 4 общих теговblessing 3 v4.mq4MQL4 / MetaTrader 4 · 4 общих теговblessing_3_v3.9.6.21.mq4MQL4 / MetaTrader 4 · 4 общих теговblessinglite-gamma.mq4MQL4 / MetaTrader 4 · 4 общих тегов
Вы автор или правообладатель?

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

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

О программе

Советник предоставляет гибкие настройки сетки, стоп-лоссов, трейлинг-стопов и раннего выхода, а также включает защиту от низкой маржи, управление рисками по просадке и аварийное закрытие всех позиций. Доступны функции хеджирования коррелированных инструментов, настройка праздничных дней, отправка уведомлений по email и отображение информационной панели на графике.

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

НастройкаОписание
Version_3_9_6_18 Версия — Текстовая метка версии настроек советника.
TradeComment Комментарий сделки — Текст, добавляемый к комментарию каждой открытой сделки.
Notes Заметки — Произвольные заметки пользователя.
EA Magic Number (EANumber) Магический номер EA — Уникальный идентификатор ордеров советника.
CLOSE ALL NOW *** (EmergencyCloseAll) Аварийное закрытие всех — Принудительное закрытие всех позиций и ордеров при активации.
. (s1) Разделитель — Текстовый разделитель в интерфейсе настроек.
NO NEW TRADES *** (ShutDown) Остановка торговли — Запрет открытия новых сделок после закрытия текущей корзины.
. (s2) Разделитель — Текстовый разделитель в интерфейсе настроек.
== ACCOUNT SETTINGS == (LabelAcc) Настройки аккаунта — Группа параметров, связанных с управлением счётом.
. (s3) Разделитель — Текстовый разделитель с подсказкой о поведении PortionPC.
Opt. with 'Open prices only' -- (eopb) Разделитель — Текстовый разделитель для настройки Open Prices Only.
EnableOncePerBar Одна проверка на бар — Ограничение обработки сигналов одним разом за бар для ускорения тестирования.
UseMinMarginPercent Проверка минимальной маржи — Контроль уровня маржи перед открытием новой сделки.
MinMarginPercent Минимальный уровень маржи — Пороговый процент маржи, ниже которого новые сделки не открываются.
. (eopb1) Разделитель — Текстовый разделитель.
LOT SIZE ----------- (LabelLS) Настройки лота — Группа параметров размера лота.
UseMM (Money Management) (UseMM) Управление деньгами — Включение автоматического расчёта размера лота.
GRID SETTINGS ------ (LabelGS) Настройки сетки — Группа параметров сеточной торговли.
===== TRADING ===== (LabelTS) Торговля — Группа параметров торговли.
EXITS ----------- (LabelES) Выходы — Группа параметров выхода из сделок.
EARLY EXITS --------- (LabelEE) Ранние выходы — Группа параметров раннего выхода из позиции.
. (LabelAdv) Дополнительно — Текстовый разделитель.
GRID SIZE --------- (LabelGrid) Размер сетки — Группа параметров размера сетки.
. (LabelEST0) Разделитель — Текстовый разделитель.
== ENTRY PARAMETERS == (LabelEST) Параметры входа — Группа параметров входных сигналов.
MA ------------- (LabelMA) Скользящая средняя — Настройки индикатора MA для входа.
CCI ------------- (LabelCCI) CCI — Настройки индикатора CCI для входа.
BOLLINGER BANDS ----- (LabelBBS) Полосы Боллинджера — Настройки Bollinger Bands для входа.
STOCHASTIC -------- (LabelSto) Стохастик — Настройки стохастика для входа.
MACD ------------ (LabelMACD) MACD — Настройки MACD для входа.
SMART GRID --------- (LabelSG) Умная сетка — Настройки умной сетки на основе RSI.
. (LabelHS0) Разделитель — Текстовый разделитель.
HEDGE SETTINGS ----- (LabelHS) Хеджирование — Группа параметров хеджирования.
. (LabelOS0) Разделитель — Текстовый разделитель.
OTHER ----------- (LabelOS) Прочие — Группа прочих настроек.
EMAIL ------------ (LabelUE) Email — Группа настроек email-уведомлений.
. (LabelEDD) Порог DD для email — Пороги просадки для отправки email-предупреждений.
. (LabelEH) Часы между email — Минимальный интервал между email-уведомлениями.
DISPLAY ----------- (LabelDisplay) Отображение — Группа настроек информационной панели на графике.
Display font (displayFont) Шрифт — Шрифт текста информационной панели.
GRID OPTIMIZATION ---- (LabelGridOpt) Оптимизация сетки — Группа параметров для оптимизации сетки.
. (LabelOpt) Подсказка оптимизации — Текстовая подсказка о применении оптимизационных значений.
SetArray1 Массив 1 — Первое значение количества сделок для оптимизации сетки.
SetArray2 Массив 2 — Второе значение количества сделок для оптимизации сетки.
SetArray3 Массив 3 — Третье значение количества сделок для оптимизации сетки.
SetArray4 Массив 4 — Четвёртое значение количества сделок для оптимизации сетки.
GridArray1 Сетка 1 — Первое значение расстояния сетки для оптимизации.
GridArray2 Сетка 2 — Второе значение расстояния сетки для оптимизации.
GridArray3 Сетка 3 — Третье значение расстояния сетки для оптимизации.
GridArray4 Сетка 4 — Четвёртое значение расстояния сетки для оптимизации.
GridArray5 Сетка 5 — Пятое значение расстояния сетки для оптимизации.
TPArray1 ТП 1 — Первое значение тейк-профита для оптимизации.
TPArray2 ТП 2 — Второе значение тейк-профита для оптимизации.
TPArray3 ТП 3 — Третье значение тейк-профита для оптимизации.
TPArray4 ТП 4 — Четвёртое значение тейк-профита для оптимизации.
TPArray5 ТП 5 — Пятое значение тейк-профита для оптимизации.
Получить полный код

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

#property version   "396.18"
#property strict

#include <stdlib.mqh>
#include <stderror.mqh>
#include <WinUser32.mqh>

#define A 1                     //All (Basket + Hedge)
#define B 2                     //Basket
#define H 3                     //Hedge
#define T 4                     //Ticket
#define P 5                     //Pending

enum portChgs {
    no_change = 0,              // No changes
    increase = 1,               // Increase only
    any = -1,                   // Increase / decrease
};

enum mktCond {
    uptrend = 0,                // Long only
    downtrend = 1,              // Short only
    range = 2,                  // Long & short
    automatic = 3               // Automatic
};

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_18 = "EA Settings:";
input string TradeComment = "b3_v396.18";
input string Notes = "";
input int EANumber = 1;         // EA Magic Number
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 string s3 = "... PortionPC > 100 forces effective balance to that amount (e.g. 1000)"; //.
input double PortionPC = 100;;  // Percentage of account you want to trade on this pair
input portChgs PortionChange = increase;;       // Permitted Portion change with open basket

input double MaxDDPercent = 50;;        // Percent of portion for max drawdown level.
input double MaxSpread = 5;;    // Maximum allowed spread while placing trades
input bool UseHolidayShutdown = true;;  // 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 mktCond ForceMarketCond = 3;;     // Market condition

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 = true;        // 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 = 1.4;; // 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 = 21;;     // Number of periods for the ATR calculation
input double GAF = 1.0;;        // Widens/Squishes Grid in increments/decrements of .1
input int EntryDelay = 2400;;   // Time Grid in seconds, avoid opening lots of levels in fast market
input double EntryOffset = 5;;  // In pips, used in conjunction with logic to offset first trade entry
input bool UseSmartGrid = true;;        // 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 = 12;; // Close All level, when reaches this level, doesn't wait for TP to be hit
input double BEPlusPips = 2;;   // 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 = false;;     // Turns on TP move and Profit Trailing Stop Feature
input double ProfitSet = 70;;   // Profit trailing stop: Lock in profit at set percent of Total Profit Potential
input double MoveTP = 30;;      // 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 = "4,4";;    // Specifies number of open trades in each block (separated by a comma)
input string GridSetArray = "25,50,100";;       // Specifies number of pips away to issue limit order (separated by a comma)
input string TP_SetArray = "50,100,200";;       // Take profit for each block (separated by a comma)

input string LabelEST0 = "";    // .
input string LabelEST = "";     // ==  ENTRY PARAMETERS  ==
input string LabelMA = "";      // -------------     MA     -------------   
input entType MAEntry = 1;;     // MA Entry
input tFrame MA_TF = 0;;        // Time frame for MA calculation, r.f. ********
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 = 0;;      // Bollinger Entry
input int BollPeriod = 10;;     // Period for Bollinger
input double BollDistance = 10;;        // Up/Down spread
input double BollDeviation = 2.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 = 0;;        // 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 = 0;;        // RSI Applied Price
input int RSI_MA_Period = 10;;  // Period for MA of RSI calculation
input ENUM_MA_METHOD RSI_MA_Method = 0;;        // RSI MA Method

input string LabelHS0 = "";     //.
input string LabelHS = "";      // ------   HEDGE SETTINGS   -----

input string HedgeSymbol = "";; // Enter the Symbol of the same/correlated pair EXACTLY as used by your broker.
input int CorrPeriod = 30;;     // Number of days for checking Hedge Correlation
input bool UseHedge = false;;   // Turns DD hedge on/off
input string DDorLevel = "DD";; // DD = start hedge at set DD;Level = Start at set level
input double HedgeStart = 20;;  // DD Percent or Level at which Hedge starts
input double hLotMult = 0.8;;   // Hedge Lots = Open Lots * hLotMult
input double hMaxLossPips = 30;;        // DD Hedge maximum pip loss - also hedge trailing stop
input bool hFixedSL = false;;   // true = fixed SL at hMaxLossPips
input double hTakeProfit = 30;; // Hedge Take Profit
input double hReEntryPC = 5;;   // Increase to HedgeStart to stop early re-entry of the hedge
input bool StopTrailAtBE = true;;       // True = Trailing Stop will stop at BE;False = Hedge will continue into profit
input bool ReduceTrailStop = true;;     // False = Trailing Stop is Fixed;True = Trailing Stop will reduce after BE is reached

input string LabelOS0 = "";     //.
input string LabelOS = "";      // ------------   OTHER   -----------
input bool RecoupClosedLoss = true;;    // true = Recoup any Hedge/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

input string LabelDisplay = ""; // ------------   DISPLAY   -----------

input bool displayOverlay = true;;      // Enable display
input bool displayLogo = true;; // Display copyright and icon
input bool displayCCI = true;;  // Enable CCI display
input bool displayLines = true;;        // Show BE, TP and TS lines
input int displayXcord = 100;;  // Left / right offset
input int displayYcord = 30;;   // Up / down offset
input int displayCCIxCord = 10;;        // Moves CCI display left and right
input string displayFont = "Arial Bold";        //Display font
input int displayFontSize = 9;; // Changes size of display characters
input int displaySpacing = 14;; // Changes space between lines

input double displayRatio = 1.3;;       // Ratio to increase label width spacing
input color displayColor = DeepSkyBlue;;        // default color of display characters
input color displayColorProfit = Green;;        // default color of profit display characters
input color displayColorLoss = Red;;    // default color of loss display characters

input color displayColorFGnd = Black;;  // default color of ForeGround Text display characters
input bool Debug = false;;

input string LabelGridOpt = ""; // ----   GRID OPTIMIZATION   ----
input string LabelOpt = "These values can only be used while optimizing";       //.
input bool UseGridOpt = false;; // Set True in order to optimize the grid settings.

input int SetArray1 = 4;
input int SetArray2 = 4;
input int SetArray3 = 0;
input int SetArray4 = 0;
input int GridArray1 = 25;
input int GridArray2 = 50;
input int GridArray3 = 100;
input int GridArray4 = 0;
input int GridArray5 = 0;
input int TPArray1 = 50;
input int TPArray2 = 100;
input int TPArray3 = 200;
input int TPArray4 = 0;
input int TPArray5 = 0;

int ca;
int Magic, hMagic;
int CbT, CpT, ChT;              // Count basket Total,Count pending Total,Count hedge Total
double Pip, hPip;
int POSLCount;
double SLbL;                    // Stop Loss basket Last
int Moves;
double MaxDD;
double SLb;                     // Stop Loss
int AccountType;
double StopTradeBalance;
double InitialAB;               // Initial Account Balance
bool Testing, Visual;
bool AllowTrading;
bool EmergencyWarning;
double MaxDDPer;
int Error;
int Set1Level, Set2Level, Set3Level, Set4Level;
int EmailCount;
string sTF;
datetime EmailSent;
int GridArray[, 2];
double Lots[], MinLotSize, LotStep;
int LotDecimal, LotMult, MinMult;
bool PendLot;
string CS, UAE;
int HolShutDown;

int HolArray[, 4];
datetime HolFirst, HolLast, NextStats, OTbF;
double RSI[];
int Digit[, 2], TF[10] = { 0, 1, 5, 15, 30, 60, 240, 1440, 10080, 43200 };

double Email[3];
double PbC, PhC, hDDStart, PbMax, PbMin, PhMax, PhMin, LastClosedPL, ClosedPips, SLh, hLvlStart, StatLowEquity, StatHighEquity;
datetime EETime;
int hActive, EECount, TbF, CbC, CaL, FileHandle;
bool TradesOpen, FileClosed, HedgeTypeDD, hThisChart, hPosCorr, dLabels, FirstRun;
string FileName, ID, StatFile;
double TPb, StopLevel, TargetPips, LbF, bTS, PortionBalance;
bool checkResult;

int EANumber_;
double EntryOffset_;
double MoveTP_;
double MADistance_;
double BollDistance_;
double POSLPips_;
double hMaxLossPips_;
double hTakeProfit_;
double CloseTPPips_;
double ForceTPPips_;
double MinTPPips_;
double BEPlusPips_;
double SLPips_;
double TSLPips_;
double TSLPipsMin_;
string HedgeSymbol_;
bool UseHedge_;
double HedgeStart_;
double StopTradePercent_;
double ProfitSet_;
double EEHoursPC_;
double EELevelPC_;
double hReEntryPC_;
double PortionPC_;
double Lot_;
bool Debug_;
mktCond ForceMarketCond_;
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_;

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

int deinit() {
    switch (UninitializeReason()) {
    case REASON_REMOVE:
    case REASON_CHARTCLOSE:
    case REASON_CHARTCHANGE:
        if (CpT > 0) {
            while (CpT > 0)
                CpT -= ExitTrades(P, displayColorLoss, "Blessing Removed");
        }

        GlobalVariablesDeleteAll(ID);
    case REASON_RECOMPILE:
    case REASON_PARAMETERS:
    case REASON_ACCOUNT:
        if (!Testing)
            LabelDelete();

        Comment("");
    }

    return (0);
}

datetime OncePerBarTime = 0;

bool OncePerBar() {
    if (!EnableOncePerBar || FirstRun)
        return (true);          // always return true if disabled

    if (OncePerBarTime != Time[0]) {
        OncePerBarTime = Time[0];
        return (true);          // true, our first time this bar
    }

    return (false);
}

double LbT = 0;                 // total lots out

double previous_stop_trade_amount;
double stop_trade_amount;

int start() {
      // код доступен только после оплаты
   }
    int CbB = 0;                // Count buy
    int CbS = 0;                // Count sell
    int CpBL = 0;               // Count buy limit
    int CpSL = 0;               // Count sell limit
    int CpBS = 0;               // Count buy stop
    int CpSS = 0;               // Count sell stop
    double LbB = 0;             // Count buy lots
    double LbS = 0;             // Count sell lots

    double OPpBL = 0;           // Buy limit open price
    double OPpSL = 0;           // Sell limit open price
    double SLbB = 0;            // stop losses are set to zero if POSL off
    double SLbS = 0;            // stop losses are set to zero if POSL off
    double BCb = 0, BCh = 0, BCa;       // Broker costs (swap + commission)
    double ProfitPot = 0;       // The Potential Profit of a basket of Trades
    double PipValue, PipVal2, ASK, BID;
    double OrderLot;
    double OPbL = 0, OPhO = 0;  // last open price
    datetime OTbL = 0;          // last open time
    datetime OTbO = 0, OThO = 0;
    double g2, tp2, Entry, RSI_MA = 0, LhB = 0, LhS = 0, LhT, OPbO = 0;
    int Ticket = 0, ChB = 0, ChS = 0, IndEntry = 0, TbO = 0, ThO = 0;
    double Pb = 0, Ph = 0, PaC = 0, PbPips = 0, PbTarget = 0, DrawDownPC = 0, BEb = 0, BEh = 0, BEa = 0;
    bool BuyMe = false, SellMe = false, Success, SetPOSL;
    string IndicatorUsed;
    double EEpc = 0, OPbN = 0, nLots = 0;
    double bSL = 0, TPa = 0, TPbMP = 0;
    int Trend = 0;
    string ATrend;
    double cci_01 = 0, cci_02 = 0, cci_03 = 0, cci_04 = 0;
    double cci_11 = 0, cci_12 = 0, cci_13 = 0, cci_14 = 0;

    PipVal2 = MarketInfo(Symbol(), MODE_TICKVALUE) / MarketInfo(Symbol(), MODE_TICKSIZE);
    PipValue = PipVal2 * Pip;
    StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL) * Point;
    ASK = ND(MarketInfo(Symbol(), MODE_ASK), (int) MarketInfo(Symbol(), MODE_DIGITS));
    BID = ND(MarketInfo(Symbol(), MODE_BID), (int) MarketInfo(Symbol(), MODE_DIGITS));

    if (ASK == 0 || 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() == hMagic) {
            Ph += OrderProfit();
            BCh += OrderSwap() + OrderCommission();
            BEh += OrderLots() * OrderOpenPrice();

            if (OrderOpenTime() < OThO || OThO == 0) {
                OThO = OrderOpenTime();
                ThO = OrderTicket();
                OPhO = OrderOpenPrice();
            }

            if (Type == OP_BUY) {
                ChB++;
                LhB += OrderLots();
            } else if (Type == OP_SELL) {
                ChS++;
                LhS += OrderLots();
            }

            continue;
        }

        if (OrderMagicNumber() != Magic || OrderSymbol() != Symbol())
            continue;

        if (OrderTakeProfit() > 0)
            ModifyOrder(OrderOpenPrice(), OrderStopLoss());

        if (Type <= OP_SELL) {
            Pb += OrderProfit();
            BCb += OrderSwap() + OrderCommission();
            BEb += OrderLots() * OrderOpenPrice();

            if (OrderOpenTime() >= OTbL) {
                OTbL = OrderOpenTime();
                OPbL = OrderOpenPrice();
            }

            if (OrderOpenTime() < OTbF || TbF == 0) {
                OTbF = OrderOpenTime();
                TbF = OrderTicket();
                LbF = OrderLots();
            }

            if (OrderOpenTime() < OTbO || OTbO == 0) {
                OTbO = OrderOpenTime();
                TbO = OrderTicket();
                OPbO = OrderOpenPrice();
            }

            if (UsePowerOutSL && ((POSLPips_ > 0 && OrderStopLoss() == 0) || (POSLPips_ == 0 && OrderStopLoss() > 0)))
                SetPOSL = true;

            if (Type == OP_BUY) {
                CbB++;
                LbB += OrderLots();
                continue;
            } else {
                CbS++;
                LbS += OrderLots();
                continue;
            }
        } else {
            if (Type == OP_BUYLIMIT) {
                CpBL++;
                OPpBL = OrderOpenPrice();
                continue;
            } else if (Type == OP_SELLLIMIT) {
                CpSL++;
                OPpSL = OrderOpenPrice();
                continue;
            } else if (Type == OP_BUYSTOP)
                CpBS++;
            else
                CpSS++;
        }
    }

    CbT = CbB + CbS;
    LbT = LbB + LbS;
    Pb = ND(Pb + BCb, 2);
    ChT = ChB + ChS;
    LhT = LhB + LhS;
    Ph = ND(Ph + BCh, 2);
    CpT = CpBL + CpSL + CpBS + CpSS;
    BCa = BCb + BCh;

    if (LbT > 0) {
        BEb = ND(BEb / LbT, Digits);

        if (BCa < 0) {	// broker costs
			if (LbB - LbS != 0) // r.f., fix divide by zero on following line
				BEb -= ND(BCa / PipVal2 / (LbB - LbS), Digits);
		}

        if (Pb > PbMax || PbMax == 0)
            PbMax = Pb;

        if (Pb < PbMin || PbMin == 0)
            PbMin = Pb;

        if (!TradesOpen) {
            FileHandle = FileOpen(FileName, FILE_BIN | FILE_WRITE);

            if (FileHandle > -1) {
                FileWriteInteger(FileHandle, TbF);
                FileClose(FileHandle);
                TradesOpen = true;

                if (Debug_)
                    Print(FileName, " File Written: ", TbF);
            }
        }
    } else if (TradesOpen) {
        TPb = 0;
        PbMax = 0;
        PbMin = 0;
        OTbF = 0;
        TbF = 0;
        LbF = 0;
        PbC = 0;
        PhC = 0;
        PaC = 0;
        ClosedPips = 0;
        CbC = 0;
        CaL = 0;
        bTS = 0;

        if (HedgeTypeDD)
            hDDStart = HedgeStart_;
        else
            hLvlStart = HedgeStart_;

        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");

                TradesOpen = false;
            } else
                Print("Error ", Error, " {", ErrorDescription(Error), ") deleting file ", FileName);
        } else
            TradesOpen = false;
    }

    if (LhT > 0) {
        BEh = ND(BEh / LhT, Digits);

        if (Ph > PhMax || PhMax == 0)
            PhMax = Ph;

        if (Ph < PhMin || PhMin == 0)
            PhMin = Ph;
    } else {
        PhMax = 0;
        PhMin = 0;
        SLh = 0;
    }

    if (CbT == 0 && ChT == 0 && ShutDown_) {
        if (CpT > 0) {
            ExitTrades(P, displayColorLoss, "Blessing is shutting down");

            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 " + Symbol() + " " + sTF + ". To resume trading, change ShutDown to false.");
            Error = GetLastError();

            if (Error > 0)
                Print("Error ", Error, " (", ErrorDescription(Error), ") sending email");
            else
                EmailCount = *;
        }
    }

    static bool LDelete;

    if (!AllowTrading) {
        if (!LDelete) {
            LDelete = true;
            LabelDelete();

            if (ObjectFind("B3LStop") == -1) {
                CreateLabel("B3LStop", "Trading has stopped on this pair.", 10, 0, 0, 3, displayColorLoss);
                CreateLabel("B3LLogo", "I", 27, 3, 10, 10, Red, "Wingdings");   // I = open hand (stop)
            }

            string Tab = "Tester Journal";

            if (!Testing)
                Tab = "Terminal Experts";

            if (ObjectFind("B3LExpt") == -1)
                CreateLabel("B3LExpt", "Check the " + Tab + " tab for the reason.", 10, 0, 0, 6, displayColorLoss);

            if (ObjectFind("B3LResm") == -1)
                CreateLabel("B3LResm", "Reset Blessing to resume trading.", 10, 0, 0, 9, displayColorLoss);
        }

        return (0);
    } else {
        LDelete = false;
        ObjDel("B3LStop");
        ObjDel("B3LExpt");
        ObjDel("B3LResm");
    }

	double temp_account_balance = AccountBalance();
	double NewPortionBalance;
	if (PortionPC > 100 && temp_account_balance > PortionPC) {
		NewPortionBalance = ND(PortionPC, 2);
	} else {
		NewPortionBalance = ND(temp_account_balance * PortionPC_, 2);
	}

    if (CbT == 0 || PortionChange < 0 || (PortionChange > 0 && NewPortionBalance > PortionBalance))
        PortionBalance = NewPortionBalance;

	if (Pb + Ph < 0)	// *******************************
		DrawDownPC = -(Pb + Ph) / PortionBalance;   // opb
	if (!FirstRun && DrawDownPC >= MaxDDPercent / 100) {
		ExitTrades(A, displayColorLoss, "Equity StopLoss Reached");

		if (PlaySounds)
			PlaySound(AlertSound);

		return (0);
	}				// ***********************************
	if (-(Pb + Ph) > MaxDD)
		MaxDD = -(Pb + Ph);

	MaxDDPer = MathMax(MaxDDPer, DrawDownPC * 100);

	if (SaveStats)
		Stats(false, TimeCurrent() < NextStats, PortionBalance, Pb + Ph);

	double StepAB = InitialAB * (1 + StopTradePercent_);
	double StepSTB;
	double temp_ab = AccountBalance();
	if (PortionPC > 100 && temp_ab > PortionPC) {
		StepSTB = PortionPC * (1 - StopTradePercent_);
	} else {
		StepSTB = temp_ab * (1 - StopTradePercent_);
	}
	double NextISTB = StepAB * (1 - StopTradePercent_);

	if (StepSTB > NextISTB) {
		InitialAB = StepAB;
		StopTradeBalance = StepSTB;
	}

	double InitialAccountMultiPortion = StopTradeBalance * PortionPC_;
	stop_trade_amount = InitialAccountMultiPortion;

	if (PortionBalance < InitialAccountMultiPortion) {
		if (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) + " " + Symbol() + " " + (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(Symbol(), MA_TF, MAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);

	if (ForceMarketCond_ == 3) {
		if (BID > ima_0 + MADistance_)
			Trend = 0;
		else if (ASK < ima_0 - MADistance_)
			Trend = 1;
		else
			Trend = 2;
	} else {
		Trend = ForceMarketCond_;

		if (Trend != 0 && BID > ima_0 + MADistance_)
			ATrend = "U";

		if (Trend != 1 && ASK < ima_0 - MADistance_)
			ATrend = "D";

		if (Trend != 2 && (BID < ima_0 + MADistance_ && ASK > ima_0 - MADistance_))
			ATrend = "R";
	}

    if (OncePerBar()) {	// **************************************************

        double Pa = Pb;
        PaC = PbC + PhC;

        if (hActive == 1 && ChT == 0) {
            PhC = FindClosedPL(H);
            hActive = 0;

            return (0);
        } else if (hActive == 0 && ChT > 0)
            hActive = 1;

        if (LbT > 0) {
            if (PbC > 0 || (PbC < 0 && RecoupClosedLoss)) {
                Pa += PbC;
                BEb -= ND(PbC / PipVal2 / (LbB - LbS), Digits);
            }

            if (PhC > 0 || (PhC < 0 && RecoupClosedLoss)) {
                Pa += PhC;
                BEb -= ND(PhC / PipVal2 / (LbB - LbS), Digits);
            }

            if (Ph > 0 || (Ph < 0 && RecoupClosedLoss))
                Pa += Ph;
        }

        if (UseCloseOldest && CbT >= CloseTradesLevel && CbC < MaxCloseTrades_) {
            if (!FirstRun && TPb > 0 && (ForceCloseOldest || (CbB > 0 && OPbO > TPb) || (CbS > 0 && OPbO < TPb))) {
                int Index = ExitTrades(T, DarkViolet, "Close Oldest Trade", TbO);

                if (Index == 1) {
                    if (OrderSelect(TbO, SELECT_BY_TICKET)) {   // yoh check return
                        PbC += OrderProfit() + OrderSwap() + OrderCommission();
                        ca = 0;
                        CbC++;
                    } else
                        Print("OrderSelect error ", GetLastError());    // yoh

                    return (0);
                }
            }
        }

        double GridTP;

        if (AutoCal) {
            double GridATR = iATR(NULL, TF[ATRTF], ATRPeriods, 0) / Pip;

            if ((CbT + CbC > Set4Level) && Set4Level > 0) {
                g2 = GridATR * 12;      //GS*2*2*2*1.5
                tp2 = GridATR * 18;     //GS*2*2*2*1.5*1.5
            } else if ((CbT + CbC > Set3Level) && Set3Level > 0) {
                g2 = GridATR * 8;       //GS*2*2*2
                tp2 = GridATR * 12;     //GS*2*2*2*1.5
            } else if ((CbT + CbC > Set2Level) && Set2Level > 0) {
                g2 = GridATR * 4;       //GS*2*2
                tp2 = GridATR * 8;      //GS*2*2*2
            } else if ((CbT + CbC > Set1Level) && Set1Level > 0) {
                g2 = GridATR * 2;       //GS*2
                tp2 = GridATR * 4;      //GS*2*2
            } else {
                g2 = GridATR;
                tp2 = GridATR * 2;
            }

            GridTP = GridATR * 2;
        } else {
            int Index = (int) MathMax(MathMin(CbT + CbC, MaxTrades) - 1, 0);
            g2 = GridArray[Index, 0];
            tp2 = GridArray[Index, 1];
            GridTP = GridArray[0, 1];
        }

        g2 = ND(MathMax(g2 * GAF * Pip, Pip), Digits);
        tp2 = ND(tp2 * GAF * Pip, Digits);
        GridTP = ND(GridTP * GAF * Pip, Digits);

        if (UseMM) {
            if (CbT > 0)        // Count basket Total
            {
                if (GlobalVariableCheck(ID + "LotMult"))
                    LotMult = (int) GlobalVariableGet(ID + "LotMult");

                if (LbF != LotSize(Lots[0] * LotMult)) {
                    LotMult = (int) (LbF / Lots[0]);
                    GlobalVariableSet(ID + "LotMult", LotMult);
                    Print("LotMult reset to " + DTS(LotMult, 0));
                }
            } else if (CbT == 0) {
                double Contracts, Factor, Lotsize;
                Contracts = PortionBalance / 10000;     // MarketInfo(Symbol(), MODE_LOTSIZE); ??

                if (Multiplier_ <= 1)
                    Factor = Level;
                else
                    Factor = (MathPow(Multiplier_, Level) - Multiplier_) / (Multiplier_ - 1);

                Lotsize = LAF * AccountType * Contracts / (1 + Factor);
                LotMult = (int) MathMax(MathFloor(Lotsize / Lot_), MinMult);
                GlobalVariableSet(ID + "LotMult", LotMult);
            }
        } else if (CbT == 0)
            LotMult = MinMult;

        static double BCaL, BEbL;
        nLots = LbB - LbS;

        if (CbT > 0 && (TPb == 0 || CbT + ChT != CaL || BEbL != BEb || BCa != BCaL || FirstRun)) {
            string sCalcTP = "Set New TP:  BE: " + DTS(BEb, Digits);
            double NewTP = 0, BasePips;
            CaL = CbT + ChT;
            BCaL = BCa;
            BEbL = BEb;
            if (nLots == 0) {
                nLots = 1;
            }                   // divide by zero error fix ... r.f.
            BasePips = ND(Lot_ * LotMult * GridTP * (CbT + CbC) / nLots, Digits);

            if (CbB > 0) {
                if (ForceTPPips_ > 0) {
                    NewTP = BEb + ForceTPPips_;
                    sCalcTP = sCalcTP + " +Force TP (" + DTS(ForceTPPips_, Digits) + ") ";
                } else if (CbC > 0 && CloseTPPips_ > 0) {
                    NewTP = BEb + CloseTPPips_;
                    sCalcTP = sCalcTP + " +Close TP (" + DTS(CloseTPPips_, Digits) + ") ";
                } else if (BEb + BasePips > OPbL + tp2) {
                    NewTP = BEb + BasePips;
                    sCalcTP = sCalcTP + " +Base TP: (" + DTS(BasePips, Digits) + ") ";
                } else {
                    NewTP = OPbL + tp2;
                    sCalcTP = sCalcTP + " +Grid TP: (" + DTS(tp2, Digits) + ") ";
                }

                if (MinTPPips_ > 0) {
                    NewTP = MathMax(NewTP, BEb + MinTPPips_);
                    sCalcTP = sCalcTP + " >Minimum TP: ";
                }

                NewTP += MoveTP_ * Moves;

                if (BreakEvenTrade > 0 && CbT + CbC >= BreakEvenTrade) {
                    NewTP = BEb + BEPlusPips_;
                    sCalcTP = sCalcTP + " >BreakEven: (" + DTS(BEPlusPips_, Digits) + ") ";
                }

                sCalcTP = (sCalcTP + "Buy: TakeProfit: ");
            } else if (CbS > 0) {
                if (ForceTPPips_ > 0) {
                    NewTP = BEb - ForceTPPips_;
                    sCalcTP = sCalcTP + " -Force TP (" + DTS(ForceTPPips_, Digits) + ") ";
                } else if (CbC > 0 && CloseTPPips_ > 0) {
                    NewTP = BEb - CloseTPPips_;
                    sCalcTP = sCalcTP + " -Close TP (" + DTS(CloseTPPips_, Digits) + ") ";
                } else if (BEb + BasePips < OPbL - tp2) {
                    NewTP = BEb + BasePips;
                    sCalcTP = sCalcTP + " -Base TP: (" + DTS(BasePips, Digits) + ") ";
                } else {
                    NewTP = OPbL - tp2;
                    sCalcTP = sCalcTP + " -Grid TP: (" + DTS(tp2, Digits) + ") ";
                }

                if (MinTPPips_ > 0) {
                    NewTP = MathMin(NewTP, BEb - MinTPPips_);
                    sCalcTP = sCalcTP + " >Minimum TP: ";
                }

                NewTP -= MoveTP_ * Moves;

                if (BreakEvenTrade > 0 && CbT + CbC >= BreakEvenTrade) {
                    NewTP = BEb - BEPlusPips_;
                    sCalcTP = sCalcTP + " >BreakEven: (" + DTS(BEPlusPips_, Digits) + ") ";
                }

                sCalcTP = (sCalcTP + "Sell: TakeProfit: ");
            }

            if (TPb != NewTP) {
                TPb = NewTP;

                if (nLots > 0)
                    TargetPips = ND(TPb - BEb, Digits);
                else
                    TargetPips = ND(BEb - TPb, Digits);

                Print(sCalcTP + DTS(NewTP, Digits));

                return (0);
            }
        }

        PbTarget = TargetPips / Pip;
        ProfitPot = ND(TargetPips * PipVal2 * MathAbs(nLots), 2);

        if (CbB > 0)
            PbPips = ND((BID - BEb) / Pip, 1);

        if (CbS > 0)
            PbPips = ND((BEb - ASK) / Pip, 1);

        double hAsk = MarketInfo(HedgeSymbol_, MODE_ASK);
        double hBid = MarketInfo(HedgeSymbol_, MODE_BID);
        double hSpread = hAsk - hBid;

        if (hThisChart)
            nLots += LhB - LhS;

        double PhPips;

        if (hActive == 1) {
            if (nLots == 0) {
                BEa = 0;
                TPa = 0;
            } else if (hThisChart) {
                if (nLots > 0) {
                    if (CbB > 0)
                        BEa = ND((BEb * LbT - (BEh - hSpread) * LhT) / (LbT - LhT), Digits);
                    else
                        BEa = ND(((BEb - (ASK - BID)) * LbT - BEh * LhT) / (LbT - LhT), Digits);

                    TPa = ND(BEa + TargetPips, Digits);
                } else {
                    if (CbS > 0)
                        BEa = ND((BEb * LbT - (BEh + hSpread) * LhT) / (LbT - LhT), Digits);
                    else
                        BEa = ND(((BEb + ASK - BID) * LbT - BEh * LhT) / (LbT - LhT), Digits);

                    TPa = ND(BEa - TargetPips, Digits);
                }
            }

            if (ChB > 0)
                PhPips = ND((hBid - BEh) / hPip, 1);

            if (ChS > 0)
                PhPips = ND((BEh - hAsk) / hPip, 1);
        } else {
            BEa = BEb;
            TPa = TPb;
        }

        double EEStartTime = 0, TPaF;

        if (UseEarlyExit && CbT > 0) {
            datetime EEopt;

            if (EEFirstTrade)
                EEopt = OTbF;
            else
                EEopt = OTbL;

            if (DayOfWeek() < TimeDayOfWeek(EEopt))
                EEStartTime = 2 * 24 * 3600;

            EEStartTime += EEopt + EEStartHours * 3600;

            if (EEHoursPC_ > 0 && TimeCurrent() >= EEStartTime)
                EEpc = EEHoursPC_ * (TimeCurrent() - EEStartTime) / 3600;

            if (EELevelPC_ > 0 && (CbT + CbC) >= EEStartLevel)
                EEpc += EELevelPC_ * (CbT + CbC - EEStartLevel + 1);

            EEpc = 1 - EEpc;

            if (!EEAllowLoss && EEpc < 0)
                EEpc = 0;

            PbTarget *= EEpc;
            TPaF = ND((TPa - BEa) * EEpc + BEa, Digits);

            if (displayOverlay && displayLines && (hActive != 1 || (hActive == 1 && hThisChart)) && (!Testing || (Testing && Visual)) &&
                EEpc < 1 && (CbT + CbC + ChT > EECount || EETime != Time[0]) && ((EEHoursPC_ > 0 && EEopt + EEStartHours * 3600 < Time[0]) || (EELevelPC_ > 0 && CbT + CbC >= EEStartLevel))) {
                EETime = Time[0];
                EECount = CbT + CbC + ChT;

                if (ObjectFind("B3LEELn") < 0) {
                    ObjectCreate("B3LEELn", OBJ_TREND, 0, 0, 0);
                    ObjectSet("B3LEELn", OBJPROP_COLOR, Yellow);
                    ObjectSet("B3LEELn", OBJPROP_WIDTH, 1);
                    ObjectSet("B3LEELn", OBJPROP_STYLE, 0);
                    ObjectSet("B3LEELn", OBJPROP_RAY, false);
                    ObjectSet("B3LEELn", OBJPROP_BACK, false);
                }

                if (EEHoursPC_ > 0)
                    ObjectMove("B3LEELn", 0, (datetime) (MathFloor(EEopt / 3600 + EEStartHours) * 3600), TPa);
                else
                    ObjectMove("B3LEELn", 0, (datetime) (MathFloor(EEopt / 3600) * 3600), TPaF);

                ObjectMove("B3LEELn", 1, Time[1], TPaF);

                if (ObjectFind("B3VEELn") < 0) {
                    ObjectCreate("B3VEELn", OBJ_TEXT, 0, 0, 0);
                    ObjectSet("B3VEELn", OBJPROP_COLOR, Yellow);
                    ObjectSet("B3VEELn", OBJPROP_WIDTH, 1);
                    ObjectSet("B3VEELn", OBJPROP_STYLE, 0);
                    ObjectSet("B3VEELn", OBJPROP_BACK, false);
                }

                ObjSetTxt("B3VEELn", "              " + DTS(TPaF, Digits), -1, Yellow);
                ObjectSet("B3VEELn", OBJPROP_PRICE1, TPaF + 2 * Pip);
                ObjectSet("B3VEELn", OBJPROP_TIME1, Time[1]);
            } else if ((!displayLines || EEpc == 1 || (!EEAllowLoss && EEpc == 0) || (EEHoursPC_ > 0 && EEopt + EEStartHours * 3600 >= Time[0]))) {
                ObjDel("B3LEELn");
                ObjDel("B3VEELn");
            }
        } else {
            TPaF = TPa;
            EETime = 0;
            EECount = 0;
            ObjDel("B3LEELn");
            ObjDel("B3VEELn");
        }

        if (MaximizeProfit) {
            if (CbT == 0) {
                SLbL = 0;
                Moves = 0;
                SLb = 0;
            }

            if (!FirstRun && CbT > 0) {
                if (Pb + Ph < 0 && SLb > 0)
                    SLb = 0;

                if (SLb > 0 && ((nLots > 0 && BID < SLb) || (nLots < 0 && ASK > SLb))) {
                    ExitTrades(A, displayColorProfit, "Profit Trailing Stop Reached (" + DTS(ProfitSet_ * 100, 2) + "%)");

                    return (0);
                }

                if (PbTarget > 0) {
                    TPbMP = ND(BEa + (TPa - BEa) * ProfitSet_, Digits);

                    if ((nLots > 0 && BID > TPbMP) || (nLots < 0 && ASK < TPbMP))
                        SLb = TPbMP;
                }

                if (SLb > 0 && SLb != SLbL && MoveTP_ > 0 && TotalMoves > Moves) {
                    TPb = 0;
                    Moves++;

                    if (Debug_)
                        Print("MoveTP");

                    SLbL = SLb;

                    if (PlaySounds)
                        PlaySound(AlertSound);

                    return (0);
                }
            }
        }

        if (!FirstRun && TPaF > 0) {
            if ((nLots > 0 && BID >= TPaF) || (nLots < 0 && ASK <= TPaF)) {
                ExitTrades(A, displayColorProfit, "Profit Target Reached @ " + DTS(TPaF, Digits));

                return (0);
            }
        }

        if (!FirstRun && UseStopLoss) {
            if (SLPips_ > 0) {
                if (nLots > 0) {
                    bSL = BEa - SLPips_;

                    if (BID <= bSL) {
                        ExitTrades(A, displayColorProfit, "Stop Loss Reached");

                        return (0);
                    }
                } else if (nLots < 0) {
                    bSL = BEa + SLPips_;

                    if (ASK >= bSL) {
                        ExitTrades(A, displayColorProfit, "Stop Loss Reached");

                        return (0);
                    }
                }
            }

            if (TSLPips_ != 0) {
                if (nLots > 0) {
                    if (TSLPips_ > 0 && BID > BEa + TSLPips_)
                        bTS = MathMax(bTS, BID - TSLPips_);

                    if (TSLPips_ < 0 && BID > BEa - TSLPips_)
                        bTS = MathMax(bTS, BID - MathMax(TSLPipsMin_, -TSLPips_ * (1 - (BID - BEa + TSLPips_) / (-TSLPips_ * 2))));

                    if (bTS > 0 && BID <= bTS) {
                        ExitTrades(A, displayColorProfit, "Trailing Stop Reached");

                        return (0);
                    }
                } else if (nLots < 0) {
                    if (TSLPips_ > 0 && ASK < BEa - TSLPips_) {
                        if (bTS > 0)
                            bTS = MathMin(bTS, ASK + TSLPips_);
                        else
                            bTS = ASK + TSLPips_;
                    }

                    if (TSLPips_ < 0 && ASK < BEa + TSLPips_)
                        bTS = MathMin(bTS, ASK + MathMax(TSLPipsMin_, -TSLPips_ * (1 - (BEa - ASK + TSLPips_) / (-TSLPips_ * 2))));

                    if (bTS > 0 && ASK >= bTS) {
                        ExitTrades(A, displayColorProfit, "Trailing Stop Reached");

                        return (0);
                    }
                }
            }
        }

        if (CbT == 0 && !PendLot) {
            PendLot = true;

            for (int Order = OrdersTotal() - 1; Order >= 0; Order--) {
                if (!OrderSelect(Order, SELECT_BY_POS, MODE_TRADES))
                    continue;

                if (OrderMagicNumber() != Magic || OrderType() <= OP_SELL)
                    continue;

                if (ND(OrderLots(), LotDecimal) > ND(Lots[0] * LotMult, LotDecimal)) {
                    PendLot = false;

                    while (IsTradeContextBusy())
                        Sleep(100);

                    if (IsStopped())
                        return (-1);

                    Success = OrderDelete(OrderTicket());

                    if (Success) {
                        PendLot = true;

                        if (Debug_)
                            Print("Delete pending > Lot");
                    }
                }
            }

            return (0);
        } else if ((CbT > 0 || (CbT == 0 && CpT > 0 && !B3Traditional)) && PendLot) {
            PendLot = false;

            for (int Order = OrdersTotal() - 1; Order >= 0; Order--) {
                if (!OrderSelect(Order, SELECT_BY_POS, MODE_TRADES))
                    continue;

                if (OrderMagicNumber() != Magic || OrderType() <= OP_SELL)
                    continue;

                if (ND(OrderLots(), LotDecimal) == ND(Lots[0] * LotMult, LotDecimal)) {
                    PendLot = true;

                    while (IsTradeContextBusy())
                        Sleep(100);

                    if (IsStopped())
                        return (-1);

                    Success = OrderDelete(OrderTicket());

                    if (Success) {
                        PendLot = false;

                        if (Debug_)
                            Print("Delete pending = Lot");
                    }
                }
            }

            return (0);
        }

        switch (ca) {
        case B:
            if (CbT == 0 && CpT == 0)
                ca = 0;

            break;
        case H:
            if (ChT == 0)
                ca = 0;

            break;
        case A:
            if (CbT == 0 && CpT == 0 && ChT == 0)
                ca = 0;

            break;
        case P:
            if (CpT == 0)
                ca = 0;

            break;
        case T:
            break;
        default:
            break;
        }

        if (ca > 0) {
            ExitTrades(ca, displayColorLoss, "Close All (" + DTS(ca, 0) + ")");

            return (0);
        } else if (CbT == 0 && ChT > 0) {
            ExitTrades(H, displayColorLoss, "Basket Closed");

            return (0);
        } else if (EmergencyCloseAll_) {
            ExitTrades(A, displayColorLoss, "Emergency Close-All-Trades");
            EmergencyCloseAll_ = false;

            return (0);
        }

        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;
                LabelDelete();
                LabelCreate();

                if (PlaySounds)
                    PlaySound(AlertSound);
            }

            if (HolShutDown == 3) {
                if (ObjectFind("B3LStop") == -1)
                    CreateLabel("B3LStop", "Trading has been paused on this pair for the holidays.", 10, 0, 0, 3, displayColorLoss);

                if (ObjectFind("B3LResm") == -1)
                    CreateLabel("B3LResm", "Trading will resume trading after " + TimeToStr(HolLast, TIME_DATE) + ".", 10, 0, 0, 9, displayColorLoss);

                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;

            if (HolShutDown == 1 && CbT == 0) {
                Print("Trading has been paused for holidays (", TimeToStr(HolFirst, TIME_DATE), " - ", TimeToStr(HolLast, TIME_DATE), ")");

                if (CpT > 0) {
                    int Index = ExitTrades(P, displayColorLoss, "Holiday Shutdown");

                    if (Index == CpT)
                        ca = 0;
                }

                HolShutDown = 2;
                ObjDel("B3LClos");
            } else if (HolShutDown == 1) {
                if (ObjectFind("B3LClos") == -1)
                    CreateLabel("B3LClos", "", 5, 0, 0, 23, displayColorLoss);

                ObjSetTxt("B3LClos", "Trading will pause for holidays when this basket closes", 5);
            }

            if (HolShutDown == 2) {
                LabelDelete();

                if (PlaySounds)
                    PlaySound(AlertSound);

                HolShutDown = 3;
            }

            if (HolShutDown == 3) {
                if (ObjectFind("B3LStop") == -1)
                    CreateLabel("B3LStop", "Trading has been paused on this pair due to holidays.", 10, 0, 0, 3, displayColorLoss);

                if (ObjectFind("B3LResm") == -1)
                    CreateLabel("B3LResm", "Trading will resume after " + TimeToStr(HolLast, TIME_DATE) + ".", 10, 0, 0, 9, displayColorLoss);

                return (0);
            }
        }

        if (SetPOSL) {
            if (UsePowerOutSL && POSLPips_ > 0) {
                double POSL = MathMin(PortionBalance * (MaxDDPercent + 1) / 100 / PipVal2 / LbT, POSLPips_);
                SLbB = ND(BEb - POSL, Digits);
                SLbS = ND(BEb + POSL, Digits);
            } else {
                SLbB = 0;
                SLbS = 0;
            }

            for (int Order = 0; Order < OrdersTotal(); Order++) {
                if (!OrderSelect(Order, SELECT_BY_POS, MODE_TRADES))
                    continue;

                if (OrderMagicNumber() != Magic || OrderSymbol() != Symbol() || OrderType() > OP_SELL)
                    continue;

                if (OrderType() == OP_BUY && OrderStopLoss() != SLbB) {
                    Success = ModifyOrder(OrderOpenPrice(), SLbB, Purple);

                    if (Debug_ && Success)
                        Print("Order ", OrderTicket(), ": Sync POSL Buy");
                } else if (OrderType() == OP_SELL && OrderStopLoss() != SLbS) {
                    Success = ModifyOrder(OrderOpenPrice(), SLbS, Purple);

                    if (Debug_ && Success)
                        Print("Order ", OrderTicket(), ": Sync POSL Sell");
                }
            }
        }

        if (MAEntry_ > 0 && CbT == 0 && CpT < 2) {
            if (BID > ima_0 + MADistance_ && (!B3Traditional || (B3Traditional && Trend != 2))) {
                if (MAEntry_ == 1) {
                    if (ForceMarketCond_ != 1 && (UseAnyEntry || IndEntry == 0 || (!UseAnyEntry && IndEntry > 0 && BuyMe)))
                        BuyMe = true;
                    else
                        BuyMe = false;

                    if (!UseAnyEntry && IndEntry > 0 && SellMe && (!B3Traditional || (B3Traditional && Trend != 2)))
                        SellMe = false;
                } else if (MAEntry_ == 2) {
                    if (ForceMarketCond_ != 0 && (UseAnyEntry || IndEntry == 0 || (!UseAnyEntry && IndEntry > 0 && SellMe)))
                        SellMe = true;
                    else
                        SellMe = false;

                    if (!UseAnyEntry && IndEntry > 0 && BuyMe && (!B3Traditional || (B3Traditional && Trend != 2)))
                        BuyMe = false;
                }
            } else if (ASK < ima_0 - MADistance_ && (!B3Traditional || (B3Traditional && Trend != 2))) {
                if (MAEntry_ == 1) {
                    if (ForceMarketCond_ != 0 && (UseAnyEntry || IndEntry == 0 || (!UseAnyEntry && IndEntry > 0 && SellMe)))
                        SellMe = true;
                    else
                        SellMe = false;

                    if (!UseAnyEntry && IndEntry > 0 && BuyMe && (!B3Traditional || (B3Traditional && Trend != 2)))
                        BuyMe = false;
                } else if (MAEntry_ == 2) {
                    if (ForceMarketCond_ != 1 && (UseAnyEntry || IndEntry == 0 || (!UseAnyEntry && IndEntry > 0 && BuyMe)))
                        BuyMe = true;
                    else
                        BuyMe = false;

                    if (!UseAnyEntry && IndEntry > 0 && SellMe && (!B3Traditional || (B3Traditional && Trend != 2)))
                        SellMe = false;
                }
            } else if (B3Traditional && Trend == 2) {
                if (ForceMarketCond_ != 1 && (UseAnyEntry || IndEntry == 0 || (!UseAnyEntry && IndEntry > 0 && BuyMe)))
                    BuyMe = true;

                if (ForceMarketCond_ != 0 && (UseAnyEntry || IndEntry == 0 || (!UseAnyEntry && IndEntry > 0 && SellMe)))
                    SellMe = true;
            } else {
                BuyMe = false;
                SellMe = false;
            }

            if (IndEntry > 0)
                IndicatorUsed = IndicatorUsed + UAE;

            IndEntry++;
            IndicatorUsed = IndicatorUsed + " MA ";
        }

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

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

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

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

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

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

Стоимость полного кода
8 788₽ ≈ $107.42