thesrzoneeadudestd_6xx.pdf
TRANSCRIPT
-
//find the system/updates at http://www.stevehopwoodforex.com/phpBB3/viewtopic.php?f=5&t=3343// http://www.stevehopwoodforex.com
// "Feeling generous? Help keep the coder going with a small Paypal donation to [email protected]"//Strategy by dudest
//coded by milanese, thanks to Steve Hopwood, phil_trade,SS_SupportResistance (code by Andrew Su//please do not publish this outside of http://www.stevehopwoodforex.com
#property copyright"Copyright 2014, milanese (Tommaso),Andrew Sumner(Indicator), Steve Hopwood et. al."#property link "http://SteveHopwoodForex.com"
#include
#define NL "\n"string Gap,ScreenMessage;#define version "TheSRZoneEA 0.6.7"//Slope constants#define buyonly "Buy Only. "#define sellonly "Sell Only. "#define buyhold "Buy and hold. "#define sellhold "Sell and hold. "#define rising "Angle is rising. "#define falling "Angle is falling. "#define unchanged "Angle is unchanged. "#define ranging "Slope is ranging. "#define SSSR_ZONE_WEAK 0#define SSSR_ZONE_TURNCOAT 1#define SSSR_ZONE_UNTESTED 2#define SSSR_ZONE_VERIFIED 3#define SSSR_ZONE_PROVEN 4
#define SSSR_UP 1#define SSSR_NONE 0#define SSSR_DN -1
#define SSSR_FAST 1#define SSSR_SLOW 2
#define SSSR_ZONE_SUPPORT 1#define SSSR_ZONE_RESIST 2
#define SSSR_UP_POINT 1#define SSSR_DN_POINT -1
extern string ishi="**** Indicator settings ****";
extern int PERIOD_SR=PERIOD_M30;extern int PERIOD_2CandleRule=PERIOD_H4;extern int PERIOD_ATR=PERIOD_H4;extern string slp="--TMA-SlopeSettings--";extern int HtfTimeFrame=240;//Zero to disableextern double HtfBuyOnlyLevel=0.2;extern double HtfBuyHoldLevel=0.8;double HtfBuyCloseLevel=0.3;extern double HtfSellOnlyLevel=-0.2;extern double HtfSellHoldLevel=-0.8;double HtfSellCloseLevel=-0.3;int LtfTimeFrame=0;//Zero to disabledouble LtfBuyOnlyLevel=0.4;double LtfBuyHoldLevel=0.8;double LtfBuyCloseLevel=0.3;double LtfSellOnlyLevel=-0.4;double LtfSellHoldLevel=-0.8;double LtfSellCloseLevel=-0.3;////////////////////////////////////////////////////////////////////////////////////////double HtfSlopeVal[8],LtfSlopeVal,PrevHtfSlopeVal,PrevLtfSlopeVal;
Page 1/44
-
string HtfSlopeTrend,LtfSlopeTrend,HtfSlopeAngle,LtfSlopeAngle;double SR_TP=0;
extern string gshi="**** General settings ****";
extern int MagicNumber=99;extern int slippage=1;extern double AdvertisedSpread=1.1;// Put here the avarage spread for the pair from your brokerbool UseFixedLot=true;extern double FixedLot=0.1;extern double StackLot=0.1;extern double BufferPips=45;double BufferPipsOpen=10;extern bool AddAdditionalPositionsInTrend=false;extern int MaxAdditionalPositions=0;extern double MinTPProfitInUSD=15;////////////////////////////////////////////////////////////////////////////////////////extern string pcbe="PartClose settings can be used in";extern string pcbe1="conjunction with BE/SL settings";extern int PartClosePercent=50;extern bool PartCloseWithMovingSLMain=false;extern bool PartCloseWithMovingSLStack=true;double JumpProfit=0;double JumpProfitST=0;double SetBEminPip=0;double SetBEminPipST=0;
double adr=0;
double Risk_percent=3;double LotStep,MinLot,MaxLot;
//double WeeklyPivot,DailyPivot,YesterdayPivot,TwoBeforedayPivot;double ma1[8],ma2[8],ma3[8],ma4[8];double rsi8[8];double HighValue=0;double LowValue=0;
extern bool Use_SetBEAndJump=true;extern double SecureProfit=4;extern double BeVarPercent=55;double BeVar=0;
extern double SecureProfitST=4;
extern bool UseCloseFriday=false;
int DeltaTimeHistoTrades=14400;int DeltaTimeLiveTrades=14400;bool BrokerHasSundayCandle=false;
extern double RequiredMarginPercentile=1000;
//CSS Integrationextern string CSSInput="----CCS inputs----";extern bool UseCSS=false;extern bool UseCSSForEntry=false;extern bool UseCSSForTP=false;
extern int maxBars=100;extern int CssTf=240;//Defaults to current time framestring CurrNames[8]={ "USD","EUR","GBP","CHF","JPY","AUD","CAD","NZD" };////////////////////////////////////////////////////////////////////////////////////////string Curr1,Curr2;//First and second currency in the pairint CurrIndex1,CurrIndex2;//Index of the currencies that form the pair to point to the correct one in currencyNamesdouble CurrVal1[8],CurrVal2[8];//Hold the values of the two currencies, allowing me to look back in time to see if the currency is rising or falling.string CurrDirection1,CurrDirection2;//One of the Currency ststus constantsint CSS_Allowed_Buy=1;int CSS_Allowed_Sell=1;#define upaccelerating "Up, and accelerating"#define updecelerating "Up, but slowing"
Page 2/44
-
#define downaccelerating "Down, and accelerating"#define downdecelerating "Down, but slowing"
bool zone_solid=false;int zone_linewidth=1;int zone_style=0;bool zone_show_info=true;int zone_label_shift=5;bool zone_merge=true;bool zone_extend=true;color color_support_weak = DarkSlateGray;color color_support_untested = SeaGreen;color color_support_verified = Green;color color_support_proven = LimeGreen;color color_support_turncoat = OliveDrab;color color_resist_weak = Indigo;color color_resist_untested=Orchid;color color_resist_verified = Crimson;color color_resist_proven = Red;color color_resist_turncoat = DarkOrange;
bool BuyOk=false;bool SellOk=false;
//Steve shell mandatory variablesint O_R_Setting_max_retries=10;double O_R_Setting_sleep_time=4.0; /* seconds */double O_R_Setting_sleep_max=15.0; /* seconds */int RetryCount=10;//Will make this number of attempts to get around the trade context busy error.bool BrokerIsECN=true;bool TakingEmergencyAction;int TicketNo=-1,OpenTrades;//end of Steve shell mandatory variables
bool SignalBuy=false;bool SignalSell=false;bool SignalBuyStack=false;bool SignalSellStack=false;double lot;
bool FlagCloseFriday=false;
int myHour=99;int multiplier=1;double spread=0;int myMinute=99;double CostPip=5;bool TPChangeFlag=false;int SSSR_BackLimit = 10000;
double SSSR_zone_fuzzfactor = 0.9;bool SSSR_zone_merge = true;bool SSSR_zone_extend = true;
double SSSR_zone_fastfactor = 3.0;double SSSR_zone_slowfactor = 6.0;
double SSSR_FastDnPts[], SSSR_FastUpPts[];double SSSR_SlowDnPts[], SSSR_SlowUpPts[];
double SSSR_zone_hi[1000], SSSR_zone_lo[1000];int SSSR_zone_start[1000], SSSR_zone_hits[1000], SSSR_zone_type[1000],SSSR_zone_strength[1000], SSSR_zone_count = 0;bool SSSR_zone_turn[1000];string SSSR_sym;int SSSR_TF;double res_hi=0, res_lo=0, sup_hi=0, sup_lo=0;int res_strength=0, sup_strength=0;int sup_zone, res_zone;bool UsePartCloseOnTP=true;extern bool UsingOnlyProvenZones=true;int strenght_used_r=4;int strenght_used_s=4;
Page 3/44
-
int time_offset=0;//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+int OnInit(void)
{
//Adapt to x digit Brokersif(Digits == 2 || Digits == 4) multiplier = 1;if(Digits == 3 || Digits == 5) multiplier = 10;if(Digits == 6) multiplier = 100;if(Digits == 7) multiplier = 1000;if(IsTesting()==true)
{UseCSS=false;UseCSSForEntry=false;UseCSSForTP=false;
}SSSR_UpdateZones(false, Symbol(), PERIOD_SR);// Special case for gold silver.
if((StringFind(Symbol(),"XAUUSD",0)!=-1)&&(Digits==3))multiplier = 100;if((StringFind(Symbol(),"XAUUSD",0)!=-1)&&(Digits==2))multiplier = 10;if((StringFind(Symbol(),"XAUUSD",0)!=-1)&&(Digits==1))multiplier = 1;if((StringFind(Symbol(),"XAGUSD",0)!=-1)&&(Digits==4))multiplier = 100;if((StringFind(Symbol(),"XAGUSD",0)!=-1)&&(Digits==3))multiplier = 10;if((StringFind(Symbol(),"XAGUSD",0)!=-1)&&(Digits==2))multiplier = 1;BeVarPercent=BeVarPercent/100;if(BeVarPercent==0)BeVarPercent=1;
CostPip*=multiplier;
AdvertisedSpread*=multiplier;slippage*=multiplier;BufferPips*=multiplier;BufferPipsOpen*=multiplier;
SecureProfit*=multiplier;
SecureProfitST*=multiplier;
LotStep= MarketInfo(Symbol(),MODE_LOTSTEP);MinLot = MarketInfo(Symbol(),MODE_MINLOT);MaxLot = MarketInfo(Symbol(),MODE_MAXLOT);
// Initialize libCSS
if (UsingOnlyProvenZones==true){strenght_used_r=4;strenght_used_s=4;}
else{strenght_used_r=3;strenght_used_s=3;}
return(0);}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void OnDeinit(const int reason)
{
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void OnTick()
{
Page 4/44
-
//end indi embedmyHour=TimeHour(TimeCurrent());//if (NewBar(PERIOD_SR)==true)SSSR_UpdateZones(true, Symbol(), PERIOD_SR);for(int i=0; i0 && SSSR_zone_strength[i]>SSSR_ZONE_UNTESTED){if(SSSR_zone_hits[i]==1)
lbl=lbl+", Test Count="+SSSR_zone_hits[i];else
lbl=lbl+", Test Count="+SSSR_zone_hits[i];}
int adjust_hpos;int wbpc=WindowBarsPerChart();int k;
k=Period()*60+(20+StringLen(lbl));
if(wbpc
-
BrokerHasSundayCandle=false;for(int CC=0; CC0 || CountSells(Symbol(),MagicNumber)>0)ManageOpenTrades();
if(TimeMinute(TimeCurrent())!=myMinute){
spread=MarketInfo(Symbol(),MODE_SPREAD);
if(UseFixedLot==false){lot=CalculateLots(Risk_percent);// if((StringFind(Symbol(),"XAUUSD",0)!=-1)&&(Digits==3)) lot*=0.1;if(lot
-
if(SignalBuyStack==true)if(SignalSellStack==false)
if(CheckTradeAllowedMargin()==true)if(AllowedSpread(Symbol())==true)
{tp=SR_TP;
sl=(Ask-(adr*1));BeVar=(adr*1)*BeVarPercent;Alert("Attempting to buy ",StackLot," of ",Symbol());Print("Attempting to buy ",StackLot," of ",Symbol());SendSingleTrade(Symbol(),OP_BUY,"StackTrade",StackLot,Ask,sl,tp);
}
RefreshRates();if(SignalBuyStack==false)
if(SignalSellStack==true)if(CheckTradeAllowedMargin()==true)
if(AllowedSpread(Symbol())==true){tp=SR_TP;
sl=(Bid+(adr*1));BeVar=(adr*1)*BeVarPercent;Alert("Attempting to sell ",StackLot," of ",Symbol());Print("Attempting to sell ",StackLot," of ",Symbol());SendSingleTrade(Symbol(),OP_SELL,"StackTrade",StackLot,Bid,sl,tp);
}
DisplayUserFeedback();myMinute=TimeMinute(TimeCurrent());
}
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+double CalculateLots(double risk_percent)
{int SL=300;double risk_value;
risk_value=AccountBalance()*(risk_percent/100.0)/(SL*MarketInfo(Symbol(),MODE_TICKVALUE)*Point/MarketInfo(Symbol(),MODE_TICKSIZE));
return(MathMin(MathMax(MinLot,MathRound(risk_value/LotStep)*LotStep),MaxLot));}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+datetime TimeElapsedSinceLastOpenTrade(string strSymbol,int nMagic)
{datetime timeelapsed=0;datetime opentime=0;
for(int i=OrdersTotal()-1; i>=0; i--){if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if((OrderType()==OP_BUY) || (OrderType()==OP_SELL))
if(OrderOpenTime()>opentime) opentime=OrderOpenTime();}
if(opentime==0) return(-1);//fxdaytrader, if there are no open orders yet we can return ...
timeelapsed=TimeCurrent()-opentime;
// WeekEnd case//172800 seconds = 48H
//if (DayOfTheWeek(TimeCurrent)=1) and (DayOfTheWeek(OrderOpenTime)>1) then ValeurRetour := ValeurRetour - 48;if(BrokerHasSundayCandle==true)
{
Page 7/44
-
if((TimeDayOfWeek(TimeCurrent())==0) && (TimeDayOfWeek(opentime)>0)) timeelapsed=timeelapsed-172800;
}else
{if((TimeDayOfWeek(TimeCurrent())==1) && (TimeDayOfWeek(opentime)>1)) timeelapsed=
timeelapsed-172800;}
// End Of WeekEnd case
if(timeelapsed=0; i--){if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if((OrderType()==OP_BUY) || (OrderType()==OP_SELL))
if(OrderCloseTime()>closetime) closetime=OrderCloseTime();}
if(closetime==0) return(-1);//fxdaytrader, if there are no orders in history yet, closetime is still==0, so we can return
timeelapsed=TimeCurrent()-closetime;
// WeekEnd case//172800 seconds = 48H
//if (DayOfTheWeek(TimeCurrent)=1) and (DayOfTheWeek(OrderOpenTime)>1) then ValeurRetour := ValeurRetour - 48;if(BrokerHasSundayCandle==true)
{if((TimeDayOfWeek(TimeCurrent())==0) && (TimeDayOfWeek(closetime)>0)) timeelapsed=
timeelapsed-172800;}
else{if((TimeDayOfWeek(TimeCurrent())==1) && (TimeDayOfWeek(closetime)>1)) timeelapsed=
timeelapsed-172800;}
// End Of WeekEnd case
if(timeelapsed=0; i--)
{if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if(OrderType()==OP_BUY)
nOrderCount++;}
return(nOrderCount);}
//+------------------------------------------------------------------+
Page 8/44
-
//| |//+------------------------------------------------------------------+int CountSells(string strSymbol,int nMagic)
{int nOrderCount=0;for(int i=OrdersTotal()-1; i>=0; i--)
{if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if(OrderType()==OP_SELL)
nOrderCount++;}
return(nOrderCount);}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+int CountHisto(string strSymbol,int nMagic)
{int nOrderCount=0;for(int i=OrdersHistoryTotal()-1; i>=0; i--)
{if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
if((OrderType()==OP_BUY) || (OrderType()==OP_SELL))if(OrderMagicNumber()==nMagic)
if(OrderSymbol()==strSymbol)nOrderCount++;
}return(nOrderCount);
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+double LastOpenTradePrice(string strSymbol,int nMagic)
{double priceLastOpenOrder=0;datetime opendate=0;
//for (int i=OrdersTotal()-1 ; i>=0 ; i--)for(int i=OrdersHistoryTotal()-1; i>=0; i--)
{//if (!OrderSelect(i,SELECT_BY_POS)) continue;if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;
if(OrderOpenTime()>=opendate){priceLastOpenOrder=OrderOpenPrice();opendate=OrderOpenTime();
}}
return(priceLastOpenOrder);}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+/*double CalculateTpForBuy(string strSymbol){ RefreshRates();
double tp=0; awr_value = 1.385*(iATR(NULL, PERIOD_D1, 14, 1)); tp=Ask+NormalizeDouble(awr_value,Digits);
return(tp);}double CalculateTpForSell(string strSymbol){ RefreshRates();
double tp=0;awr_value = 1.385*(iATR(NULL, PERIOD_D1, 14, 1)); tp=Bid-NormalizeDouble(awr_value,Digits);
Page 9/44
-
return(tp);}
*/bool CheckTradeAllowedMargin()
{bool allowed=true;if(IsTesting()==false)
{if((MarketInfo(Symbol(),MODE_MARGINREQUIRED)*lot)>=(AccountFreeMargin()/2))allowed=
false;if(AccountMargin()>0)
{double freemarginpercentile=(AccountEquity()/AccountMargin())*100;if(freemarginpercentile=21) && FlagCloseFriday==false)
{FlagCloseFriday=true;for(int i=OrdersTotal()-1; i>=0; i--)
{if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if(OrderType()==OP_BUY)
{ticket=OrderTicket();if(OrderProfit()>0)
if(AllowedSpread(strSymbol)==true)if(OrderOpenPrice()==ReturnLowOpenPrice(strSymbol,MagicNumber,ticket))
if(OrderLots()
-
}}
if(OrderType()==OP_SELL){ticket=OrderTicket();if(OrderProfit()>0)
if(AllowedSpread(strSymbol)==true)if(OrderOpenPrice()==ReturnHighOpenPrice(strSymbol,MagicNumber,ticket))
if(OrderLots()=0; i--)
{if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if((OrderType()==OP_BUY) || (OrderType()==OP_SELL))
if(OrderOpenPrice()>=OrderHighOpenPrice)OrderHighOpenPrice=(OrderOpenPrice()+CostPip*Point);
}if(ticket>0)OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);return(OrderHighOpenPrice);
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+double ReturnLowOpenPrice(string strSymbol,int nMagic,int ticket)
{double OrderLowOpenPrice=9999;
Page 11/44
-
for(int i=OrdersTotal()-1; i>=0; i--){if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if((OrderType()==OP_BUY) || (OrderType()==OP_SELL))
if(OrderOpenPrice()0)OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);return(OrderLowOpenPrice);
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+double GetProfitPair(string strSymbol,int nMagic,int ticket)
{double profit=0;for(int i=OrdersTotal()-1; i>=0; i--)
{if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if((OrderType()==OP_BUY) || (OrderType()==OP_SELL))
profit=profit+(OrderProfit()+OrderSwap()+OrderCommission());}
if(ticket>0)OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);//restore pointer for calling func
return(profit);}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+bool AllowedSpread(string strSymbol)
{bool IsOk=true;if(spread>AdvertisedSpread)IsOk=false;return(IsOk);
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void ManageOpenTrades()
{if(UseCloseFriday==true)CloseFriday(Symbol(),MagicNumber);
if(UseCSSForTP==true && UseCSS==true) TP_CSS(Symbol(),MagicNumber);
SetBEAndJump(Symbol(),MagicNumber);SetBEAndJumpStackTrade(Symbol(),MagicNumber);
CloseTheTradeSlope(Symbol(),MagicNumber);CloseFirstTwoAgainstUs(Symbol(),MagicNumber);
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void SetBEAndJump(string symbol,int nMagic)
{
int ticket=-1;double NewSL=0;JumpProfit=(adr/2)*BeVarPercent;SetBEminPip=(adr)*BeVarPercent;for(int i=OrdersTotal()-1; i>=0; i--)
{if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic)continue;if(OrderSymbol()!=symbol)continue;if(OrderComment()!="MainTrade")continue;
Page 12/44
-
if(OrderType()==OP_SELL){ticket=OrderTicket();
{if((OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0) && ((Ask+(BeVar))(SetBEminPip))
{if(((NewSL>OrderStopLoss()) || (OrderStopLoss()
-
void SetBEAndJumpStackTrade(string symbol,int nMagic){
int ticket=-1;double NewSL=0;JumpProfitST=(adr/2)*BeVarPercent;SetBEminPipST=(adr)*BeVarPercent;
for(int i=OrdersTotal()-1; i>=0; i--){if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic)continue;if(OrderSymbol()!=symbol)continue;if(OrderComment()!="StackTrade")continue;if(OrderType()==OP_SELL)
{ticket=OrderTicket();
{if((OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0) && ((Ask+(BeVar))(SetBEminPipST))
{if(((NewSL>OrderStopLoss()) || (OrderStopLoss()
-
{PartCloseTrade(ticket);Alert(PartClosePercent,"% of Position closed");
}}
}}
}
}return;
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void TP_CSS(string strSymbol,int nMagic)
{int ticket=-1;for(int i=OrdersTotal()-1; i>=0; i--)
{if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;if(OrderType()==OP_SELL)
{ticket=OrderTicket();if(GetProfitPair(strSymbol,nMagic,ticket)>MinTPProfitInUSD)
// if(TimeElapsedSinceLastHistoBuy(strSymbol, MagicNumber,OrderTicket())>=DeltaTimeLiveTrades)if(CurrVal1[1]>CurrVal2[1] && CurrVal1[2]>CurrVal2[2] && CurrVal1[3]>CurrVal2[3
])
if(AllowedSpread(strSymbol)==true)if(OrderLots()CurrVal1[1] && CurrVal2[2]>CurrVal1[2] && CurrVal2[3]>CurrVal1[3])
Page 15/44
-
if(GetProfitPair(strSymbol,nMagic,ticket)>MinTPProfitInUSD)
//if(TimeElapsedSinceLastHistoBuy(strSymbol, MagicNumber,OrderTicket())>=DeltaTimeLiveTrades)if(AllowedSpread(strSymbol)==true)
if(OrderLots()=0; i--){if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;
if(OrderType()==OP_SELL){ticket=OrderTicket();
shift=iBarShift(NULL,PERIOD_SR,OrderOpenTime(),false);if((shift==5 && HtfSlopeVal[0]>-0.4))
{
if(AllowedSpread(strSymbol)==true){Alert("CloseTheTrade :Attempting to close ",strSymbol);Print("CloseTheTrade :Attempting to close ",strSymbol);if(OrderClose(ticket,OrderLots(),Ask,slippage,Red))
Page 16/44
-
{Alert("CloseTheTrade :Close ",strSymbol," Succeeded !");Print("CloseTheTrade :Close ",strSymbol," Succeeded !");
}else
{Alert("CloseTheTrade :Close ",strSymbol," Failed !");Print("CloseTheTrade :Close ",strSymbol," Failed !");
}}
}
}if(OrderType()==OP_BUY)
{ticket=OrderTicket();
shift=iBarShift(NULL,PERIOD_SR,OrderOpenTime(),false);if((shift==5 && HtfSlopeVal[0]=0; i--){if(!OrderSelect(i,SELECT_BY_POS)) continue;if(OrderMagicNumber()!=nMagic) continue;if(OrderSymbol()!=strSymbol) continue;
if(OrderType()==OP_SELL){ticket=OrderTicket();
shift=iBarShift(NULL,PERIOD_2CandleRule,OrderOpenTime(),false);if(shift==2)
{
Page 17/44
-
if(iClose(NULL,PERIOD_2CandleRule,shift)>iOpen(NULL,PERIOD_2CandleRule,shift))
{if(iClose(NULL,PERIOD_2CandleRule,shift-1)>iOpen(NULL,PERIOD_2CandleRule,
shift-1)){
if(AllowedSpread(strSymbol)==true){Alert("CloseTheTrade :Attempting to close ",strSymbol);Print("CloseTheTrade :Attempting to close ",strSymbol);if(OrderClose(ticket,OrderLots(),Ask,slippage,Red))
{Alert("CloseTheTrade :Close ",strSymbol," Succeeded !");Print("CloseTheTrade :Close ",strSymbol," Succeeded !");
}else
{Alert("CloseTheTrade :Close ",strSymbol," Failed !");Print("CloseTheTrade :Close ",strSymbol," Failed !");
}}
}}
}
}if(OrderType()==OP_BUY)
{ticket=OrderTicket();shift=iBarShift(NULL,PERIOD_2CandleRule,OrderOpenTime(),false);if(shift==2)
{if(iClose(NULL,PERIOD_2CandleRule,shift)
-
if(d==1 && BrokerHasSundayCandle && Period()==1440) m_bar=m_bar+1;
adr=GetAtr(Symbol(),PERIOD_ATR,5,m_bar+1);if(UseCSS==true)
{
SplitSymbol();//Split the Symbol into its constituent currencies. Also finds their index for passing to CSS
CurrVal1[1] = GetCSS(CurrIndex1,m_bar);CurrVal2[1] = GetCSS(CurrIndex2,m_bar);
CurrVal1[2] = GetCSS(CurrIndex1,m_bar+ 1);CurrVal2[2] = GetCSS(CurrIndex2,m_bar+1);
CurrVal1[3] = GetCSS(CurrIndex1,m_bar+ 2);CurrVal2[3] = GetCSS(CurrIndex2,m_bar+ 2);}
//slope
if(HtfTimeFrame>0){HtfSlopeVal[0]= GetSlope(Symbol(),HtfTimeFrame,m_bar);HtfSlopeTrend = ranging;if(HtfSlopeVal[0] >= HtfBuyOnlyLevel) HtfSlopeTrend = buyonly;if(HtfSlopeVal[0] >= HtfBuyHoldLevel) HtfSlopeTrend = buyhold;if(HtfSlopeVal[0] 0)
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void LookForTrading()
{
ReadIndicators();
SignalBuy=false;SignalSell=false;SignalBuyStack=false;SignalSellStack=false;int res_zone_strenght=0;int sup_zone_strenght=0;double res_zone_hi=0;double res_zone_lo=0;double sup_zone_hi=0;double sup_zone_lo=0;int strenght_used=0;if (UsingOnlyProvenZones==true)strenght_used=4;else strenght_used=3;
BuyOk=0;SellOk=0;
res_zone = SSSR_FindZoneV2(SSSR_UP, true, Bid, res_hi, res_lo, res_strength);sup_zone = SSSR_FindZoneV2(SSSR_DN, true, Bid, sup_hi, sup_lo, sup_strength);
res_zone_strenght=SSSR_GetZoneStrength(res_zone);sup_zone_strenght=SSSR_GetZoneStrength(sup_zone);res_zone_hi=SSSR_GetZoneHi(res_zone);res_zone_lo=SSSR_GetZoneLo(res_zone);sup_zone_hi=SSSR_GetZoneHi(sup_zone);sup_zone_lo=SSSR_GetZoneLo(sup_zone);
if(UseCSS==true)
Page 19/44
-
{// need to reset CSS Values to yesCSS_Allowed_Sell=1;CSS_Allowed_Buy=1;
//Define direction//Currency 1if(CurrVal1[1]>0 && CurrVal1[1]>=CurrVal1[2]) CurrDirection1=upaccelerating;if(CurrVal1[1]>0 && CurrVal1[1]0 && CurrVal2[1]
-
if(CountSells(Symbol(),MagicNumber)==0 && (CountBuys(Symbol(),MagicNumber)>0 &&CountBuys(Symbol(),MagicNumber)=NormalizeDouble(res_zone_hi,Digits)) && (MathAbs(Bid-res_zone_hi)=strenght_used)
{SR_TP=res_zone_lo;
if(SR_TP>Bid-(BufferPips*Point)) SR_TP=Bid-(BufferPips*Point);SellOk=1;}
if((SellOk==1))
if(TimeElapsedSinceLastOpenTrade(Symbol(),MagicNumber)>DeltaTimeLiveTrades ||TimeElapsedSinceLastOpenTrade(Symbol(),MagicNumber)==-1)
if(TimeElapsedSinceLastHistoTrade(Symbol(),MagicNumber)>DeltaTimeHistoTrades ||TimeElapsedSinceLastHistoTrade(Symbol(),MagicNumber)==-1)
if(CSS_Allowed_Sell==1)
{
SignalSell=true;
}
}if(AddAdditionalPositionsInTrend==true && TimeElapsedSinceLastOpenTrade(Symbol(),
MagicNumber)>=DeltaTimeLiveTrades)
if(CountSells(Symbol(),MagicNumber)>0 && (CountBuys(Symbol(),MagicNumber)==0 &&CountSells(Symbol(),MagicNumber)=NormalizeDouble(res_zone_hi,Digits)) && (MathAbs(Bid-res_zone_hi)=strenght_used)
{SR_TP=res_zone_lo;
if(SR_TP>Bid-(BufferPips*Point)) SR_TP=Bid-(BufferPips*Point);SellOk=1;}
if((SellOk==1))
Page 21/44
-
if(TimeElapsedSinceLastOpenTrade(Symbol(),MagicNumber)>DeltaTimeLiveTrades ||TimeElapsedSinceLastOpenTrade(Symbol(),MagicNumber)==-1)
if(TimeElapsedSinceLastHistoTrade(Symbol(),MagicNumber)>DeltaTimeHistoTrades|| TimeElapsedSinceLastHistoTrade(Symbol(),MagicNumber)==-1)
if(CSS_Allowed_Sell==1){
SignalSellStack=true;
}
}//if (AddAdditionalPositionsInTrend==true &&
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+double GetAtr(string symbol,int tf,int period,int shift)
{//Returns the value of atr
return(iATR(symbol, tf, period, shift) );
}//End double GetAtr()//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void SplitSymbol()
{Curr1 = StringSubstrOld(Symbol(), 0, 3);Curr2 = StringSubstrOld(Symbol(), 3, 3);
//Calculate the index to pass to CSSint cc;for(cc=0; cc
-
{ScreenMessage=StringConcatenate(ScreenMessage,Gap,message);
}//End void SM()//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void DisplayUserFeedback()
{if(IsTesting()==true && IsVisualMode()==false) return;
ScreenMessage="";string zone_strength_r="";string zone_strength_s="";
if (res_strength==0) zone_strength_r="weak";if (res_strength==1) zone_strength_r="turncoat";if (res_strength==2) zone_strength_r="unproven";if (res_strength==3) zone_strength_r="verified";if (res_strength==4) zone_strength_r="proven";if (sup_strength==0) zone_strength_s="weak";if (sup_strength==1) zone_strength_s="turncoat";if (sup_strength==2) zone_strength_s="unproven";if (sup_strength==3) zone_strength_s="verified";if (sup_strength==4) zone_strength_s="proven";
//ScreenMessage = StringConcatenate(ScreenMessage,Gap + NL);SM(NL);
SM("Updates for this EA are to be found at http://www.stevehopwoodforex.com/phpBB3/viewtopic.php?f=5&t=3343"+NL);
SM("Feeling generous? Help keep SHF going with a small Paypal donation to [email protected]"+NL);
SM("Broker time = "+TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+": Local time = "+TimeToStr(TimeLocal(),TIME_DATE|TIME_SECONDS)+NL);
SM(version+NL);if(UseCSS)
{SM("CSS Values: "+Curr1+" actual = "+DoubleToStr(CurrVal1[1],4)+
" last closed candle = "+DoubleToStr(CurrVal1[2],4)+": Direction is "+CurrDirection1+NL);SM("CSS Values: "+Curr2+" actual = "+DoubleToStr(CurrVal2[1],4)+
" last closed candle= "+DoubleToStr(CurrVal2[2],4)+": Direction is "+CurrDirection2+NL);if(UseCSSForEntry==true)
{SM("Allowed Buy CSS(1=ok)= "+CSS_Allowed_Buy+NL);SM("Allowed Sell CSS(1=ok)= "+CSS_Allowed_Sell+NL);
}}//if (UseCSS)// get details of the zones and print them to the screen
if (res_zone >= 0)SM("Next Resistance Zone High: "+DoubleToStr(res_hi, Digits)+
" Next Resistance Zone Low:"+DoubleToStr(res_lo,Digits)+" "+" Zone Strenth: "+zone_strength_r+NL);
elseSM( "No Resistance Found, "+NL);
if (sup_zone >= 0)SM( "Next Support Zone High: "+DoubleToStr(sup_hi, Digits)+" Next Support Zone Low:"+
DoubleToStr(sup_lo,Digits)+" "+" Zone Strenth: "+zone_strength_s+NL);else
SM( "No Support Found."+NL);SM("TimeElaspsedSinceLastOpenTrade="+TimeElapsedSinceLastOpenTrade(Symbol(),MagicNumber)+
" seconds"+NL);SM("TimeElapsedSinceLastClosed Histo Trade="+TimeElapsedSinceLastHistoTrade(Symbol(),
MagicNumber)+" seconds"+NL);
SM("Open Price of last open order="+DoubleToStr(LastOpenTradePrice(Symbol(),MagicNumber),Digits)+NL);
SM("Echo Symbol="+Symbol()+NL);SM("Digits="+Digits+NL);SM("Multiplier="+multiplier+NL);
Page 23/44
-
if(HtfTimeFrame>0){SM("TMA-Slope value actual "+DoubleToStr(HtfSlopeVal[0],4)+": Trend is "+HtfSlopeTrend
+HtfSlopeAngle+NL);SM("TMA-Slope value last candle "+DoubleToStr(HtfSlopeVal[1],4)+NL);
//SM("Htf value " + DoubleToStr(HtfSlopeVal, 4) + ": Trend is " + HtfSlopeTrend + HtfSlopeAngle }//if (HtfTimeFrame > 0)
SM("SignalBuy="+SignalBuy+NL);SM("SignalSell="+SignalSell+NL);SM("Count Active Buys="+CountBuys(Symbol(),MagicNumber)+NL);SM("Count Active Sells="+CountSells(Symbol(),MagicNumber)+NL);SM("Count Historical Trades="+CountHisto(Symbol(),MagicNumber)+NL);SM("Trade Allowed Margin="+CheckTradeAllowedMargin()+NL);SM("Allowed Spread is = "+DoubleToStr((AdvertisedSpread*0.1),1)+" Actual Spread is= "+
DoubleToStr((spread*0.1),1)+NL);
Comment(ScreenMessage);
}//void DisplayUserFeedback()//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+bool SendSingleTrade(string symbol,int type,string comment,double lotsize,double price,double stop,double take)
{
//pah (Paul) contributed the code to get around the trade context busy error. Many thanks, Paul.
lotsize=NormalizeLots(symbol,lotsize); //fxdaytrader, normalize lots
color col=Red;if(type==OP_BUY || type==OP_BUYSTOP) col=Green;int expiry=0;
//if (SendPendingTrades) expiry = TimeCurrent() + (PendingExpiryMinutes * 60);
//RetryCount is declared as 10 in the Trading variables section at the top of this filefor(int cc=0; cc-1)
{ModifyOrder(ticket,stop,take);
}//if (ticket > 0)}}//if (BrokerIsECN)
if(ticket>-1) break;//Exit the trade send loopif(cc == RetryCount - 1) return(false);
//Error trapping for bothif(ticket
-
if(type == OP_SELL) stype = "OP_SELL";if(type == OP_BUYLIMIT) stype = "OP_BUYLIMIT";if(type == OP_SELLLIMIT) stype = "OP_SELLLIMIT";if(type == OP_BUYSTOP) stype = "OP_BUYSTOP";if(type == OP_SELLSTOP) stype = "OP_SELLSTOP";int err=GetLastError();Alert(symbol," ",WindowExpertName()," ",stype," order send failed with error(",err,
"): ",ErrorDescription(err));Print(symbol," ",WindowExpertName()," ",stype," order send failed with error(",err,
"): ",ErrorDescription(err));return(false);
}//if (ticket < 0) }//for (int cc = 0; cc < RetryCount; cc++);
TicketNo=ticket;//Make sure the trade has appeared in the platform's history to avoid duplicate trades.
//My mod of Matt's code attempts to overcome the bastard crim's attempts to overcome Matt's code.bool TradeReturnedFromBroker=false;while(!TradeReturnedFromBroker)
{TradeReturnedFromBroker=O_R_CheckForHistory(ticket);if(!TradeReturnedFromBroker)
{Alert(Symbol()," sent trade not in your trade history yet. Turn of this ea NOW.");
}//if (!TradeReturnedFromBroker)}//while (!TradeReturnedFromBroker)
//Got this far, so trade send succeededreturn(true);
}//End bool SendSingleTrade(int type, string comment, double lotsize, double price, double stop, double take)//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+void ModifyOrder(int ticket,double stop,double take)
{//Modifies an order already sent if the crim is ECN.
if(stop==0 && take==0) return; //nothing to do
if(!OrderSelect(ticket,SELECT_BY_TICKET)) return;//Trade does not exist, so no mod needed
//RetryCount is declared as 10 in the Trading variables section at the top of this file for(int cc=0; cc0)
{while(IsTradeContextBusy()) Sleep(100);if(OrderModify(ticket,OrderOpenPrice(),stop,take,OrderExpiration(),CLR_NONE))
{Alert("Modify Order Succeeded !");Print("Modify Order Succeeded !");return;
}}//if (take > 0 && stop > 0)
if(take!=0 && stop==0){while(IsTradeContextBusy()) Sleep(100);if(OrderModify(ticket,OrderOpenPrice(),OrderStopLoss(),take,OrderExpiration(),
CLR_NONE)){Alert("Modify Order Succeeded !");Print("Modify Order Succeeded !");return;
}}//if (take == 0 && stop != 0)
if(take==0 && stop!=0){while(IsTradeContextBusy()) Sleep(100);
Page 25/44
-
if(OrderModify(ticket,OrderOpenPrice(),stop,OrderTakeProfit(),OrderExpiration(),CLR_NONE))
{Alert("Modify Order Succeeded !");Print("Modify Order Succeeded !");return;
}}//if (take == 0 && stop != 0)
}//for (int cc = 0; cc < RetryCount; cc++)
//Got this far, so the order modify failedint err=GetLastError();Print(Symbol()," SL/TP order modify failed with error(",err,"): ",ErrorDescription(err
));Alert(Symbol()," SL/TP order modify failed with error(",err,"): ",ErrorDescription(err
));
}//void ModifyOrder(int ticket, double tp, double sl)//=============================================================================// O_R_CheckForHistory()//// This function is to work around a very annoying and dangerous bug in MT4:// immediately after you send a trade, the trade may NOT show up in the// order history, even though it exists according to ticket number.// As a result, EA's which count history to check for trade entries// may give many multiple entries, possibly blowing your account!//// This function will take a ticket number and loop until// it is seen in the history.//// RETURN VALUE:// TRUE if successful, FALSE otherwise////// FEATURES:// * Re-trying under some error conditions, sleeping a random// time defined by an exponential probability distribution.//// * Displays various error messages on the log for debugging.//// ORIGINAL AUTHOR AND DATE:// Matt Kennel, 2010////=============================================================================bool O_R_CheckForHistory(int ticket)
{
//My thanks to Matt for this code. He also has the undying gratitude of all users of my trading robots
int lastTicket=OrderTicket();
int cnt=0;int err=GetLastError(); // so we clear the global variable.err=0;bool exit_loop=false;bool success=false;
while(!exit_loop){
/* loop through open trades */int total=OrdersTotal();for(int c=0; c3)
{/* look through history too, as order may have opened and closed immediately */
Page 26/44
-
total=OrdersHistoryTotal();for(c=0; cO_R_Setting_max_retries)
{exit_loop=true;
}if(!(success || exit_loop))
{Print("Did not find #"+ticket+" in history, sleeping, then doing retry #"+cnt);O_R_Sleep(O_R_Setting_sleep_time,O_R_Setting_sleep_max);
}}
// Select back the prior ticket num in case caller was using it.if(lastTicket>=0)
{OrderSelect(lastTicket,SELECT_BY_TICKET,MODE_TRADES);
}if(!success)
{Print("Never found #"+ticket+" in history! crap!");
}return(success);
}//End bool O_R_CheckForHistory(int ticket)//=============================================================================// O_R_Sleep()//// This sleeps a random amount of time defined by an exponential// probability distribution. The mean time, in Seconds is given// in 'mean_time'.// This returns immediately if we are backtesting// and does not sleep.////=============================================================================void O_R_Sleep(double mean_time,double max_time)
{if(IsTesting())
{return; // return immediately if backtesting.
}double p = (MathRand()+1) / 32768.0;double t = -MathLog(p)*mean_time;t=MathMin(t,max_time);int ms=t*1000;if(ms
-
//+------------------------------------------------------------------+// v1.0.0, 5/7/13// * Initial release// * NanningBob's 10.5 rules apply// v1.1.0, 8/2/13// * Added getSlopeRSI// * Changed to original NB rules// v1.1.1, 8/5/13// * Added getGlobalMarketTrend// * Added parameters for caching mechanism// v1.1.2, 9/6/13// * Added flushCache parameter
bool libCSSsundayCandlesDetected = false;bool libCSSaddSundayToMonday = false;bool libCSSuseOnlySymbolOnChart = false;string libCSScacheSymbol = "EURUSD";int libCSScacheTimeframe = PERIOD_M1;string libCSSsymbolsToWeigh ="GBPNZD,EURNZD,GBPAUD,GBPCAD,GBPJPY,GBPCHF,CADJPY,EURCAD,EURAUD,USDCHF,GBPUSD,EURJPY,NZDJPY,AUDC;int libCSSsymbolCount;string libCSSsymbolNames[];string libCSScurrencyNames[libCSSCURRENCYCOUNT]={ "USD","EUR","GBP","CHF","JPY","AUD","CAD","NZD" };double libCSScurrencyValues[libCSSCURRENCYCOUNT]; // Currency slope strengthdouble libCSScurrencyOccurrences[libCSSCURRENCYCOUNT];// Holds the number of occurrences of each currency in symbols//+------------------------------------------------------------------+//| libCSSinit() |//+------------------------------------------------------------------+void libCSSinit()
{libCSSinitSymbols();
libCSSsundayCandlesDetected=false;for(int i=0; i
-
ArrayResize(libCSSsymbolNames,size+1);// Set arraylibCSSsymbolNames[size]=newSymbol;
}// Trim symbolslibCSSsymbolsToWeigh=StringSubstrOld(libCSSsymbolsToWeigh,i+1);i=StringFind(libCSSsymbolsToWeigh,",");
}
// Kill unwanted symbols from arrayif(libCSSuseOnlySymbolOnChart)
{libCSSsymbolCount=ArraySize(libCSSsymbolNames);string tempNames[];for(i=0; i
-
if(TimeDayOfWeek(iTime(symbol,PERIOD_D1,shift))==0) shiftWithoutSunday++;}
double atr=iATR(symbol,tf,100,shiftWithoutSunday+10)/10;double gadblSlope=0.0;if(atr!=0)
{dblTma=libCSScalcTmaTrue(symbol,tf,shiftWithoutSunday);dblPrev=libCSScalcPrevTrue(symbol,tf,shiftWithoutSunday);gadblSlope=(dblTma-dblPrev)/atr;
}
return ( gadblSlope );}
//+------------------------------------------------------------------+//| calcTmaTrue() |//+------------------------------------------------------------------+double libCSScalcTmaTrue(string symbol,int tf,int inx)
{return ( iMA( symbol, tf, 21, 0, MODE_LWMA, PRICE_CLOSE, inx ) );
}//+------------------------------------------------------------------+//| calcPrevTrue() |//+------------------------------------------------------------------+double libCSScalcPrevTrue(string symbol,int tf,int inx)
{double dblSum = iClose( symbol, tf, inx + 1 ) * 21;double dblSumw = 21;int jnx,knx;
dblSum += iClose( symbol, tf, inx ) * 20;dblSumw += 20;
for(jnx=1,knx=20; jnx
-
}//+------------------------------------------------------------------+//| getBBonStoch( string symbol, int tf, int shift ) |//+------------------------------------------------------------------+
bool CloseEnough(double num1,double num2){
/*
This function addresses the problem of the way in which mql4 compares doubles. It often messes up the 8th decimal point.
For example, if A = 1.5 and B = 1.5, then these numbers are clearly equal. Unseen by the coder, mql4 may
actually be giving B the value of 1.50000001, and so the variable are not equal, even though they are.
This nice little quirk explains some of the problems I have endured in the past when comparing doubles. This is common to a lot of program languages, so watch out for it if you program elsewhere. Gary (garyfritz) offered this solution, so our thanks to him. */
if(num1==0 && num2==0) return(true); //0==0if(MathAbs(num1 - num2) / (MathAbs(num1) + MathAbs(num2)) < 0.00000001) return(true);
//Doubles are unequalreturn(false);
}//End bool CloseEnough(double num1, double num2)
//see also the original function by WHRoeder, http://forum.mql4.com/45425#564188, fxdaytraderdouble NormalizeLots(string symbol,double lots)
{if(MathAbs(lots)==0.0) return(0.0);
//just in case ... otherwise it may happen that after rounding 0.0 the result is >0 and we have got a problem, fxdaytraderdouble ls=MarketInfo(symbol,MODE_LOTSTEP);lots=MathMin(MarketInfo(symbol,MODE_MAXLOT),MathMax(MarketInfo(symbol,MODE_MINLOT),lots
)); //check if lots >= min. lots &&
-
}}
return( dblSum / dblSumw );
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+/*void CalculatePivots(string symbol){ //Calculates the monthly and weekly pivots //Calculation code copied from 10.2 MonthlyMIDPivots.mq4
//I have copied this function from BJS, and left the parameter in place in case being able to
//Define the variables double last_low;//Previous candle's low double last_high;//Previous candle's high double last_close;//Previous candle's close double P;////Previous candle's pivot
//Weekly last_low=iLow(symbol, PERIOD_W1, 1); last_high=iHigh(symbol, PERIOD_W1, 1); last_close=iClose(symbol, PERIOD_W1, 1);
//Pivot P=(last_high+last_low+last_close)/3; WeeklyPivot = P;
//Daily int shift = 1;//Need to deal with a Sunday candle int d = TimeDayOfWeek(TimeCurrent() ); if (d == 1 && (BrokerHasSundayCandle )) shift = 2;
last_low=iLow(symbol, PERIOD_D1, shift); last_high=iHigh(symbol, PERIOD_D1, shift); last_close=iClose(symbol, PERIOD_D1, shift);
//Pivot P=(last_high+last_low+last_close)/3; DailyPivot = P; //Yesterday int yshift = 2;//Need to deal with a Sunday candle d = TimeDayOfWeek(TimeCurrent() ); if (d == 2 && (BrokerHasSundayCandle )) yshift = 3;
last_low=iLow(symbol, PERIOD_D1, yshift); last_high=iHigh(symbol, PERIOD_D1, yshift); last_close=iClose(symbol, PERIOD_D1, yshift);
//Pivot P=(last_high+last_low+last_close)/3; YesterdayPivot = P; //TwoDaysBefore int twoshift = 3;//Need to deal with a Sunday candle d = TimeDayOfWeek(TimeCurrent() ); if (d == 3 && (BrokerHasSundayCandle ))twoshift = 4;
last_low=iLow(symbol, PERIOD_D1, twoshift); last_high=iHigh(symbol, PERIOD_D1, twoshift); last_close=iClose(symbol, PERIOD_D1, twoshift);
//Pivot P=(last_high+last_low+last_close)/3; TwoBeforedayPivot = P;
}//End void CalculatePivots()*//////////indi integration
Page 32/44
-
////////// LibSSSRv4.mqh// Copyright 2013, Andrew Sumner//
int SSSR_FindZoneV2(int direction, bool useWeak, double price, double &hi, double &lo, int &strength){
int zone = SSSR_FindZone(direction, useWeak, price);
if (zone >= 0){
hi = SSSR_GetZoneHi(zone);lo = SSSR_GetZoneLo(zone);strength = SSSR_GetZoneStrength(zone);
}
return(zone);}
//
///////////////////////////////////////////////////////////////////////////////////////////////// INTERNAL LIBRARY FUNCTIONS ONLY BELOW
///////////////////////////////////////////////////////////////////////////////////////////////
//// SSSR_Settings//// Call this once when the EA inits//
//// SSSR_FindFractal//int SSSR_FindFractal(int direction, int type, int limit=1000, int shift=0, int count=0){
if ((direction > SSSR_UP || direction < SSSR_DN) ||(type != SSSR_FAST && type != SSSR_SLOW))
return(-1);
if (shift < 0)shift = 0;
if (count < 0)count = 0;
if (limit < 100)limit = 100;
int up = -1, dn = -1;if (type == SSSR_FAST){
if (direction >= SSSR_NONE)up = SSSR_FindFastUpFractal(shift, count, limit);
if (direction = SSSR_NONE)up = SSSR_FindSlowUpFractal(shift, count, limit);
if (direction
-
if (direction == SSSR_NONE){
if (up > -1 && dn > -1)return(MathMin(up, dn));
else if (up > -1)return(up);
elsereturn(dn);
}else if (direction == SSSR_UP)
return(up);else
return(dn);}
//// SSSR_UpdateZones//// Call this to make the library recalculate the zones//void SSSR_UpdateZones(bool checkCandle, string symbol, int timeframe){
if (SSSR_sym != symbol || SSSR_TF != timeframe)checkCandle = false;
SSSR_sym = symbol;SSSR_TF = timeframe;
if (checkCandle && !SSSR_NewBar())return;
DeleteZones();SSSR_FastFractals();SSSR_SlowFractals();SSSR_FindZones();DrawZones();
}
//// SSSR_FindZone//// Call this function to discover the closest zone to the provided price value//int SSSR_FindZone(int direction, bool useWeak, double price){
int i, zone = -1;double hi = 0, lo = 99999;
if (direction == SSSR_UP){
for (i = 0; i < SSSR_zone_count; i++){
if (SSSR_zone_hi[i] > price && (useWeak || SSSR_zone_strength[i] != SSSR_ZONE_WEAK))
{if (SSSR_zone_lo[i] < lo && (SSSR_zone_type[i] == SSSR_ZONE_RESIST ||
SSSR_zone_lo[i] > price)){
lo = SSSR_zone_lo[i];zone = i;
}}
}}else if (direction == SSSR_DN){
for (i = 0; i < SSSR_zone_count; i++){
if (SSSR_zone_lo[i] < price && (useWeak || SSSR_zone_strength[i] != SSSR_ZONE_WEAK))
{if (SSSR_zone_hi[i] > hi && (SSSR_zone_type[i] == SSSR_ZONE_SUPPORT ||
SSSR_zone_hi[i] < price)){
hi = SSSR_zone_hi[i];zone = i;
Page 34/44
-
}}
}}else
return(-1);
return(zone);}
int SSSR_GetZoneType(int zone){
return(SSSR_zone_type[zone]);}
double SSSR_GetZoneHi(int zone){
if (zone < 0 || zone >= SSSR_zone_count)return(0);
return(SSSR_zone_hi[zone]);}
double SSSR_GetZoneLo(int zone){
if (zone < 0 || zone >= SSSR_zone_count)return(0);
return(SSSR_zone_lo[zone]);}
int SSSR_GetZoneStrength(int zone){
if (zone < 0 || zone >= SSSR_zone_count)return(0);
return(SSSR_zone_strength[zone]);}
///////////////////////////////////////////////////////////////////////////////////////////////// INTERNAL LIBRARY FUNCTIONS ONLY BELOW
///////////////////////////////////////////////////////////////////////////////////////////////
bool SSSR_NewBar(){
static datetime LastTime = 0;
if (iTime(SSSR_sym, SSSR_TF, 0) > LastTime){
LastTime = iTime(SSSR_sym, SSSR_TF, 0);return(true);
}
elsereturn(false);
}
bool SSSR_Fractal(int M, int P, int shift){
if (SSSR_TF > P)P = SSSR_TF;
if (SSSR_TF > 0)P = P / SSSR_TF * 2 + MathCeil(P / SSSR_TF / 2);
if (shift < P)return(false);
if (shift > iBars(SSSR_sym, SSSR_TF) - P)return(false);
for (int i = 1; i
-
if (M == SSSR_UP_POINT){
if (iHigh(SSSR_sym, SSSR_TF, shift + i) > iHigh(SSSR_sym, SSSR_TF, shift))return(false);
if (iHigh(SSSR_sym, SSSR_TF, shift - i) >= iHigh(SSSR_sym, SSSR_TF, shift))return(false);
}
if (M == SSSR_DN_POINT){
if (iLow(SSSR_sym, SSSR_TF, shift + i) < iLow(SSSR_sym, SSSR_TF, shift))return(false);
if (iLow(SSSR_sym, SSSR_TF, shift - i) count)
return(shift);}
}
return(-1);}
int SSSR_FindFastDnFractal(int shift, int count, int limit){
int found = 0;
for (int i=shift; i 0.00001){
found++;if (found > count)
return(shift);}
}
return(-1);}
int SSSR_FindSlowUpFractal(int shift, int count, int limit){
int found = 0;
for (int i=shift; i 0.00001){
found++;if (found > count)
return(shift);}
}
return(-1);}
int SSSR_FindSlowDnFractal(int shift, int count, int limit){
Page 36/44
-
int found = 0;
for (int i=shift; i 0.00001){
found++;if (found > count)
return(shift);}
}
return(-1);}
void SSSR_FastFractals(){
int shift;int limit = MathMin(iBars(SSSR_sym, SSSR_TF) - 1, SSSR_BackLimit);int P = SSSR_TF * SSSR_zone_fastfactor;
ArrayResize(SSSR_FastUpPts, limit);ArrayResize(SSSR_FastDnPts, limit);ArraySetAsSeries(SSSR_FastUpPts, true);ArraySetAsSeries(SSSR_FastDnPts, true);
SSSR_FastUpPts[0] = 0.0;SSSR_FastUpPts[1] = 0.0;SSSR_FastDnPts[0] = 0.0;SSSR_FastDnPts[1] = 0.0;
for (shift = limit; shift > 1; shift--){
SSSR_FastUpPts[shift] = 0.0;
if (SSSR_Fractal(SSSR_UP_POINT, P, shift))SSSR_FastUpPts[shift] = iHigh(SSSR_sym, SSSR_TF, shift);
SSSR_FastDnPts[shift] = 0.0;
if (SSSR_Fractal(SSSR_DN_POINT, P, shift))SSSR_FastDnPts[shift] = iLow(SSSR_sym, SSSR_TF, shift);
}}
void SSSR_SlowFractals(){
int shift;int limit = MathMin(iBars(SSSR_sym, SSSR_TF) - 1, SSSR_BackLimit);int P = PERIOD_SR * SSSR_zone_slowfactor;
ArrayResize(SSSR_SlowUpPts, limit);ArrayResize(SSSR_SlowDnPts, limit);ArraySetAsSeries(SSSR_SlowUpPts, true);ArraySetAsSeries(SSSR_SlowDnPts, true);
SSSR_SlowUpPts[0] = 0.0;SSSR_SlowUpPts[1] = 0.0;SSSR_SlowDnPts[0] = 0.0;SSSR_SlowDnPts[1] = 0.0;
for (shift = limit; shift > 1; shift--){
SSSR_SlowUpPts[shift] = 0.0;
if (SSSR_Fractal(SSSR_UP_POINT, P, shift))SSSR_SlowUpPts[shift] = iHigh(SSSR_sym, SSSR_TF, shift);
SSSR_SlowDnPts[shift] = 0.0;
if (SSSR_Fractal(SSSR_DN_POINT, P, shift))SSSR_SlowDnPts[shift] = iLow(SSSR_sym, SSSR_TF, shift);
}}
Page 37/44
-
void SSSR_FindZones(){
int i, j, shift, bustcount = 0, testcount = 0;double hival, loval;bool turned = false, hasturned = false;
double temp_hi[1000], temp_lo[1000];int temp_start[1000], temp_hits[1000], temp_strength[1000], temp_count = 0;bool temp_turn[1000], temp_merge[1000];int merge1[1000], merge2[1000], merge_count = 0;
// iterate through zones from oldest to youngest (ignore recent 5 bars),// finding those that have survived through to the present...for (shift = MathMin(iBars(SSSR_sym, SSSR_TF) - 1, SSSR_BackLimit); shift > 5; shift--){
double atr = iATR(SSSR_sym, SSSR_TF, 7, shift);double fu = atr / 2 * SSSR_zone_fuzzfactor;bool isWeak;bool touchOk = false;bool isBust = false;double close = iClose(SSSR_sym, SSSR_TF, shift);double high = iHigh(SSSR_sym, SSSR_TF, shift);double low = iLow(SSSR_sym, SSSR_TF, shift);double hi_i;double lo_i;
if (SSSR_FastUpPts[shift] > 0.001){
// a fractal high pointisWeak = true;
if (SSSR_SlowUpPts[shift] > 0.001)isWeak = false;
hival = high;
if (SSSR_zone_extend == true)hival += fu;
loval = MathMax(MathMin(close, high - fu), high - fu * 2);turned = false;hasturned = false;isBust = false;
bustcount = 0;testcount = 0;
for (i = shift - 1; i >= 0; i--){
hi_i = iHigh(SSSR_sym, SSSR_TF, i);lo_i = iLow(SSSR_sym, SSSR_TF, i);
if ((!turned && SSSR_FastUpPts[i] >= loval && SSSR_FastUpPts[i] = loval && SSSR_FastUpPts[j]
-
}}
if ((turned == false && hi_i > hival)|| (turned == true && lo_i < loval))
{// this level has been busted at least oncebustcount++;
if (bustcount > 1 || isWeak == true){
// busted twice or moreisBust = true;break;
}
turned = !turned;
hasturned = true;
// forget previous hitstestcount = 0;
}}
if (!isBust){
// level is still valid, add to our listtemp_hi[temp_count] = hival;temp_lo[temp_count] = loval;temp_turn[temp_count] = hasturned;temp_hits[temp_count] = testcount;temp_start[temp_count] = shift;temp_merge[temp_count] = false;
if (testcount > 3)temp_strength[temp_count] = SSSR_ZONE_PROVEN;
elseif (testcount > 0)
temp_strength[temp_count] = SSSR_ZONE_VERIFIED;
elseif (hasturned)
temp_strength[temp_count] = SSSR_ZONE_TURNCOAT;
elseif (!isWeak)
temp_strength[temp_count] = SSSR_ZONE_UNTESTED;
elsetemp_strength[temp_count] = SSSR_ZONE_WEAK;
temp_count++;}
}
elseif (SSSR_FastDnPts[shift] > 0.001){
// a zigzag low pointisWeak = true;
if (SSSR_SlowDnPts[shift] > 0.001)isWeak = false;
loval = low;
if (SSSR_zone_extend == true)loval -= fu;
hival = MathMin(MathMax(close, low + fu), low + fu * 2);turned = false;hasturned = false;
Page 39/44
-
bustcount = 0;testcount = 0;isBust = false;
for (i = shift - 1; i >= 0; i--){
hi_i = iHigh(SSSR_sym, SSSR_TF, i);lo_i = iLow(SSSR_sym, SSSR_TF, i);
if ((turned && SSSR_FastUpPts[i] >= loval && SSSR_FastUpPts[i] = loval && SSSR_FastUpPts[j] hival)|| (!turned && lo_i < loval))
{// this level has been busted at least oncebustcount++;
if (bustcount > 1 || isWeak){
// busted twice or moreisBust = true;break;
}
turned = !turned;
hasturned = true;
// forget previous hitstestcount = 0;
}}
if (!isBust){
// level is still valid, add to our listtemp_hi[temp_count] = hival;temp_lo[temp_count] = loval;temp_turn[temp_count] = hasturned;temp_hits[temp_count] = testcount;temp_start[temp_count] = shift;temp_merge[temp_count] = false;
if (testcount > 3)temp_strength[temp_count] = SSSR_ZONE_PROVEN;
elseif (testcount > 0)
temp_strength[temp_count] = SSSR_ZONE_VERIFIED;
Page 40/44
-
elseif (hasturned)
temp_strength[temp_count] = SSSR_ZONE_TURNCOAT;
elseif (!isWeak)
temp_strength[temp_count] = SSSR_ZONE_UNTESTED;
elsetemp_strength[temp_count] = SSSR_ZONE_WEAK;
temp_count++;}
}}
// look for overlapping zones...if (SSSR_zone_merge){
merge_count = 1;int iterations = 0;
while (merge_count > 0 && iterations < 3){
merge_count = 0;iterations++;
for (i = 0; i < temp_count; i++)temp_merge[i] = false;
for (i = 0; i < temp_count - 1; i++){
if (temp_hits[i] == -1 || temp_merge[j])continue;
for (j = i + 1; j < temp_count; j++){
if (temp_hits[j] == -1 || temp_merge[j])continue;
if ((temp_hi[i] >= temp_lo[j] && temp_hi[i] = temp_lo[i] && temp_hi[j] 3)temp_strength[target] = SSSR_ZONE_PROVEN;
if (temp_hits[target] == 0 && !temp_turn[target]){
temp_hits[target] = 1;
if (temp_strength[target] < SSSR_ZONE_VERIFIED)temp_strength[target] = SSSR_ZONE_VERIFIED;
Page 41/44
-
}if (!temp_turn[target] || !temp_turn[source])temp_turn[target] = false;
if (temp_turn[target])temp_hits[target] = 0;
temp_hits[source] = -1;}
}}
// copy the remaining list into our official zones arraysSSSR_zone_count = 0;
for (i = 0; i < temp_count; i++){
if (temp_hits[i] >= 0 && SSSR_zone_count < 1000){
SSSR_zone_hi[SSSR_zone_count] = temp_hi[i];SSSR_zone_lo[SSSR_zone_count] = temp_lo[i];SSSR_zone_hits[SSSR_zone_count] = temp_hits[i];SSSR_zone_turn[SSSR_zone_count] = temp_turn[i];SSSR_zone_start[SSSR_zone_count] = temp_start[i];SSSR_zone_strength[SSSR_zone_count] = temp_strength[i];
if (SSSR_zone_hi[SSSR_zone_count] < Close[4])SSSR_zone_type[SSSR_zone_count] = SSSR_ZONE_SUPPORT;
elseif (SSSR_zone_lo[SSSR_zone_count] > Close[4])
SSSR_zone_type[SSSR_zone_count] = SSSR_ZONE_RESIST;
else{
for (j = 5; j < 1000; j++){
if (iClose(SSSR_sym, SSSR_TF, j) < SSSR_zone_lo[SSSR_zone_count]){
SSSR_zone_type[SSSR_zone_count] = SSSR_ZONE_RESIST;break;
}
elseif (iClose(SSSR_sym, SSSR_TF, j) > SSSR_zone_hi[SSSR_zone_count]){
SSSR_zone_type[SSSR_zone_count] = SSSR_ZONE_SUPPORT;break;
}}
if (j == 1000)SSSR_zone_type[SSSR_zone_count] = SSSR_ZONE_SUPPORT;
}
SSSR_zone_count++;}
}}
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+bool NewBar(int TimeFrame)
{static datetime LastTime=0;if(iTime(NULL,TimeFrame,0)!=LastTime)
{LastTime=iTime(NULL,TimeFrame,0);return (true);
}else
return (false);
Page 42/44
-
}//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+
//+------------------------------------------------------------------+//| |//+------------------------------------------------------------------+bool PartCloseTrade(int ticket)
{//Close MoveOnSLPartClosePercent of the initial trade.//Return true if close succeeds, else false
if(!OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) return(true);//in case the trade closed
double CloseLots=NormalizeLots(OrderSymbol(),OrderLots() *(PartClosePercent/100));bool Success=OrderClose(ticket,CloseLots,OrderClosePrice(),1000,Blue);
//fxdaytrader, NormalizeLots(...
if(!Success){
//mod. fxdaytrader, orderclose-retry if failed with ordercloseprice(). Maybe very seldom, but itwhile(IsTradeContextBusy()) Sleep(100);RefreshRates();if(OrderType()==OP_BUY) Success = OrderClose(ticket, CloseLots, MarketInfo(OrderSymbol
(),MODE_BID), 5000, Blue);if(OrderType()==OP_SELL) Success = OrderClose(ticket, CloseLots, MarketInfo(
OrderSymbol(),MODE_ASK), 5000, Blue);//end mod. //original:if(!Success)
{Alert(" PartCloseTrade() failed!!");return (false);
}}//if (!Success)
//Got this far, so closure succeededreturn (true);
}//bool PartCloseTrade(int ticket)// for 6xx build compatibilit added by milanese
string StringSubstrOld(string x,int a,int b=-1){if(a
-
ObjectSet(s,OBJPROP_TIME1,iTime(NULL,PERIOD_SR,SSSR_zone_start[i]));ObjectSet(s,OBJPROP_TIME2,TimeCurrent());ObjectSet(s,OBJPROP_PRICE1,SSSR_zone_hi[i]);ObjectSet(s,OBJPROP_PRICE2,SSSR_zone_lo[i]);ObjectSet(s,OBJPROP_BACK,zone_solid);ObjectSet(s,OBJPROP_WIDTH,zone_linewidth);ObjectSet(s,OBJPROP_STYLE, zone_style);
if(SSSR_zone_type[i]==SSSR_ZONE_SUPPORT){// support zoneif(SSSR_zone_strength[i]==SSSR_ZONE_TURNCOAT)
ObjectSet(s,OBJPROP_COLOR,color_support_turncoat);else if(SSSR_zone_strength[i]==SSSR_ZONE_PROVEN)
ObjectSet(s,OBJPROP_COLOR,color_support_proven);else if(SSSR_zone_strength[i]==SSSR_ZONE_VERIFIED)
ObjectSet(s,OBJPROP_COLOR,color_support_verified);else if(SSSR_zone_strength[i]==SSSR_ZONE_UNTESTED)
ObjectSet(s,OBJPROP_COLOR,color_support_untested);else
ObjectSet(s,OBJPROP_COLOR,color_support_weak);}
else{// resistance zoneif(SSSR_zone_strength[i]==SSSR_ZONE_TURNCOAT)
ObjectSet(s,OBJPROP_COLOR,color_resist_turncoat);else if(SSSR_zone_strength[i]==SSSR_ZONE_PROVEN)
ObjectSet(s,OBJPROP_COLOR,color_resist_proven);else if(SSSR_zone_strength[i]==SSSR_ZONE_VERIFIED)
ObjectSet(s,OBJPROP_COLOR,color_resist_verified);else if(SSSR_zone_strength[i]==SSSR_ZONE_UNTESTED)
ObjectSet(s,OBJPROP_COLOR,color_resist_untested);else
ObjectSet(s,OBJPROP_COLOR,color_resist_weak);}
}}void DeleteZones(){int len=5;int i;
while(i