//+------------------------------------------------------------------+ //| MA_Angle_EA.mq4 | //| Copyright © 2007 Robert Hill | //+------------------------------------------------------------------+ #property copyright "Copyright © 2007, Robert Hill" #include #define UP 1 #define DOWN 2 #define LONG 1 #define SHORT -1 #define FLAT 0 #define SMA 0 #define EMA 1 #define SMMA 2 #define LWMA 3 #define LSMA 4 extern bool Debug = false; // Change to true to allow print extern int MA_Period=34; extern string m = "--Moving Average Types--"; extern string m0 = " 0 = SMA"; extern string m1 = " 1 = EMA"; extern string m2 = " 2 = SMMA"; extern string m3 = " 3 = LWMA"; extern string m4 = " 4 = LSMA"; extern int MA_Type = 1; extern string p = "--Applied Price Types--"; extern string p0 = " 0 = close"; extern string p1 = " 1 = open"; extern string p2 = " 2 = high"; extern string p3 = " 3 = low"; extern string p4 = " 4 = median(high+low)/2"; extern string p5 = " 5 = typical(high+low+close)/3"; extern string p6 = " 6 = weighted(high+low+close+close)/4"; extern int MA_AppliedPrice = 0; extern double EntryAngle_Threshold=10; // What size angle to trigger a trade extern double ExitAngle_Threshold=2; extern int PrevMAShift=3; extern int CurMAShift=1; //+---------------------------------------------------+ //|Money Management | //+---------------------------------------------------+ extern string mm = "---Money Management---"; extern double Lots=0.1; extern double MaxLot = 30; extern bool UseMoneyManagement = true; // Change to false to shutdown money management controls. extern bool BrokerIsIBFX = false; extern string mm1="Set mini and micro to false for standard account"; extern bool AccountIsMini = true; extern bool AccountIsMicro = false; extern double TradeSizePercent = 1; // Change to whatever percent of equity you wish to risk. extern bool BrokerPermitsFractionalLots = true; //+---------------------------------------------------+ //|Profit controls | //+---------------------------------------------------+ extern double StopLoss = 0; // Maximum pips willing to lose per position. extern int TakeProfit = 0; extern int Slippage = 3; // Possible fix for not getting filled or closed extern string tsp = "--Trailing Stop Types--"; extern string tsp0 = " 0 = None"; extern string tsp1 = " 1 = Trail immediately"; extern string tsp2 = " 2 = Wait to trail"; extern string tsp3 = " 3 = Uses 3 levels before trail"; extern string tsp4 = " 4 = Breakeven + Lockin"; extern int TrailingStopType = 4; extern string ts2 = "Settings for Type 2"; extern double TrailingStop = 15; // Change to whatever number of pips you wish to trail your position with. extern string ts3 = "Settings for Type 3"; extern double FirstMove = 20; // Type 3 first level pip gain extern double FirstStopLoss = 50; // Move Stop to Breakeven extern double SecondMove = 30; // Type 3 second level pip gain extern double SecondStopLoss = 30; // Move stop to lock is profit extern double ThirdMove = 40; // type 3 third level pip gain extern double TrailingStop3 = 20; // Move stop and trail from there extern string ts4 = "Settings for Type 4"; extern double BreakEven = 30; extern int LockInPips = 1; // Profit Lock in pips int SignalCandle = 1; extern string sm0="--Trading Hours Filter--"; extern string sm2="UseTradingHours - Enter 0 for false, 1 for true"; extern int UseTradingHours = 0; extern string sm4="TradeAsian - Enter 0 for false, 1 for true"; extern int TradeAsianMarket = 1; extern int AsianStart = 100; // Start trades after time extern int AsianStop = 400; // Stop trading after time extern string sm5="Trade Europe - Enter 0 for false, 1 for true"; extern int TradeEuropeanMarket = 1; extern int EurStart = 1000; // Start trades after time extern int EurStop = 1200; // Stop trading after time extern string sm6="Trade NY - Enter 0 for false, 1 for true"; extern int TradeNewYorkMarket = 1; extern int NYStart = 1600; // Start trades after time extern int NYStop = 1800; // Stop trading after time //+---------------------------------------------------+ //|General controls | //+---------------------------------------------------+ string setup; double lotMM; int TradesInThisSymbol; int MagicNumber; bool YesStop; double myPoint, mFactor; //+---------------------------------------------------+ //| Indicator values for filters | //| Add or Change to test your system | //+---------------------------------------------------+ double MACurrent, MAPrevious; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- MagicNumber = 3000 + func_Symbol2Val(Symbol())*100 + func_TimeFrame_Const2Val(Period()); setup="MA_Angle_EA" + Symbol() + "_" + func_TimeFrame_Val2String(func_TimeFrame_Const2Val(Period())); myPoint = SetPoint(); if(CurMAShift >= PrevMAShift) { Print("Error: CurMAShift >= PrevMAShift"); PrevMAShift = 6; CurMAShift = 0; } mFactor = Get_mFactor(); //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { return(0); } //+------------------------------------------------------------------+ //| The functions from this point to the start function are where | //| changes are made to test other systems or strategies. | //|+-----------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom Indicators | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| LSMA with PriceMode | //| LSMA - Least Squares Moving Average function calculation | //| LSMA_In_Color Indicator plots the end of the linear regression line | //| PrMode 0=close, 1=open, 2=high, 3=low, 4=median(high+low)/2, | //| 5=typical(high+low+close)/3, 6=weighted(high+low+close+close)/4 | //+------------------------------------------------------------------+ double fLSMA(int LSMAPeriod, int LSMAPrice,int shift) { double wt; double ma1=iMA(NULL,0,LSMAPeriod,0,MODE_SMA ,LSMAPrice,shift); double ma2=iMA(NULL,0,LSMAPeriod,0,MODE_LWMA,LSMAPrice,shift); wt = MathFloor((3.0*ma2-2.0*ma1)/myPoint)*myPoint; return(wt); } double Get_mFactor() { string Sym; double Factor; int ShiftDif; Factor = 100000.0; Sym = StringSubstr(Symbol(),3,3); if (Sym == "JPY") Factor = 1000.0; ShiftDif = PrevMAShift-CurMAShift; Factor /= ShiftDif; return (Factor); } void GetMAs (int TrendMethod, int MAPeriod, int Prev, int Cur) { switch (TrendMethod) { case LSMA : MACurrent=fLSMA(MAPeriod,MA_AppliedPrice,Cur); MAPrevious=fLSMA(MAPeriod,MA_AppliedPrice,Prev); break; default : MACurrent=iMA(NULL,0,MAPeriod,0,MA_Type,MA_AppliedPrice,Cur); MAPrevious=iMA(NULL,0,MAPeriod,0,MA_Type,MA_AppliedPrice,Prev); } } //+------------------------------------------------------------------+ //| CheckExitCondition | //| Check if AngleSep cross 0 line | //+------------------------------------------------------------------+ bool CheckExitCondition(int cmd) { double maAngle; GetMAs(MA_Type, MA_Period , PrevMAShift, CurMAShift); maAngle = mFactor * (MACurrent - MAPrevious)/2.0; switch (cmd) { case OP_BUY : if (maAngle < ExitAngle_Threshold) return(true); break; case OP_SELL : if (maAngle > -ExitAngle_Threshold) return(true); } return(false); } //+------------------------------------------------------------------+ //| CheckEntryCondition | //| Check if separation on LSMA pair | //+------------------------------------------------------------------+ int GetSignal() { double maAngle; GetMAs(MA_Type, MA_Period , PrevMAShift, CurMAShift); maAngle = mFactor * (MACurrent - MAPrevious)/2.0; if (maAngle > EntryAngle_Threshold) return(LONG); if (maAngle < -EntryAngle_Threshold) return(SHORT); return(FLAT); } //-- Check for Start of a new Bar bool NewBar() { static datetime dt = 0; if (Time[0] != dt) { dt = Time[0]; return(true); } return(false); } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { int signal; //---- RefreshRates(); //+------------------------------------------------------------------+ //| Check for Open Position | //+------------------------------------------------------------------+ HandleOpenPositions(); // Check if any open positions were not closed TradesInThisSymbol = CheckOpenPositions(); //+------------------------------------------------------------------+ //| Check if OK to make new trades | //+------------------------------------------------------------------+ // Only allow 1 trade per Symbol if(TradesInThisSymbol > 0) return(0); YesStop = CheckTradeFilters(); if (YesStop) return(0); if (!NewBar()) return(0); // wait until first tick after bar close to take any action; signal=GetSignal(); lotMM = GetLots(); if (signal == LONG) OpenBuyOrder(); if (signal == SHORT) OpenSellOrder(); //---- return(0); } void OpenBuyOrder() { int err,ticket, digits; double TPprice,STprice; ticket=OrderSend(Symbol(),OP_BUY,lotMM,Ask,Slippage,0,0,setup,MagicNumber,0,Green); if (ticket > 0) { if (OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) { if (Debug) Print("BUY order opened : ", OrderOpenPrice()); if (StopLoss != 0 || TakeProfit != 0) { TPprice = 0; if (TakeProfit > 0) TPprice=TakeLong(OrderOpenPrice(), TakeProfit); STprice = 0; if (StopLoss > 0) { STprice=StopLong(OrderOpenPrice(), StopLoss); STprice = ValidStopLoss(OP_BUY,Bid, STprice); } // Normalize stoploss / takeprofit to the proper # of digits. if (Digits > 0) { STprice = NormalizeDouble( STprice, Digits); TPprice = NormalizeDouble( TPprice, Digits); } ModifyOrder(ticket, OrderOpenPrice(), STprice, TPprice, LightGreen); } } } else { err = GetLastError(); Print("Error opening BUY order [" + setup + "]: (" + err + ") " + ErrorDescription( err) ); } } //+------------------------------------------------------------------+ //| OpenSellOrder | //| If Stop Loss or TakeProfit are used the values are calculated | //| for each trade | //+------------------------------------------------------------------+ void OpenSellOrder() { int err, ticket, digits; double TPprice,STprice; ticket=OrderSend(Symbol(),OP_SELL,lotMM,Bid,Slippage,0,0,setup,MagicNumber,0,Red); if (ticket > 0) { if (OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES)) { if (Debug) Print("SELL order opened : ", OrderOpenPrice()); if (StopLoss != 0 || TakeProfit != 0) { TPprice = 0; if (TakeProfit > 0) TPprice=TakeShort(OrderOpenPrice(),TakeProfit); STprice = 0; if (StopLoss > 0) { STprice=StopShort(OrderOpenPrice() ,StopLoss); STprice = ValidStopLoss(OP_SELL,Ask, STprice); } // Normalize stoploss / takeprofit to the proper # of digits. if (Digits > 0) { STprice = NormalizeDouble( STprice, Digits); TPprice = NormalizeDouble( TPprice, Digits); } ModifyOrder(ticket, OrderOpenPrice(), STprice, TPprice, LightGreen); } } } else { err = GetLastError(); Print("Error opening Sell order [" + setup + "]: (" + err + ") " + ErrorDescription(err)); } } //+------------------------------------------------------------------+ //| Check Open Position Controls | //+------------------------------------------------------------------+ int CheckOpenPositions() { int cnt, total, NumPositions; int NumBuyTrades, NumSellTrades; // Number of buy and sell trades in this symbol NumBuyTrades = 0; NumSellTrades = 0; total=OrdersTotal(); for(cnt=0;cnt 0) CloseCnt++; } else { CloseCnt = 3; } } } int ModifyOrder(int ord_ticket,double op, double price,double tp, color mColor) { int CloseCnt, err; CloseCnt=0; while (CloseCnt < 3) { if (OrderModify(ord_ticket,op,price,tp,0,mColor)) { CloseCnt = 3; } else { err=GetLastError(); Print(CloseCnt," Error modifying order : (", err , ") " + ErrorDescription(err)); if (err>0) CloseCnt++; } } } //+------------------------------------------------------------------+ //| HandleTrailingStop | //| Type 1 moves the stoploss without delay. | //| Type 2 waits for price to move the amount of the trailStop | //| before moving stop loss then moves like type 1 | //| Type 3 uses up to 3 levels for trailing stop | //| Level 1 Move stop to 1st level | //| Level 2 Move stop to 2nd level | //| Level 3 Trail like type 1 by fixed amount other than 1 | //| Type 4 Move stop to breakeven + Lockin, no trail | //| Type 5 uses steps for 1, every step pip move moves stop 1 pip | //| Type 6 Uses EMA to set trailing stop | //+------------------------------------------------------------------+ int HandleTrailingStop(int type, int ticket, double op, double os, double tp) { switch (TrailingStopType) { case 1 : Immediate_TrailingStop (type, ticket, op, os, tp); break; case 2 : Delayed_TrailingStop (type, ticket, op, os, tp); break; case 3 : ThreeLevel_TrailingStop (type, ticket, op, os, tp); break; case 4 : BreakEven_TrailingStop (type, ticket, op, os, tp); break; break; } return(0); } //+------------------------------------------------------------------+ //| BreakEvenExpert_v1.mq4 | //| Copyright © 2006, Forex-TSD.com | //| Written by IgorAD,igorad2003@yahoo.co.uk | //| http://finance.groups.yahoo.com/group/TrendLaboratory | //+------------------------------------------------------------------+ void BreakEven_TrailingStop(int type, int ticket, double op, double os, double tp) { int digits; double pBid, pAsk, BuyStop, SellStop; digits = MarketInfo(Symbol(), MODE_DIGITS); if (type==OP_BUY) { pBid = MarketInfo(Symbol(), MODE_BID); if ( pBid-op > myPoint*BreakEven ) { BuyStop = op + LockInPips * myPoint; if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits); BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop); if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen); return; } } if (type==OP_SELL) { pAsk = MarketInfo(Symbol(), MODE_ASK); if ( op - pAsk > myPoint*BreakEven ) { SellStop = op - LockInPips * myPoint; if (digits > 0) SellStop = NormalizeDouble( SellStop, digits); SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop); if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange); return; } } } //+------------------------------------------------------------------+ //| ThreeLevel_TrailingStop.mq4 | //| Copyright © 2006, Forex-TSD.com | //| Written by MrPip,robydoby314@yahoo.com | //| | //| Uses up to 3 levels for trailing stop | //| Level 1 Move stop to 1st level | //| Level 2 Move stop to 2nd level | //| Level 3 Trail like type 1 by fixed amount other than 1 | //+------------------------------------------------------------------+ void ThreeLevel_TrailingStop(int type, int ticket, double op, double os, double tp) { int digits; double pBid, pAsk, BuyStop, SellStop; digits = MarketInfo(Symbol(), MODE_DIGITS) ; if (type == OP_BUY) { pBid = MarketInfo(Symbol(), MODE_BID); if (pBid - op > FirstMove * myPoint) { BuyStop = op + FirstMove*myPoint - FirstStopLoss * myPoint; if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop); if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen); } if (pBid - op > SecondMove * myPoint) { BuyStop = op + SecondMove*myPoint - SecondStopLoss * myPoint; if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop); if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen); } if (pBid - op > ThirdMove * myPoint) { BuyStop = pBid - ThirdMove*myPoint; if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop); if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen); } } if (type == OP_SELL) { pAsk = MarketInfo(Symbol(), MODE_ASK); if (op - pAsk > FirstMove * myPoint) { SellStop = op - FirstMove * myPoint + FirstStopLoss * myPoint; if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop); if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange); } if (op - pAsk > SecondMove * myPoint) { SellStop = op - SecondMove * myPoint + SecondStopLoss * myPoint; if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop); if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange); } if (op - pAsk > ThirdMove * myPoint) { SellStop = pAsk + ThirdMove * myPoint; if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop); if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange); } } } //+------------------------------------------------------------------+ //| Immediate_TrailingStop.mq4 | //| Copyright © 2006, Forex-TSD.com | //| Written by MrPip,robydoby314@yahoo.com | //| | //| Moves the stoploss without delay. | //+------------------------------------------------------------------+ void Immediate_TrailingStop(int type, int ticket, double op, double os, double tp) { int digits; double pt, pBid, pAsk, BuyStop, SellStop; digits = MarketInfo(Symbol( ), MODE_DIGITS); if (type==OP_BUY) { pBid = MarketInfo(Symbol(), MODE_BID); pt = StopLoss * myPoint; if(pBid-os > pt) { BuyStop = pBid - pt; if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits); BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop); if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen); return; } } if (type==OP_SELL) { pAsk = MarketInfo(Symbol(), MODE_ASK); pt = StopLoss * myPoint; if(os - pAsk > pt) { SellStop = pAsk + pt; if (digits > 0) SellStop = NormalizeDouble( SellStop, digits); SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop); if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange); return; } } } //+------------------------------------------------------------------+ //| Delayed_TrailingStop.mq4 | //| Copyright © 2006, Forex-TSD.com | //| Written by MrPip,robydoby314@yahoo.com | //| | //| Waits for price to move the amount of the TrailingStop | //| Moves the stoploss pip for pip after delay. | //+------------------------------------------------------------------+ void Delayed_TrailingStop(int type, int ticket, double op, double os, double tp) { int digits; double pt, pBid, pAsk, BuyStop, SellStop; pt = TrailingStop * myPoint; digits = MarketInfo(Symbol(), MODE_DIGITS); if (type==OP_BUY) { pBid = MarketInfo(Symbol(), MODE_BID); BuyStop = pBid - pt; if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits); BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop); if (pBid-op > pt && os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen); return; } if (type==OP_SELL) { pAsk = MarketInfo(Symbol(), MODE_ASK); pt = TrailingStop * myPoint; SellStop = pAsk + pt; if (digits > 0) SellStop = NormalizeDouble( SellStop, digits); SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop); if (op - pAsk > pt && os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange); return; } } //+------------------------------------------------------------------+ //| Handle Open Positions | //| Check if any open positions need to be closed or modified | //| Three attempts are made to close or modify | //+------------------------------------------------------------------+ int HandleOpenPositions() { int cnt; bool YesClose; int myOrderType; for(cnt=OrdersTotal()-1;cnt>=0;cnt--) { OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES); if ( OrderSymbol() != Symbol()) continue; if ( OrderMagicNumber() != MagicNumber) continue; myOrderType = OrderType(); if(myOrderType == OP_BUY) { if (CheckExitCondition(OP_BUY)) { CloseOrder(OrderTicket(),OrderLots(),OP_BUY); } else { HandleTrailingStop(OP_BUY,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit()); } } if(myOrderType == OP_SELL) { if (CheckExitCondition(OP_SELL)) { CloseOrder(OrderTicket(),OrderLots(),OP_SELL); } else { HandleTrailingStop(OP_SELL,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit()); } } } } //+------------------------------------------------------------------+ //| Get number of lots for this trade | //+------------------------------------------------------------------+ double GetLots() { double lot; if(UseMoneyManagement == false) return(Lots); if (BrokerIsIBFX == true) { lot = Calc_IBFX_Money_Management(); return(lot); } // lot = LotsOptimized(); lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,2); // Use at least 1 micro lot if (AccountIsMicro == true) { lot = MathFloor(lot*100)/100; if (lot < 0.01) lot = 0.01; if (lot > MaxLot) lot = MaxLot; return(lot); } // Use at least 1 mini lot if(AccountIsMini == true) { lot = MathFloor(lot*10)/10; if (lot < 0.1) lot = 0.1; if (lot > MaxLot) lot = MaxLot; return(lot); } // Standard account if (lot >= 1.0) lot = MathFloor(lot); else lot = 1.0; if (lot > MaxLot) lot = MaxLot; return(lot); } double Calc_IBFX_Money_Management() { // variables used for money management double lot; lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,2); // Use at least 1 micro lot if (AccountIsMicro == true) { lot = lot * 10; lot = MathFloor(lot*100)/100; if (lot < 0.1) lot = 0.1; if (lot > MaxLot) lot = MaxLot; return(lot); } // Use at least 1 mini lot if(AccountIsMini == true) { lot = lot * 10; lot = MathFloor(lot*10)/10; if (lot < 1) lot = 1; if (lot > MaxLot) lot = MaxLot; return(lot); } // Standard Account lot = StrToDouble(DoubleToStr(lot, 2)); if (lot > MaxLot) lot = MaxLot; return(lot); } bool CheckTradeFilters() { bool myStop; myStop = false; if (myStop == false) { if (UseTradingHours == 1) { myStop = CheckTradingTimes(); } } return(myStop); } bool IsNotValidTradingTime( int StartHour, int EndHour) { int lHour=Hour() *100+Minute( ); if(StartHour<=EndHour) { if(lHourEndHour) return(true) ; } else if(lHour>EndHour && lHour