Navigation:Home > Content >

Blessing_3_v3.9.6.07.mq4

Time: 2017-09-18 | Download file:Blessing_3_v3.9.6.07.mq4

//+---------------------------------------------------------------------+
//|                                                Blessing 3 v3.9.6.07 |
//|                                                     August 06, 2013 |
//|                     Copyright © 2007-2011, J Talon LLC/FiFtHeLeMeNt |
//|     In no event will authors be liable for any damages whatsoever.  |
//|                         Use at your own risk.                       |
//|                                                                     |
//|  This EA is dedicated to Mike McKeough, a member of the Blessing    |
//|  Development Group, who passed away on Saturday, 31st July 2010.    |
//|  His contributions to the development of this EA have helped make   |
//|  it what it is today, and we will miss his enthusiasm, dedication   |
//|  and desire to make this the best EA possible.                      |
//|  Rest In Peace.                                                     |
//+---------------------------------------------------------------------+

#property copyright "Copyright © 2007-2011, J Talon LLC/FiFtHeLeMeNt"
#property link      "http://www.jtatoday.com"
#property link      "http://www.jtatoday.info/forum/index.php"

#include 
#include 
#include 

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

//+-----------------------------------------------------------------+
//| External Parameters Set                                         |
//+-----------------------------------------------------------------+

extern string   Version.3.9.6       = "EA Settings:";
extern string   TradeComment        = "Blessing 3.9.6.07";
extern int      EANumber            = 1;        // Enter a unique number to identify this EA
extern bool     EmergencyCloseAll   = false;    // Setting this to true will close all open orders immediately

extern string   LabelAcc            = "Account Trading Settings:";
extern bool     ShutDown            = false;    // Setting this to true will stop the EA trading after any open trades have been closed
extern double   StopTradePercent    = 10;       // percent of account balance lost before trading stops
extern bool     NanoAccount         = false;    // set to true for nano "penny a pip" account (contract size is $10,000)
extern double   PortionPC           = 100;      // Percentage of account you want to trade on this pair
extern double   MaxDDPercent        = 50;       // Percent of portion for max drawdown level.
extern double   MaxSpread           = 5;        // Maximum allowed spread while placing trades
extern bool     UseHolidayShutdown  = true;     // Will shutdown over holiday period
extern string   Holidays            = "18/12-01/01"; // List of holidays, each seperated by a comma, [day]/[mth]-[day]/[mth], dates inclusive
extern bool     PlaySounds          = false;    // will sound alarms
extern string   AlertSound          = "Alert.wav";  // Alarm sound to be played

extern string   LabelIES            = "Indicator / Entry Settings:";
extern bool     B3Traditional       = true;     // Stop/Limits for entry if true, Buys/Sells if false
extern int      ForceMarketCond     = 3;        // Market condition 0=uptrend 1=downtrend 2=range 3=off
extern bool     UseAnyEntry         = false;    // true = ANY entry can be used to open orders, false = ALL entries used to open orders
extern int      MAEntry             = 1;        // 0 = Off, 1 = will base entry on MA channel, 2 = will trade in reverse
extern int      CCIEntry            = 0;        // 0 = Off, 1 = will base entry on CCI indicator, 2 = will trade in reverse
extern int      BollingerEntry      = 0;        // 0 = Off, 1 = will base entry on BB, 2 = will trade in reverse
extern int      StochEntry          = 0;        // 0 = Off, 1 = will base entry on Stoch, 2 = will trade in reverse
extern int      MACDEntry           = 0;        // 0 = Off, 1 = will base entry on MACD, 2 = will trade in reverse

extern string   LabelLS             = "Lot Size Settings:";
extern bool     UseMM               = true;    // Money Management
extern double   LAF                 = 0.5;      // Adjusts MM base lot for large accounts
extern double   Lot                 = 0.01;     // Starting lots if Money Management is off
extern double   Multiplier          = 1.4;      // Multiplier on each level

extern string   LabelGS             = "Grid Settings:";
extern bool     AutoCal             = false;    // Auto calculation of TakeProfit and Grid size;
extern string   LabelATRTFr         = "0:Chart, 1:M1, 2:M5, 3:M15, 4:M30, 5:H1, 6:H4, 7:D1, 8:W1, 9:MN1";
extern int      ATRTF               = 0;        // TimeFrame for ATR calculation
extern int      ATRPeriods          = 21;       // Number of periods for the ATR calculation
extern double   GAF                 = 1.0;      // Widens/Squishes Grid on increments/decrements of .1
extern int      EntryDelay          = 2400;     // Time Grid in seconds, to avoid opening of lots of levels in fast market
extern double   EntryOffset         = 5;        // In pips, used in conjunction with logic to offset first trade entry
extern bool     UseSmartGrid        = true;     // True = use RSI/MA calculation for next grid order

extern string   LabelTS             = "Trading Settings:";
extern int      MaxTrades           = 15;       // Maximum number of trades to place (stops placing orders when reaches MaxTrades)
extern int      BreakEvenTrade      = 12;       // Close All level, when reaches this level, doesn't wait for TP to be hit
extern double   BEPlusPips          = 2;        // Pips added to Break Even Point before BE closure
extern bool     UseCloseOldest      = false;    // True = will close the oldest open trade after CloseTradesLevel is reached
extern int      CloseTradesLevel    = 5;        // will start closing oldest open trade at this level
extern bool     ForceCloseOldest    = true;     // Will close the oldest trade whether it has potential profit or not
extern int      MaxCloseTrades      = 4;        // Maximum number of oldest trades to close
extern double   CloseTPPips         = 10;       // After Oldest Trades have closed, Forces Take Profit to BE +/- xx Pips
extern double   ForceTPPips         = 0;        // Force Take Profit to BE +/- xx Pips
extern double   MinTPPips           = 0;        // Ensure Take Profit is at least BE +/- xx Pips

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

extern string   LabelES             = "Exit Settings:";
extern bool     MaximizeProfit      = false;    // Turns on TP move and Profit Trailing Stop Feature
extern double   ProfitSet           = 70;       // Locks in Profit at this percent of Total Profit Potential
extern double   MoveTP              = 30;       // Moves TP this amount in pips
extern int      TotalMoves          = 2;        // Number of times you want TP to move before stopping movement
extern bool     UseStopLoss         = false;    // Use Stop Loss and/or Trailing Stop Loss
extern double   SLPips              = 30;       // Pips for fixed StopLoss from BE, 0=off
extern double   TSLPips             = 10;       // Pips for trailing stop loss from BE + TSLPips: +ve = fixed trail; -ve = reducing trail; 0=off
extern double   TSLPipsMin          = 3;        // Minimum trailing stop pips if using reducing TS
extern bool     UsePowerOutSL       = false;    // Transmits a SL in case of internet loss
extern double   POSLPips            = 600;      // Power Out Stop Loss in pips
extern bool     UseFIFO             = false;    // 

extern string   LabelEE             = "Early Exit Settings:";
extern bool     UseEarlyExit        = false;    // Reduces ProfitTarget by a percentage over time and number of levels open
extern double   EEStartHours        = 3;        // Number of Hours to wait before EE over time starts
extern bool     EEFirstTrade        = true;     // true = StartHours from FIRST trade: false = StartHours from LAST trade
extern double   EEHoursPC           = 0.5;      // Percentage reduction per hour (0 = OFF)
extern int      EEStartLevel        = 5;        // Number of Open Trades before EE over levels starts
extern double   EELevelPC           = 10;       // Percentage reduction at each level (0 = OFF)
extern bool     EEAllowLoss         = false;    // true = Will allow the basket to close at a loss : false = Minimum profit is Break Even

extern string   LabelAdv            = "Advanced Settings Change sparingly";

extern string   LabelGrid           = "Grid Size Settings:";
extern string   SetCountArray       = "4,4";    // Specifies number of open trades in each block (separated by a comma)
extern string   GridSetArray        = "25,50,100"; // Specifies number of pips away to issue limit order (separated by a comma)
extern string   TP_SetArray         = "50,100,200"; // Take profit for each block (separated by a comma)

extern string   LabelMA             = "MA Entry Settings:";
extern int      MAPeriod            = 100;      // Period of MA (H4 = 100, H1 = 400)
extern double   MADistance          = 10;       // Distance from MA to be treated as Ranging Market

extern string   LabelCCI            = "CCI Entry Settings:";
extern int      CCIPeriod           = 14;       // Period for CCI calculation

extern string   LabelBBS            = "Bollinger Bands Entry Settings:";
extern int      BollPeriod          = 10;       // Period for Bollinger
extern double   BollDistance        = 10;       // Up/Down spread
extern double   BollDeviation       = 2.0;      // Standard deviation multiplier for channel

extern string   LabelSto            = "Stochastic Entry Settings:";
extern int      BuySellStochZone    = 20;       // Determines Overbought and Oversold Zones
extern int      KPeriod             = 10;       // Stochastic KPeriod
extern int      DPeriod             = 2;        // Stochastic DPeriod
extern int      Slowing             = 2;        // Stochastic Slowing

extern string   LabelMACD           = "MACD Entry Settings:";
extern string   LabelMACDTF         = "0:Chart, 1:M1, 2:M5, 3:M15, 4:M30, 5:H1, 6:H4, 7:D1, 8:W1, 9:MN1";
extern int      MACD_TF             = 0;        // Time frame for MACD calculation
extern int      FastPeriod          = 12;       // MACD EMA Fast Period
extern int      SlowPeriod          = 26;       // MACD EMA Slow Period
extern int      SignalPeriod        = 9;        // MACD EMA Signal Period
extern int      MACDPrice           = 0;        // 0=close, 1=open, 2=high, 3=low, 4=HL/2, 5=HLC/3 6=HLCC/4

extern string   LabelSG             = "Smart Grid Settings:";
extern string   LabelSGTF           = "0:Chart, 1:M1, 2:M5, 3:M15, 4:M30, 5:H1, 6:H4, 7:D1, 8:W1, 9:MN1";
extern int      RSI_TF              = 3;        // Timeframe for RSI calculation - should be less than chart TF.
extern int      RSI_Period          = 14;       // Period for RSI calculation
extern int      RSI_Price           = 0;        // 0=close, 1=open, 2=high, 3=low, 4=HL/2, 5=HLC/3 6=HLCC/4
extern int      RSI_MA_Period       = 10;       // Period for MA of RSI calculation
extern int      RSI_MA_Method       = 0;        // 0=Simple MA, 1=Exponential MA, 2=Smoothed MA, 3=Linear Weighted MA

extern string   LabelOS             = "Other Settings:";
extern bool     RecoupClosedLoss    = true;     // true = Recoup any Hedge/CloseOldest losses: false = Use original profit target.
extern int      Level               = 7;        // Largest Assumed Basket size.  Lower number = higher start lots
extern int      slip                = 99;       // Adjusts opening and closing orders by "slipping" this amount
extern bool     SaveStats           = false;    // true = will save equity statistics
extern int      StatsPeriod         = 3600;     // seconds betwen stats entries - off by default
extern bool     StatsInitialise     = true;     // true for backtest - false for foward/live to ACCUMULATE equity traces

extern string   LabelUE             = "Email Settings:";
extern bool     UseEmail            = false;
extern string   LabelEDD            = "At what DD% would you like Email warnings (Max: 49, Disable: 0)?";
extern double   EmailDD1            = 20;
extern double   EmailDD2            = 30;
extern double   EmailDD3            = 40;
extern string   LabelEH             = "Number of hours before DD timer resets";
extern double   EmailHours          = 24;       // Minimum number of hours between emails

extern string   LabelDisplay        = "Used to Adjust Overlay";
extern bool     displayOverlay      = true;     // Turns the display on and off
extern bool     displayLogo         = true;     // Turns off copyright and icon
extern bool     displayCCI          = true;     // Turns off the CCI display
extern bool     displayLines        = true;     // Show BE, TP and TS lines
extern int      displayXcord        = 100;      // Moves display left and right
extern int      displayYcord        = 22;       // Moves display up and down
extern int      displayCCIxCord     = 10;       // Moves CCI display left and right
extern string   displayFont         = "Arial Bold";//Display font
extern int      displayFontSize     = 9;        // Changes size of display characters
extern int      displaySpacing      = 14;       // Changes space between lines
extern double   displayRatio        = 1;        // Ratio to increase label width spacing
extern color    displayColor        = DeepSkyBlue; // default color of display characters
extern color    displayColorProfit  = Green;    // default color of profit display characters
extern color    displayColorLoss    = Red;      // default color of loss display characters
extern color    displayColorFGnd    = White;    // default color of ForeGround Text display characters

extern bool     Debug               = false;

extern string   LabelOpt            = "These values can only be used while optimizing";
extern bool     UseGridOpt          = false;    // Set to true if you want to be able to optimize the grid settings.
extern int      SetArray1           = 4;        // These values will replace the normal SetCountArray,
extern int      SetArray2           = 4;        // GridSetArray and TP_SetArray during optimization.
extern int      SetArray3           = 0;        // The default values are the same as the normal array defaults
extern int      SetArray4           = 0;
extern int      GridArray1          = 25;       // REMEMBER:
extern int      GridArray2          = 50;       // There must be one more value for GridArray and TPArray
extern int      GridArray3          = 100;      // than there is for SetArray
extern int      GridArray4          = 0;
extern int      GridArray5          = 0;
extern int      TPArray1            = 50;
extern int      TPArray2            = 100;
extern int      TPArray3            = 200;
extern int      TPArray4            = 0;
extern int      TPArray5            = 0;

//+-----------------------------------------------------------------+
//| Internal Parameters Set                                         |
//+-----------------------------------------------------------------+
int         ca;
int         Magic,hMagic;
int         CbT,CpT,ChT;
double      Pip,hPip;
int         POSLCount;
double      SLbL;
int         Moves;
double      MaxDD;
double      SLb;
int         AccountType;
double      StopTradeBalance;
double      InitialAB;
bool        Testing,Visual;
bool        AllowTrading;
bool        EmergencyWarning;
double      MaxDDPer;
int         Error,y;
int         Set1Level,Set2Level,Set3Level,Set4Level;
int         EmailCount;
string      sTF;
datetime    EmailSent;
int         GridArray[,2];
double      Lots[],MinLotSize,LotStep,LotDecimal;
int         LotMult,MinMult;
bool        PendLot;
string      CS,UAE;
int         HolShutDown;
datetime    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      EETime,PbC,PhC,hDDStart,PbMax,PbMin,PhMax,PhMin,LastClosedPL,ClosedPips,SLh,hLvlStart,StatLowEquity,StatHighEquity;
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;

//+-----------------------------------------------------------------+
//| expert initialization function                                  |
//+-----------------------------------------------------------------+
int init()
{	CS="Waiting for next tick .";      // To display comments while testing, simply use CS = .... and
	Comment(CS);                       // it will be displayed by the line at the end of the start() block.
	CS="";
	Testing=IsTesting();
	Visual=IsVisualMode();
	FirstRun=true;
	AllowTrading=true;
	if(EANumber<1)EANumber=1;
	if(Testing)EANumber=0;
	Magic=GenerateMagicNumber();
	hMagic=JenkinsHash(Magic);
	FileName="B3_"+Magic+".dat";
	if(Debug)
	{	Print("Magic Number: "+DTS(Magic,0));
		Print("Hedge Number: "+DTS(hMagic,0));
		Print("FileName: "+FileName);
	}
	Pip=Point;
	if(Digits%2==1)Pip*=10;
	if(NanoAccount)AccountType=10;
	else AccountType=1;

	MoveTP=ND(MoveTP*Pip,Digits);
	EntryOffset=ND(EntryOffset*Pip,Digits);
	MADistance=ND(MADistance*Pip,Digits);
	BollDistance=ND(BollDistance*Pip,Digits);
	POSLPips=ND(POSLPips*Pip,Digits);
	hMaxLossPips=ND(hMaxLossPips*Pip,Digits);
	hTakeProfit=ND(hTakeProfit*Pip,Digits);
	CloseTPPips=ND(CloseTPPips*Pip,Digits);
	ForceTPPips=ND(ForceTPPips*Pip,Digits);
	MinTPPips=ND(MinTPPips*Pip,Digits);
	BEPlusPips=ND(BEPlusPips*Pip,Digits);
	SLPips=ND(SLPips*Pip,Digits);
	TSLPips=ND(TSLPips*Pip,Digits);
	TSLPipsMin=ND(TSLPipsMin*Pip,Digits);
	slip*=Pip/Point;

	if(UseHedge)
	{	if(HedgeSymbol=="")HedgeSymbol=Symbol();
		if(HedgeSymbol==Symbol())hThisChart=true;
		else hThisChart=false;
		hPip=MarketInfo(HedgeSymbol,MODE_POINT);
		int hDigits=MarketInfo(HedgeSymbol,MODE_DIGITS);
		if(hDigits%2==1)hPip*=10;
		if(CheckCorr()>0.9||hThisChart)hPosCorr=true;
		else if(CheckCorr()<-0.9)hPosCorr=false;
		else
		{	AllowTrading=false;
			UseHedge=false;
			Print("The Hedge Symbol you have entered ("+HedgeSymbol+") is not closely correlated to "+Symbol());
		}
		if(StringSubstr(DDorLevel,0,1)=="D"||StringSubstr(DDorLevel,0,1)=="d")HedgeTypeDD=true;
		else if(StringSubstr(DDorLevel,0,1)=="L"||StringSubstr(DDorLevel,0,1)=="l")HedgeTypeDD=false;
		else UseHedge=false;
		if(HedgeTypeDD)
		{	HedgeStart/=100;
			hDDStart=HedgeStart;
		}
	}
	StopTradePercent/=100;
	ProfitSet/=100;
	EEHoursPC/=100;
	EELevelPC/=100;
	hReEntryPC/=100;
	PortionPC/=100;

	InitialAB=AccountBalance();
	StopTradeBalance=InitialAB*(1-StopTradePercent);
	if(Testing)ID="B3Test.";
	else ID=DTS(Magic,0)+".";
	HideTestIndicators(true);

	MinLotSize=MarketInfo(Symbol(),MODE_MINLOT);
	if(MinLotSize>Lot)
	{	Print("Lot is less than your brokers minimum lot size");
		AllowTrading=false;
	}
	LotStep=MarketInfo(Symbol(),MODE_LOTSTEP);
	double MinLot=MathMin(MinLotSize,LotStep);
	LotMult=ND(MathMax(Lot,MinLotSize)/MinLot,0);
	MinMult=LotMult;
	Lot=MinLot;
	if(MinLot<0.01)LotDecimal=3;
	else if(MinLot<0.1)LotDecimal=2;
	else if(MinLot<1)LotDecimal=1;
	else LotDecimal=0;
	FileHandle=FileOpen(FileName,FILE_BIN|FILE_READ);
	if(FileHandle!=-1)
	{	TbF=FileReadInteger(FileHandle,LONG_VALUE);
		FileClose(FileHandle);
		Error=GetLastError();
		if(OrderSelect(TbF,SELECT_BY_TICKET))
		{	OTbF=OrderOpenTime();
			LbF=OrderLots();
			LotMult=MathMax(1,LbF/MinLot);
			PbC=FindClosedPL(B);
			PhC=FindClosedPL(H);
			TradesOpen=true;
			if(Debug)Print(FileName+" File Read: "+TbF+" Lots: "+DTS(LbF,LotDecimal));
		}
		else
		{	FileDelete(FileName);
			TbF=0;
			OTbF=0;
			LbF=0;
			Error=GetLastError();
			if(Error==ERR_NO_ERROR)
			{	if(Debug)Print(FileName+" File Deleted");
			}
			else Print("Error deleting file: "+FileName+" "+Error+" "+ErrorDescription(Error));
		}
	}
	GlobalVariableSet(ID+"LotMult",LotMult);
	if(Debug)Print("Lot Decimal: "+DTS(LotDecimal,0));
	EmergencyWarning=EmergencyCloseAll;

	if(IsOptimization())Debug=false;
	if(UseAnyEntry)UAE="||";
	else UAE="&&";
	if(ForceMarketCond<0||ForceMarketCond>3)ForceMarketCond=3;
	if(MAEntry<0||MAEntry>2)MAEntry=0;
	if(CCIEntry<0||CCIEntry>2)CCIEntry=0;
	if(BollingerEntry<0||BollingerEntry>2)BollingerEntry=0;
	if(StochEntry<0||StochEntry>2)StochEntry=0;
	if(MACDEntry<0||MACDEntry>2)MACDEntry=0;
	if(MaxCloseTrades==0)MaxCloseTrades=MaxTrades;

	ArrayResize(Digit,6);
	for(y=0;y0)Digit[y,0]=MathPow(10,y);
		Digit[y,1]=y;
		if(Debug)Print("Digit: "+y+" ["+Digit[y,0]+","+Digit[y,1]+"]");
	}
	LabelCreate();
	dLabels=false;

	//+-----------------------------------------------------------------+
	//| Set Lot Array                                                   |
	//+-----------------------------------------------------------------+
	ArrayResize(Lots,MaxTrades);
	if(Debug)Print("Lot Multiplier: "+LotMult);
	for(y=0;y0)
			{	SetCountArray=DTS(SetArray1,0);
				GridSetArray=DTS(GridArray1,0);
				TP_SetArray=DTS(TPArray1,0);
			}
			if(SetArray2>0||(SetArray1>0&&GridArray2>0))
			{	if(SetArray2>0)SetCountArray=SetCountArray+","+DTS(SetArray2,0);
				GridSetArray=GridSetArray+","+DTS(GridArray2,0);
				TP_SetArray=TP_SetArray+","+DTS(TPArray2,0);
			}
			if(SetArray3>0||(SetArray2>0&&GridArray3>0))
			{	if(SetArray3>0)SetCountArray=SetCountArray+","+DTS(SetArray3,0);
				GridSetArray=GridSetArray+","+DTS(GridArray3,0);
				TP_SetArray=TP_SetArray+","+DTS(TPArray3,0);
			}
			if(SetArray4>0||(SetArray3>0&&GridArray4>0))
			{	if(SetArray4>0)SetCountArray=SetCountArray+","+DTS(SetArray4,0);
				GridSetArray=GridSetArray+","+DTS(GridArray4,0);
				TP_SetArray=TP_SetArray+","+DTS(TPArray4,0);
			}
			if(SetArray4>0&&GridArray5>0)
			{	GridSetArray=GridSetArray+","+DTS(GridArray5,0);
				TP_SetArray=TP_SetArray+","+DTS(TPArray5,0);
			}
		}
		while(GridIndex0)
			{	SetCountArray=StringSubstr(SetCountArray,StringFind(SetCountArray,",")+1);
				GridTemp=StrToInteger(StringSubstr(GridSetArray,0,StringFind(GridSetArray,",")));
				GridSetArray=StringSubstr(GridSetArray,StringFind(GridSetArray,",")+1);
				GridTP=StrToInteger(StringSubstr(TP_SetArray,0,StringFind(TP_SetArray,",")));
				TP_SetArray=StringSubstr(TP_SetArray,StringFind(TP_SetArray,",")+1);
			}
			else GridSet=MaxTrades;
			if(GridTemp==0||GridTP==0)
			{	GridError=2;
				break;
			}
			for(GridLevel=GridIndex;GridLevel<=MathMin(GridIndex+GridSet-1,MaxTrades-1);GridLevel++)
			{	GridArray[GridLevel,0]=GridTemp;
				GridArray[GridLevel,1]=GridTP;
				if(Debug)Print("GridArray "+(GridLevel+1)+"  : ["+GridArray[GridLevel,0]+","+GridArray[GridLevel,1]+"]");
			}
			GridIndex=GridLevel;
		}
		if(GridError>0||GridArray[0,0]==0||GridArray[0,1]==0)
		{	if(GridError==1)Print("Grid Array Error. Each value should be separated by a comma.");
			else Print("Grid Array Error. Check that there is one more 'Grid' and 'TP' number than there are 'Set' numbers, separated by commas.");
			AllowTrading=false;
		}
	}
	else
	{	while(GridIndex<4)
		{	GridSet=StrToInteger(StringSubstr(SetCountArray,0,StringFind(SetCountArray,",")));
			SetCountArray=StringSubstr(SetCountArray,StringFind(SetCountArray,DTS(GridSet,0))+2);
			if(GridIndex==0&&GridSet<1)
			{	GridError=1;
				break;
			}
			if(GridSet>0)GridLevel+=GridSet;
			else if(GridLevelStart2)
				{	Temp0=HolArray[Item1,0];
					Temp1=HolArray[Item1,1];
					Temp2=HolArray[Item1,2];
					Temp3=HolArray[Item1,3];
					HolArray[Item1,0]=HolArray[HolTemp,0];
					HolArray[Item1,1]=HolArray[HolTemp,1];
					HolArray[Item1,2]=HolArray[HolTemp,2];
					HolArray[Item1,3]=HolArray[HolTemp,3];
					HolArray[HolTemp,0]=Temp0;
					HolArray[HolTemp,1]=Temp1;
					HolArray[HolTemp,2]=Temp2;
					HolArray[HolTemp,3]=Temp3;
				}
			}
		}
		if(Debug)
		{	for(HolTemp=0;HolTemp0)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);
}

//+-----------------------------------------------------------------+
//| expert start function                                           |
//+-----------------------------------------------------------------+
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  LbT          =0;     // total lots out
	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,BCh,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,OPhO;           // last open price
	int     OTbL;                // last open time
	double  g2,tp2,Entry,RSI_MA,LhB,LhS,LhT,OPbO,OTbO,OThO,TbO,ThO;
	int     Ticket,ChB,ChS,IndEntry;
	double  Pb,Ph,PaC,PbPips,PbTarget,DrawDownPC,BEb,BEh,BEa;
	bool    BuyMe,SellMe,Success,SetPOSL;
	string  IndicatorUsed;

	//+-----------------------------------------------------------------+
	//| Count Open Orders, Lots and Totals                              |
	//+-----------------------------------------------------------------+
	PipVal2=MarketInfo(Symbol(),MODE_TICKVALUE)/MarketInfo(Symbol(),MODE_TICKSIZE);
	PipValue=PipVal2*Pip;
	StopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
	ASK=ND(MarketInfo(Symbol(),MODE_ASK),MarketInfo(Symbol(),MODE_DIGITS));
	BID=ND(MarketInfo(Symbol(),MODE_BID),MarketInfo(Symbol(),MODE_DIGITS));
	if(ASK==0||BID==0)return;
	for(y=0;y0)ModifyOrder(OrderOpenPrice(),OrderStopLoss());
		if(Type<=OP_SELL)
		{	Pb+=OrderProfit();
			BCb+=OrderSwap()+OrderCommission();
			BEb+=OrderLots()*OrderOpenPrice();
			if(OrderOpenTime()>=OTbL)
			{	OTbL=OrderOpenTime();
				OPbL=OrderOpenPrice();
			}
			if(OrderOpenTime()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;

	//+-----------------------------------------------------------------+
	//| Calculate Min/Max Profit and Break Even Points                  |
	//+-----------------------------------------------------------------+
	if(LbT>0)
	{	BEb=ND(BEb/LbT,Digits);
		if(BCa<0)BEb-=ND(BCa/PipVal2/(LbB-LbS),Digits);
		if(Pb>PbMax||PbMax==0)PbMax=Pb;
		if(Pb-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=0;
		EmailSent=0;
		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 deleting file: "+FileName+" "+Error+" "+ErrorDescription(Error));
		}
		else TradesOpen=false;
	}
	if(LhT>0)
	{	BEh=ND(BEh/LhT,Digits);
		if(Ph>PhMax||PhMax==0)PhMax=Ph;
		if(Ph0)
		{	ExitTrades(P,displayColorLoss,"Blessing is shutting down");
			return;
		}
		if(AllowTrading)
		{	Print("Blessing has ShutDown. Set ShutDown = 'false' to continue trading");
			if(PlaySounds)PlaySound(AlertSound);
			AllowTrading=false;
		}
		if(UseEmail&&EmailCount<4&&!Testing)
		{	SendMail("Blessing EA","Blessing has shut down on "+Symbol()+" "+sTF+
					". Trading has been suspended. To resume trading, set ShutDown to false.");
			Error=GetLastError();
			if(Error>0)Print("Error sending Email: "+Error+" "+ErrorDescription(Error));
			else EmailCount=4;
		}
	}
	if(!AllowTrading)
	{	static bool LDelete;
		if(!LDelete)
		{	LDelete=true;
			LabelDelete();
			if(ObjectFind("B3LStop")==-1)CreateLabel("B3LStop","Trading has been stopped on this pair.",10,0,0,3,displayColorLoss);
			if(Testing)string Tab="Tester Journal";
			else Tab="Terminal Experts";
			if(ObjectFind("B3LExpt")==-1)CreateLabel("B3LExpt","Check the "+Tab+" tab for the reason why.",10,0,0,6,displayColorLoss);
			if(ObjectFind("B3LResm")==-1)CreateLabel("B3LResm","Reset Blessing to resume trading.",10,0,0,9,displayColorLoss);
		}
		return;
	}
	else
	{	LDelete=false;
		ObjDel("B3LStop");
		ObjDel("B3LExpt");
		ObjDel("B3LResm");
	}

	//+-----------------------------------------------------------------+
	//| Calculate Drawdown and Equity Protection                        |
	//+-----------------------------------------------------------------+
	double PortionBalance=ND(AccountBalance()*PortionPC,2);
	if(Pb+Ph<0)DrawDownPC=-(Pb+Ph)/PortionBalance;
	if(!FirstRun&&DrawDownPC>=MaxDDPercent/100)
	{	ExitTrades(A,displayColorLoss,"Equity Stop Loss Reached");
		if(PlaySounds)PlaySound(AlertSound);
		return;
	}
	if(-(Pb+Ph)>MaxDD)MaxDD=-(Pb+Ph);
	MaxDDPer=MathMax(MaxDDPer,DrawDownPC*100);
	if(SaveStats)Stats(false,TimeCurrent()NextISTB)
	{	InitialAB=StepAB;
		StopTradeBalance=StepSTB;
	}
	double InitialAccountMultiPortion=StopTradeBalance*PortionPC;
	if(PortionBalanceima_0+MADistance)Trend=0;
		else if(ASKima_0+MADistance)ATrend="U";
		if(Trend!=1&&ASKima_0-MADistance))ATrend="R";
	}
	//+-----------------------------------------------------------------+
	//| Hedge/Basket/ClosedTrades Profit Management                     |
	//+-----------------------------------------------------------------+
	double Pa=Pb;
	PaC=PbC+PhC;
	if(hActive==1&&ChT==0)
	{	PhC=FindClosedPL(H);
		hActive=0;
		return;
	}
	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;
	}

	//+-----------------------------------------------------------------+
	//| Close oldest open trade after CloseTradesLevel reached          |
	//+-----------------------------------------------------------------+
	if(UseCloseOldest&&CbT>=CloseTradesLevel&&CbC0&&(ForceCloseOldest||(CbB>0&&OPbO>TPb)||(CbS>0&&OPbOSet4Level)&&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
	{	y=MathMax(MathMin(CbT+CbC,MaxTrades)-1,0);
		g2=GridArray[y,0];
		tp2=GridArray[y,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);


	//+-----------------------------------------------------------------+
	//| Money Management and Lot size coding                            |
	//+-----------------------------------------------------------------+
	if(UseMM)
	{	if(CbT>0)
		{	if(GlobalVariableCheck(ID+"LotMult"))LotMult=GlobalVariableGet(ID+"LotMult");
			if(LbF!=LotSize(Lots[0]*LotMult))
			{	LotMult=LbF/Lots[0];
				GlobalVariableSet(ID+"LotMult",LotMult);
				Print("LotMult reset to "+DTS(LotMult,0));
			}
		}
		if(CbT==0)
		{	double Contracts,Factor,Lotsize;
			Contracts=PortionBalance/10000;
			if(Multiplier<=1)Factor=Level;
			else Factor=(MathPow(Multiplier,Level)-Multiplier)/(Multiplier-1);
			Lotsize=LAF*AccountType*Contracts/(1+Factor);
			LotMult=MathMax(MathFloor(Lotsize/Lot),MinMult);
			GlobalVariableSet(ID+"LotMult",LotMult);
		}
	}
	else if(CbT==0)LotMult=MinMult;
	//+-----------------------------------------------------------------+
	//| Calculate Take Profit                                           |
	//+-----------------------------------------------------------------+
	static double BCaL,BEbL;
	double 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,BasePips;
		CaL=CbT+ChT;
		BCaL=BCa;
		BEbL=BEb;
		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+BasePips0)
			{	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;
		}
	}
	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);

	//+-----------------------------------------------------------------+
	//| Adjust BEb/TakeProfit if Hedge is active                        |
	//+-----------------------------------------------------------------+
	double hAsk=MarketInfo(HedgeSymbol,MODE_ASK);
	double hBid=MarketInfo(HedgeSymbol,MODE_BID);
	double hSpread=hAsk-hBid;
	if(hThisChart)nLots+=LhB-LhS;
	if(hActive==1)
	{	double TPa,PhPips;
		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);
			}
		}
		else
		{
		}
		if(ChB>0)PhPips=ND((hBid-BEh)/hPip,1);
		if(ChS>0)PhPips=ND((BEh-hAsk)/hPip,1);
	}
	else
	{	BEa=BEb;
		TPa=TPb;
	}
	//+-----------------------------------------------------------------+
	//| Calculate Early Exit Percentage                                 |
	//+-----------------------------------------------------------------+
	if(UseEarlyExit&&CbT>0)
	{	double EEpc,EEopt,EEStartTime,TPaF;
		if(EEFirstTrade)EEopt=OTbF;
		else EEopt=OTbL;
		if(DayOfWeek()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*36000&&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);
			}
			if(EEHoursPC>0)ObjectMove("B3LEELn",0,MathFloor(EEopt/3600+EEStartHours)*3600,TPa);
			else ObjectMove("B3LEELn",0,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);
			}
			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");
	}

	//+-----------------------------------------------------------------+
	//| Maximize Profit with Moving TP and setting Trailing Profit Stop |
	//+-----------------------------------------------------------------+
	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&&BIDSLb)))
			{	ExitTrades(A,displayColorProfit,"Profit Trailing Stop Reached ("+DTS(ProfitSet*100,2)+"%)");
				return;
			}
			if(PbTarget>0)
			{	double TPbMP=ND(BEa+(TPa-BEa)*ProfitSet,Digits);
				if((nLots>0&&BID>TPbMP)||(nLots<0&&ASK0&&SLb!=SLbL&&MoveTP>0&&TotalMoves>Moves)
			{	TPb=0;
				Moves++;
				if(Debug)Print("MoveTP");
				SLbL=SLb;
				if(PlaySounds)PlaySound(AlertSound);
				return;
			}
		}
	}
	if(!FirstRun&&TPaF>0)
	{	if((nLots>0&&BID>=TPaF)||(nLots<0&&ASK<=TPaF))
		{	ExitTrades(A,displayColorProfit,"Profit Target Reached @ "+DTS(TPaF,Digits));
			return;
		}
	}
	if(!FirstRun&&UseStopLoss)
	{	double bSL;
		if(SLPips>0)
		{	if(nLots>0)
			{	bSL=BEa-SLPips;
				if(BID<=bSL)
				{	ExitTrades(A,displayColorProfit,"Stop Loss Reached");
					return;
				}
			}
			else if(nLots<0)
			{	bSL=BEa+SLPips;
				if(ASK>=bSL)
				{	ExitTrades(A,displayColorProfit,"Stop Loss Reached");
					return;
				}
			}
		}
		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;
				}
			}
			else if(nLots<0)
			{	if(TSLPips>0&&ASK0)bTS=MathMin(bTS,ASK+TSLPips);
				   else bTS=ASK+TSLPips;
				}
				if(TSLPips<0&&ASK0&&ASK>=bTS)
				{	ExitTrades(A,displayColorProfit,"Trailing Stop Reached");
					return;
				}
			}
		}
	}

	//+-----------------------------------------------------------------+
	//| Check for and Delete hanging pending orders                     |
	//+-----------------------------------------------------------------+
	if(CbT==0&&!PendLot)
	{	PendLot=true;
		for(y=OrdersTotal()-1;y>=0;y--)
		{	if(!OrderSelect(y,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;
	}
	else if((CbT>0||(CbT==0&&CpT>0&&!B3Traditional))&&PendLot)
	{	PendLot=false;
		for(y=OrdersTotal()-1;y>=0;y--)
		{	if(!OrderSelect(y,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;
	}

	//+-----------------------------------------------------------------+
	//| Check ca, Breakeven Trades and Emergency Close All              |
	//+-----------------------------------------------------------------+
	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;
	}
	if(CbT==0&&ChT>0)
	{	ExitTrades(H,displayColorLoss,"Basket Closed");
		return;
	}
	if(EmergencyCloseAll)
	{	ExitTrades(A,displayColorLoss,"Emergency Close All Trades");
		EmergencyCloseAll=false;
		return;
	}

	//+-----------------------------------------------------------------+
	//| Check Holiday Shutdown                                          |
	//+-----------------------------------------------------------------+
	if(UseHolidayShutdown)
	{	if(HolShutDown>0&&TimeCurrent()>=HolLast&&HolLast>0)
		{	Print("Blessing has resumed after the holidays. From: "+TimeToStr(HolFirst,TIME_DATE)+" To: "+TimeToStr(HolLast,TIME_DATE));
			HolShutDown=0;
			LabelDelete();
			LabelCreate();
			if(PlaySounds)PlaySound(AlertSound);
		}
		if(HolShutDown==3)
		{	if(ObjectFind("B3LStop")==-1)
				CreateLabel("B3LStop","Trading has been stopped on this pair for the holidays.",10,0,0,3,displayColorLoss);
			if(ObjectFind("B3LResm")==-1)
				CreateLabel("B3LResm","Blessing will resume trading after "+TimeToStr(HolLast,TIME_DATE)+".",10,0,0,9,displayColorLoss);
			return;
		}
		else if((HolShutDown==0&&TimeCurrent()>=HolLast)||HolFirst==0)
		{	for(y=0;yHolLast)HolLast=StrToTime(DTS(Year()+1,0)+"."+HolArray[y,2]+"."+HolArray[y,3]+" 23:59:59");
					break;
				}
				if(TimeCurrent()HolLast)HolFirst=StrToTime(DTS(Year()-1,0)+"."+HolArray[y,0]+"."+HolArray[y,1]);
					break;
				}
				if(TimeCurrent()>HolFirst&&HolFirst>HolLast)
				{	HolLast=StrToTime(DTS(Year()+1,0)+"."+HolArray[y,2]+"."+HolArray[y,3]+" 23:59:59");
					if(TimeCurrent()=HolFirst&&TimeCurrent()<=HolLast)
			{	Comment("");
				HolShutDown=1;
			}
		}
		else if(HolShutDown==0&&TimeCurrent()>=HolFirst&&TimeCurrent()0)
			{	y=ExitTrades(P,displayColorLoss,"Holiday Shutdown");
				if(y==CpT)ca=0;
			}
			HolShutDown=2;
			ObjDel("B3LClos");
		}
		else if(HolShutDown==1)
		{	if(ObjectFind("B3LClos")==-1)CreateLabel("B3LClos","",5,0,0,23,displayColorLoss);
			ObjSetTxt("B3LClos","Blessing will shutdown for the 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 stopped on this pair for the holidays.",10,0,0,3,displayColorLoss);
			if(ObjectFind("B3LResm")==-1)
				CreateLabel("B3LResm","Blessing will resume trading after "+TimeToStr(HolLast,TIME_DATE)+".",10,0,0,9,displayColorLoss);
			Comment("");
			return;
		}
	}

	//+-----------------------------------------------------------------+
	//| Power Out Stop Loss Protection                                  |
	//+-----------------------------------------------------------------+
	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(y=0;yOP_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");
			}
		}
	}

	//+-----------------------------------------------------------------+  << This must be the first Entry check.
	//| Moving Average Indicator for Order Entry                        |  << Add your own Indicator Entry checks
	//+-----------------------------------------------------------------+  << after the Moving Average Entry.
	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(ASK0&&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 ";
	}

	//+----------------------------------------------------------------+
	//| CCI of 5M,15M,30M,1H for Market Condition and Order Entry      |
	//+----------------------------------------------------------------+
	if(CCIEntry>0)
	{	double cci_01=iCCI(Symbol(),PERIOD_M5,CCIPeriod,PRICE_CLOSE,0);
		double cci_02=iCCI(Symbol(),PERIOD_M15,CCIPeriod,PRICE_CLOSE,0);
		double cci_03=iCCI(Symbol(),PERIOD_M30,CCIPeriod,PRICE_CLOSE,0);
		double cci_04=iCCI(Symbol(),PERIOD_H1,CCIPeriod,PRICE_CLOSE,0);
		double cci_11=iCCI(Symbol(),PERIOD_M5,CCIPeriod,PRICE_CLOSE,1);
		double cci_12=iCCI(Symbol(),PERIOD_M15,CCIPeriod,PRICE_CLOSE,1);
		double cci_13=iCCI(Symbol(),PERIOD_M30,CCIPeriod,PRICE_CLOSE,1);
		double cci_14=iCCI(Symbol(),PERIOD_H1,CCIPeriod,PRICE_CLOSE,1);
	}
	if(CCIEntry>0&&CbT==0&&CpT<2)
	{	if(cci_11>0&&cci_12>0&&cci_13>0&&cci_14>0&&cci_01>0&&cci_02>0&&cci_03>0&&cci_04>0)
		{	if(ForceMarketCond==3)Trend=0;
			if(CCIEntry==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(CCIEntry==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(cci_11<0&&cci_12<0&&cci_13<0&&cci_14<0&&cci_01<0&&cci_02<0&&cci_03<0&&cci_04<0)
		{	if(ForceMarketCond==3)Trend=1;
			if(CCIEntry==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(CCIEntry==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(!UseAnyEntry&&IndEntry>0)
		{	BuyMe=false;
			SellMe=false;
		}
		if(IndEntry>0)IndicatorUsed=IndicatorUsed+UAE;
		IndEntry++;
		IndicatorUsed=IndicatorUsed+" CCI ";
	}

	//+----------------------------------------------------------------+
	//| Bollinger Band Indicator for Order Entry                       |
	//+----------------------------------------------------------------+
	if(BollingerEntry>0&&CbT==0&&CpT<2)
	{	double ma=iMA(Symbol(),0,BollPeriod,0,MODE_SMA,PRICE_OPEN,0);
		double stddev=iStdDev(Symbol(),0,BollPeriod,0,MODE_SMA,PRICE_OPEN,0);
		double bup=ma+(BollDeviation*stddev);
		double bdn=ma-(BollDeviation*stddev);
		double bux=bup+BollDistance;
		double bdx=bdn-BollDistance;
		if(ASK0&&BuyMe)))BuyMe=true;
				else BuyMe=false;
				if(!UseAnyEntry&&IndEntry>0&&SellMe&&(!B3Traditional||(B3Traditional&&Trend!=2)))SellMe=false;
			}
			else if(BollingerEntry==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(BID>bux)
		{	if(BollingerEntry==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(BollingerEntry==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(!UseAnyEntry&&IndEntry>0)
		{	BuyMe=false;
			SellMe=false;
		}
		if(IndEntry>0)IndicatorUsed=IndicatorUsed+UAE;
		IndEntry++;
		IndicatorUsed=IndicatorUsed+" BBands ";
	}

	//+----------------------------------------------------------------+
	//| Stochastic Indicator for Order Entry                           |
	//+----------------------------------------------------------------+
	if(StochEntry>0&&CbT==0&&CpT<2)
	{	int zoneBUY=BuySellStochZone;
		int zoneSELL=100-BuySellStochZone;
		double stoc_0=iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MODE_LWMA,1,0,1);
		double stoc_1=iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MODE_LWMA,1,1,1);
		if(stoc_00&&BuyMe)))BuyMe=true;
				else BuyMe=false;
				if(!UseAnyEntry&&IndEntry>0&&SellMe&&(!B3Traditional||(B3Traditional&&Trend!=2)))SellMe=false;
			}
			else if(StochEntry==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(stoc_0>zoneSELL&&stoc_1>zoneSELL)
		{	if(StochEntry==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(StochEntry==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(!UseAnyEntry&&IndEntry>0)
		{	BuyMe=false;
			SellMe=false;
		}
		if(IndEntry>0)IndicatorUsed=IndicatorUsed+UAE;
		IndEntry++;
		IndicatorUsed=IndicatorUsed+" Stoch ";
	}

	//+----------------------------------------------------------------+
	//| MACD Indicator for Order Entry                                 |
	//+----------------------------------------------------------------+
	if(MACDEntry>0&&CbT==0&&CpT<2)
	{	double MACDm=iMACD(NULL,TF[MACD_TF],FastPeriod,SlowPeriod,SignalPeriod,MACDPrice,0,0);
		double MACDs=iMACD(NULL,TF[MACD_TF],FastPeriod,SlowPeriod,SignalPeriod,MACDPrice,1,0);
		if(MACDm>MACDs)
		{	if(MACDEntry==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(MACDEntry==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;
			}
		}
		el        

Recommend