datetime expiryDate = D'2025.12.31 00:00'; //change as per your requirement //+------------------------------------------------------------------+ //| MT-MoonLight EA V1.1.mq4 | //| | //| | //+------------------------------------------------------------------+ #include #property copyright "Copyright 2020" #property link "" #property version "1.10" #property strict enum mm { fixed_lot, //Use Fixed Lots use_percentage //Use Risk Percentage }; enum add { both = 0, // Buys and Sells buys = 1, // Buys only sells = 2, // Sells only none = 3 // None }; extern int Stoch_K_Period=14; extern int Stoch_D_Period=6; extern int Stoch_Slowing=6; extern ENUM_MA_METHOD Stoch_MA_Method=MODE_SMA; extern ENUM_STO_PRICE Stoch_Price_Field=STO_LOWHIGH; extern string EA_Name="MT-MoonLight"; //EA Name extern mm money_management=0; //Use Fixed Lots or Risk % extern double order_lot=0.1; //Fixed LotSize extern double risk_percent=1; //Risk Percent extern double take_profit=20; //Fixed takeprofit in pips (0=no takeprofit) extern double stop_loss=80; //Fixed stoploss in pips (0=no stoploss) extern string start_trading_time="00:00"; //Trade Start Time extern string end_trading_time="23;59"; //Trade Stop Time extern bool enable_friday_close=true; //Enable Friday Exit Trades extern string friday_close_time="22:00"; //Friday Exit Time extern int max_trades=1; //Maximum Open Trades extern double total_profit_day=100; //Total Profit per day (in $) and Stop extern double total_loss_day=200; //Total Loss per day (in $) and Stop extern bool show_info=true; //Info Display extern int x_dist=7; extern int y_dist=17; extern int magic_number=1119202; //Magic Number input string newvars = "New Parameters:"; // ______________ input bool CloseOnDD = true; // Close on DD input int CloseForHours = 24; // Hours to stop after DD input double AmountDD = 100; // Loss in $ input double PercentDD = 10; // Loss in % from Equity input bool IncreaseLotsOnLoss = true; // Increase Lots after Loss input double LossPercent = 100; // Loss % to be covered input int MaxIncrease = 4; // Max Increase Steps input add AditionalPos = 0; // Aditional Positions input double AditionalPosLoss = 20; // Loss pips for Aditional Position input double AditionalPossLossPrc = 10; // Loss % of Equity for Aditional Position static datetime LastDDclose; double MaxEquity,dist; int magic_number1; int order_type,ress; int slippage=5; //Allowed slippage of open/close order int bar=1; int timeframe=0; int number_retry_open_trade=10; double myPoint, mySpread, myStopLevel,myTickValue,myTickSize,myLotValue; double myDigits; datetime TradeBarTime; bool enable_ea; double my_lots,temp_lots; int digit_lot; int signal; int signalclose; int myBars; double last_history_check; string TradeCode="MT-MoonLight_EA1.1"; int err; double lotsize=0; double profit=0; double price_op=0; double price_tp=0; double price_sl=0; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- if(!IsTesting())ExpertRemove(); if (TimeCurrent() > expiryDate) Alert(" ** INVALID EA ** "); if (TimeCurrent() > expiryDate) return(0); SetPoint(); if(Digits==3 || Digits==5) slippage*=10; if(MarketInfo(Symbol(),MODE_LOTSTEP)>=0.01) digit_lot=2; if(MarketInfo(Symbol(),MODE_LOTSTEP)>=0.1) digit_lot=1; if(MarketInfo(Symbol(),MODE_LOTSTEP)>=1) digit_lot=0; TradeBarTime=Time[0]; TradeCode=EA_Name; magic_number1 = magic_number+1; //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- for(int i=0;i expiryDate) Alert(" ** INVALID EA ** "); if (TimeCurrent() > expiryDate) return; double sl,tp; int openticket1; int openticket2; double openprice1; double openprice2; double stop; bool enableopen = true; if(CloseOnDD) { if(AccountEquity()>MaxEquity)MaxEquity=AccountEquity(); if(LastDDclose+CloseForHours*60*60>TimeCurrent()) { enableopen=false; } if(MaxEquity-AccountEquity()>AmountDD && enableopen) { CloseTrades(OP_BUY); CloseTrades(OP_SELL); LastDDclose=TimeCurrent(); MaxEquity=AccountEquity(); Alert("DD Ammount hit - Closed all trades and disable trading for "+IntegerToString(CloseForHours)+" hours."); enableopen=false; } if(MaxEquity-AccountEquity()>MaxEquity*PercentDD/100 && enableopen) { CloseTrades(OP_BUY); CloseTrades(OP_SELL); LastDDclose=TimeCurrent(); MaxEquity=AccountEquity(); Alert("% DD hit - Closed All trades and disable trading for "+IntegerToString(CloseForHours)+" hours."); enableopen=false; } } get_open_trade(); my_lots=order_lot; if(money_management==1 && stop_loss==0) { double my_lots2; my_lots2=(AccountBalance()*risk_percent*0.01)/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)); my_lots=NormalizeDouble(my_lots2,digit_lot); } else if(money_management && stop_loss>0) { double my_lots2; stop=stop_loss; if(Digits==3 || Digits==5) my_lots2=(AccountBalance()*risk_percent*0.01)/(stop * myTickValue*10); else my_lots2=(AccountBalance()*risk_percent*0.01)/(stop * myTickValue); my_lots=NormalizeDouble(my_lots2,digit_lot); } if((AditionalPos==0 || AditionalPos==1) && lotsize!=0 && TotalAdded()==0 && profit<0) { dist = MathAbs(profit/lotsize/MarketInfo(OrderSymbol(),MODE_TICKVALUE)/10); if(order_type==0 && ((dist>=AditionalPosLoss && dist=stop_loss*AditionalPossLossPrc/100 && dist<=stop_loss*AditionalPossLossPrc/100+5))) { ress=OrderSend(Symbol(),OP_BUY,my_lots,Ask,slippage,price_sl,price_tp,IntegerToString(magic_number1),magic_number1,0,clrBlue); Print("Added Buy pips reached"); } } if((AditionalPos==0 || AditionalPos==2) && lotsize!=0 && TotalAdded()==0 && profit<0) { dist = MathAbs(profit/lotsize/MarketInfo(OrderSymbol(),MODE_TICKVALUE)/10); if(order_type==1 && ((dist>=AditionalPosLoss && dist=stop_loss*AditionalPossLossPrc/100 && dist<=stop_loss*AditionalPossLossPrc/100+5))) { ress=OrderSend(Symbol(),OP_SELL,my_lots,Bid,slippage,price_sl,price_tp,IntegerToString(magic_number1),magic_number1,0,clrRed); Print("Added Sell pips reached"); } } int gap_v=18; int text_size=10; color text_color=clrWhite; if(show_info) { string strcomment=""; string nl="\n"; DrawRectLabel(0,TradeCode+"_RectLabel",0,x_dist-2,y_dist-2,220,180, clrBlack,BORDER_RAISED,0,clrWhite,STYLE_SOLID,1,false); DrawLabel(TradeCode+"_ea_name",EA_Name,x_dist+10, y_dist+(gap_v*0),text_color,text_size,0); DrawLabel(TradeCode+"_acc_bal","Account Balance = $ "+ DoubleToStr(AccountBalance(),2),x_dist+10, y_dist+(gap_v*1),text_color,text_size,0); if(CountOpenOrders(OP_BUY)+CountOpenOrders(OP_SELL)>0) { lotsize=0; profit=0; price_op=0; price_sl=0; price_tp=0; get_open_trade(); DrawLabel(TradeCode+"_lotsize","Lot Size = "+ DoubleToStr(lotsize,digit_lot),x_dist+10, y_dist+(gap_v*2),text_color,text_size,0); DrawLabel(TradeCode+"_openprice","Open Price = -"+ DoubleToStr(price_op,Digits()),x_dist+10, y_dist+(gap_v*3),text_color,text_size,0); DrawLabel(TradeCode+"_takeprofit","Take Profit = -"+ DoubleToStr(price_tp,Digits()),x_dist+10, y_dist+(gap_v*4),text_color,text_size,0); DrawLabel(TradeCode+"_stoploss","Stop Loss = -"+DoubleToStr(price_sl,Digits()),x_dist+10, y_dist+(gap_v*5),text_color,text_size,0); DrawLabel(TradeCode+"_profit","Profit = "+ DoubleToStr(profit,2),x_dist+10, y_dist+(gap_v*6),text_color,text_size,0); DrawLabel(TradeCode+"_maxdd","Max DD = "+ DoubleToStr(AmountDD,2)+"$/"+DoubleToStr(MaxEquity*PercentDD/100,2)+"$",x_dist+10, y_dist+(gap_v*8),text_color,text_size,0); } else if(CountOpenOrders(OP_BUY)+CountOpenOrders(OP_SELL)==0) { DrawLabel(TradeCode+"_lotsize","Lot Size = -",x_dist+10, y_dist+(gap_v*2),text_color,text_size,0); DrawLabel(TradeCode+"_openprice","Open Price = -",x_dist+10, y_dist+(gap_v*3),text_color,text_size,0); DrawLabel(TradeCode+"_takeprofit","Take Profit = -",x_dist+10, y_dist+(gap_v*4),text_color,text_size,0); DrawLabel(TradeCode+"_stoploss","Stop Loss = -",x_dist+10, y_dist+(gap_v*5),text_color,text_size,0); DrawLabel(TradeCode+"_profit","Profit = -",x_dist+10, y_dist+(gap_v*6),text_color,text_size,0); DrawLabel(TradeCode+"_maxdd","Max DD = "+ DoubleToStr(AmountDD,2)+"$/"+DoubleToStr(MaxEquity*PercentDD/100,2)+"$",x_dist+10, y_dist+(gap_v*8),text_color,text_size,0); } DrawLabel(TradeCode+"_total_profit","Total Profit = $ "+ DoubleToStr(sum_profit(),2),x_dist+10, y_dist+(gap_v*7),text_color,text_size,0); } if(total_loss_day>0 || total_profit_day>0) { double sumprofitday=sum_profit_day(); if(total_profit_day>0 && sumprofitday>=total_profit_day) { if(CountOpenOrders(OP_BUY)+CountOpenOrders(OP_SELL)>0) { CloseTrades(OP_BUY); CloseTrades(OP_SELL); CloseTrades(OP_BUY); CloseTrades(OP_SELL); CloseTrades(OP_BUY); CloseTrades(OP_SELL); } enableopen=false; } if(total_loss_day>0 && sumprofitday<=0-total_loss_day) { if(CountOpenOrders(OP_BUY)+CountOpenOrders(OP_SELL)>0) { CloseTrades(OP_BUY); CloseTrades(OP_SELL); CloseTrades(OP_BUY); CloseTrades(OP_SELL); CloseTrades(OP_BUY); CloseTrades(OP_SELL); } enableopen=false; } } if(isNewCandle()) { signal=signal(); } int sep; int sh1,sm1,eh1,em1; sep=0; sep=StringFind(start_trading_time,":"); sh1=StrToInteger(StringSubstr(start_trading_time,0,sep)); sm1=StrToInteger(StringSubstr(start_trading_time,sep+1)); sep=0; sep=StringFind(end_trading_time,":"); eh1=StrToInteger(StringSubstr(end_trading_time,0,sep)); em1=StrToInteger(StringSubstr(end_trading_time,sep+1)); if(!istradinghours(sh1,eh1,sm1,em1)) enableopen=false; if(enable_friday_close && TimeDayOfWeek(TimeCurrent())==5) { int fh1,fm1; sep=0; sep=StringFind(friday_close_time,":"); fh1=StrToInteger(StringSubstr(friday_close_time,0,sep)); fm1=StrToInteger(StringSubstr(friday_close_time,sep+1)); if(istradinghours(fh1,24,fm1,0)) { if(CountOpenOrders(OP_BUY)+CountOpenOrders(OP_SELL)>0) { CloseTrades(OP_BUY); CloseTrades(OP_SELL); } enableopen=false; return; } } if(signal!=30) { datetime lastclosetime=last_close_time(); if(iBarShift(Symbol(),timeframe,lastclosetime)==0 && lastclosetime>0) enableopen=false; } if(enableopen) if(TradeBarTime!=Time[0]) if(signal!=30 ) { if(CountOpenOrders(OP_BUY)+CountOpenOrders(OP_SELL)0) { double my_lots2; stop=stop_loss; if(Digits==3 || Digits==5) my_lots2=(AccountBalance()*risk_percent*0.01)/(stop * myTickValue*10); else my_lots2=(AccountBalance()*risk_percent*0.01)/(stop * myTickValue); my_lots=NormalizeDouble(my_lots2,digit_lot); } if(IncreaseLotsOnLoss && CompoundLossCount()>0) { temp_lots = (CompoundLoss()*LossPercent/100)/(take_profit*MarketInfo(Symbol(),MODE_TICKVALUE))/10; if(MaxIncrease<=CompoundLossCount()-1)temp_lots=my_lots; if(temp_lotsMarketInfo(Symbol(),MODE_MAXLOT)) my_lots=MarketInfo(Symbol(),MODE_MAXLOT); if(signal==10) { openprice1=Ask; sl=setSL(openprice1,stop_loss); tp=setTP(openprice1,take_profit); openticket1=Open_Trade(Symbol(),OP_BUY,openprice1, my_lots,sl, tp, TradeCode); if(openticket1>0) { Alert("Buy Alert "+ Symbol()+ " " + strtf(Period()) + " Date & Time: " + TimeToStr(TimeCurrent(),TIME_DATE)+" "+TimeToStr(TimeCurrent(),TIME_MINUTES) + " - " + WindowExpertName()); DrawArrow("arr_up"+IntegerToString(iTime(Symbol(),timeframe,1)),iLow(Symbol(),timeframe,1)-(5*myPoint),iTime(Symbol(),timeframe,1),clrLime,1,233); DrawLine(TradeCode+"_TP_LINE",tp,clrLime); DrawLine(TradeCode+"_SL_LINE",sl,clrRed); } } if(signal==20) { openprice2=Bid; sl=setSL(openprice2,0-stop_loss); tp=setTP(openprice2,0-take_profit); openticket2=Open_Trade(Symbol(),OP_SELL,openprice2, my_lots,sl, tp, TradeCode); if(openticket2>0) { Alert("Sell Alert "+ Symbol()+ " " + strtf(Period()) + " Date & Time: " + TimeToStr(TimeCurrent(),TIME_DATE)+" "+TimeToStr(TimeCurrent(),TIME_MINUTES) + " - " + WindowExpertName()); DrawArrow("arr_dn"+IntegerToString(iTime(Symbol(),timeframe,1)),iHigh(Symbol(),timeframe,1)+(5*myPoint),iTime(Symbol(),timeframe,1),clrRed,1,234); DrawLine(TradeCode+"_TP_LINE",tp,clrLime); DrawLine(TradeCode+"_SL_LINE",sl,clrRed); } } } } //---- } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //+-------------------------General Functions------------------------+ //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ double setTP(double open, double tp_pips) { if(tp_pips==0) return(0); else return(NormalizeDouble(open+(tp_pips*myPoint),Digits)); } double setSL(double open, double sl_pips) { if(sl_pips==0) return(0); else return(NormalizeDouble(open-(sl_pips*myPoint),Digits)); } int signal() { double stm1=iStochastic(Symbol(),timeframe,Stoch_K_Period,Stoch_D_Period,Stoch_Slowing,Stoch_MA_Method,Stoch_Price_Field,MODE_MAIN,bar); double sts1=iStochastic(Symbol(),timeframe,Stoch_K_Period,Stoch_D_Period,Stoch_Slowing,Stoch_MA_Method,Stoch_Price_Field,MODE_SIGNAL,bar); double stm2=iStochastic(Symbol(),timeframe,Stoch_K_Period,Stoch_D_Period,Stoch_Slowing,Stoch_MA_Method,Stoch_Price_Field,MODE_MAIN,bar+1); double sts2=iStochastic(Symbol(),timeframe,Stoch_K_Period,Stoch_D_Period,Stoch_Slowing,Stoch_MA_Method,Stoch_Price_Field,MODE_SIGNAL,bar+1); if(stm1=sts2) return(10); if(stm1>sts1 && stm2<=sts2) return(20); return(30); } datetime last_close_time() { int i; datetime closetime=0; for(i=OrdersHistoryTotal()-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==True) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic_number) { if(closetime==0 || closetime= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==True) { if(OrderSymbol()==Symbol() && (OrderMagicNumber()==magic_number || OrderMagicNumber()==magic_number1)) { sum=sum+OrderProfit(); } } } for (i=OrdersHistoryTotal()-1; i >= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==True) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic_number) { sum=sum+OrderProfit(); } } } return(sum); } double sum_profit_day() { double sum=0; int i=0; for (i=OrdersTotal()-1; i >= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==True) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic_number) { if(TimeDay(OrderOpenTime())==TimeDay(TimeCurrent()) && TimeMonth(OrderOpenTime())==TimeMonth(TimeCurrent()) && TimeYear(OrderOpenTime())==TimeYear(TimeCurrent())) { sum=sum+OrderProfit()+OrderCommission()+OrderSwap(); } } } } for (i=OrdersHistoryTotal()-1; i >= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==True) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic_number) { if(TimeDay(OrderCloseTime())==TimeDay(TimeCurrent()) && TimeMonth(OrderCloseTime())==TimeMonth(TimeCurrent()) && TimeYear(OrderCloseTime())==TimeYear(TimeCurrent())) { sum=sum+OrderProfit()+OrderCommission()+OrderSwap(); } } } } return(sum); } void get_open_trade() { double sum=0; int i=0; for (i=OrdersTotal()-1; i >= 0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==True) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic_number) { lotsize=OrderLots(); profit=OrderProfit(); price_op=OrderOpenPrice(); price_sl=OrderStopLoss(); price_tp=OrderTakeProfit(); order_type = OrderType(); } } } } void SetPoint() { myPoint = MarketInfo(Symbol(),MODE_POINT); mySpread = MarketInfo(Symbol(),MODE_SPREAD); myDigits = MarketInfo(Symbol(),MODE_DIGITS); myStopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL); myTickValue = MarketInfo(Symbol(),MODE_TICKVALUE); myTickSize = MarketInfo(Symbol(),MODE_TICKSIZE); myLotValue = myTickValue/myTickSize; if( myDigits==3 || myDigits==5 ) { myPoint = myPoint * 10; mySpread = mySpread / 10; myStopLevel = myStopLevel / 10; myDigits = myDigits -1; } } //+------------------------------------------------------------------+ //+----------------------Trading Hours-------------------------------+ bool istradinghours(int starthour, int endhour, int startminute=0, int endminute=0, int shift = 0) { int nowtime = (Hour()+shift)*60 + Minute(); if (nowtime < 0) nowtime += 1440; if (nowtime >= 1440) nowtime -= 1440; int starttime = starthour*60 + startminute; int endtime = endhour*60 + endminute; if (starttime <= endtime) { if ((nowtime < starttime) || (nowtime >= endtime)) return(false); } else { if ((nowtime < starttime) && (nowtime >= endtime)) return(false); } return(true); } //+------------------------------------------------------------------+ //+------------------Count Number of Open Orders---------------------+ int CountOpenOrders(int direction) { int i,j; j = 0; for(i=OrdersTotal()-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==True) { if( OrderType() == direction && OrderSymbol() == Symbol() && OrderMagicNumber() == magic_number ) j++; } else Print("Could not SELECT trade"); } return(j); } //+------------------------------------------------------------------+ //+-------------------Close Trades by Symbol()-------------------------+ int CloseTrades(int direction) { int j; //double ClosePrice; j = 0; int x; int status; if(direction==-1) return(0); for(int cnt=OrdersTotal()-1;cnt>=0;cnt--) { if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)==True) { if(OrderSymbol()==Symbol() && (OrderMagicNumber()==magic_number || OrderMagicNumber()==magic_number1)) if(OrderType()==direction) { if(OrderType()==OP_BUY) { for (x = 5; x!= 0; x--) { while (IsTradeContextBusy() || !IsTradeAllowed()) Sleep(5000); status = OrderClose(OrderTicket(),OrderLots(),Bid,0); if (status == 1) { j++; break; } } } else if(OrderType()==OP_BUYLIMIT) { for (x = 5; x!= 0; x--) { while (IsTradeContextBusy() || !IsTradeAllowed()) Sleep(5000); status = OrderDelete(OrderTicket()); if (status == 1) { j++; break; } } } else if(OrderType()==OP_BUYSTOP) { for (x = 5; x!= 0; x--) { while (IsTradeContextBusy() || !IsTradeAllowed()) Sleep(5000); status = OrderDelete(OrderTicket()); if (status == 1) { j++; break; } } } if(OrderType()==OP_SELL) { for (x = 5; x!= 0; x--) { while (IsTradeContextBusy() || !IsTradeAllowed()) Sleep(5000); status = OrderClose(OrderTicket(),OrderLots(),Ask,0); if (status == 1) { j++; break; } } } else if(OrderType()==OP_SELLLIMIT) { for (x = 5; x!= 0; x--) { while (IsTradeContextBusy() || !IsTradeAllowed()) Sleep(5000); status = OrderDelete(OrderTicket()); if (status == 1) { j++; break; } } } else if(OrderType()==OP_SELLSTOP) { for (x = 5; x!= 0; x--) { while (IsTradeContextBusy() || !IsTradeAllowed()) Sleep(5000); status = OrderDelete(OrderTicket()); if (status == 1) { j++; break; } } } } } } return(j); } //+------------------------------------------------------------------+ //+----------------Modify Profit Target and Stop Loss----------------+ bool ModifyProfitTarget(int myTicket, double ProfitTarget, double StopLoss) { int try; string strerr=""; if(OrderSelect(myTicket,SELECT_BY_TICKET,MODE_TRADES)==False) return(false); if( ( MathRound(ProfitTarget/Point) != MathRound(OrderTakeProfit()/Point) || MathRound(StopLoss/Point) != MathRound(OrderStopLoss()/Point) ) ) { //RefreshRates(); for(try=1;try<=5;try++) { if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(StopLoss,Digits),NormalizeDouble(ProfitTarget,Digits),OrderExpiration())) return(true); else{ err=GetLastError(); strerr=IntegerToString(err); Print("OrderModify Error # " + strerr + " : ",ErrorDescription(err)); } } } return(false); } //+------------------------------------------------------------------+ //+----------------------OPEN TRADE----------------------------------+ int Open_Trade(string curr,int cmd,double price, double lot,double sl, double tp, string comm) { string strerr=""; int ticket=0; int retry=0; color colour=CLR_NONE; sl=NormalizeDouble(sl,Digits); tp=NormalizeDouble(tp,Digits); price=NormalizeDouble(price,Digits); if(cmd==0) colour=Blue; if(cmd==1) colour=Red; if(Digits==3 || Digits==5) { for(retry=1;retry<=number_retry_open_trade;retry++) { RefreshRates(); ticket=OrderSend(curr,cmd,lot,price,slippage,0,0,comm,magic_number,0,colour); if(ticket>0) break; else { err=GetLastError(); strerr=IntegerToString(err); Print("OrderSend Error # " + strerr + " : ",ErrorDescription(err)); } } } else { for(retry=1;retry<=number_retry_open_trade;retry++) { RefreshRates(); ticket=OrderSend(curr,cmd,lot,price,slippage,sl,tp,comm,magic_number,0,colour); if(ticket>0) break; else { err=GetLastError(); strerr=IntegerToString(err); Print("OrderSend Error # " + strerr + " : ",ErrorDescription(err)); } } } if(ticket>0) { if(Digits==3 || Digits==5) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) for(retry=1;retry<=number_retry_open_trade;retry++) { if(ModifyProfitTarget(ticket, tp, sl)) break; } } TradeBarTime=Time[0]; return(ticket); } return(0); } bool isNewCandle() { bool res=false; if (myBars!=Bars) { myBars=Bars; res=true; } return(res); } //+------------------------------------------------------------------+ //+-----------------------------Draw Line----------------------------+ void DrawLine(string sName, double dPrice,color cLineClr=CLR_NONE) { int iWidth=1; string sObjName = sName; if(ObjectFind(sObjName) == -1){ // create object ObjectCreate(sObjName,OBJ_HLINE, 0, 0,0); } ObjectSet(sObjName,OBJPROP_PRICE1,dPrice); ObjectSet(sObjName, OBJPROP_COLOR, cLineClr); ObjectSet(sObjName, OBJPROP_WIDTH, iWidth); } //+------------------------------------------------------------------+ //+---------------------------Get Line Price-------------------------+ double GetHLineValue(string name) { if (ObjectFind(name) == -1) return(-1); else return(ObjectGet(name,OBJPROP_PRICE1)); } string strtf(int tf) { switch(tf) { case PERIOD_M1: return("M1"); case PERIOD_M5: return("M5"); case PERIOD_M15: return("M15"); case PERIOD_M30: return("M30"); case PERIOD_H1: return("H1"); case PERIOD_H4: return("H4"); case PERIOD_D1: return("D1"); case PERIOD_W1: return("W1"); case PERIOD_MN1: return("MN1"); default:return("Unknown timeframe"); } } //+------------------------------------------------------------------+ //+---------------Traling Stop Function for Buy Position-------------+ void TrailingPositionsBuy(double trailingStart, double trailingStop, double trailingStep) { for(int i=0;i=trailingStart) { if(((OrderStopLoss()+0)/myPoint)<=((Bid-((trailingStop+trailingStep)*myPoint))/myPoint) || OrderStopLoss()==0) { int ret=ModifyProfitTarget(OrderTicket(), OrderTakeProfit(), ordersl+(trailingStep*myPoint)); if(ret>0) Print("Modify at " + DoubleToStr(ordersl+(trailingStep*myPoint),Digits) + " - Bid at " + DoubleToStr(Bid,Digits)); } } } } } } //+------------------------------------------------------------------+ //+---------------Traling Stop Function for Sell Position-------------+ void TrailingPositionsSell(double trailingStart, double trailingStop, double trailingStep) { for(int i=0;i=trailingStart) { if(((OrderStopLoss()-0)/myPoint)>=((Ask+((trailingStop+trailingStep)*myPoint))/myPoint) || OrderStopLoss()==0) { int ret=ModifyProfitTarget(OrderTicket(), OrderTakeProfit(),ordersl-(trailingStep*myPoint)); if(ret>0) Print("Modify at " + DoubleToStr(ordersl-(trailingStep*myPoint),Digits) + " - Ask at " + DoubleToStr(Ask,Digits)); } } } } } } //+------------------------------------------------------------------+ //+------------------------BreakEven Function------------------------+ void HandleBreakEven(double breakeven, double breakeven_plus_pips) { for(int x = 0; x < OrdersTotal(); x++) { if(OrderSelect(x, SELECT_BY_POS, MODE_TRADES)) if(OrderSymbol() == Symbol() && OrderMagicNumber() == magic_number) { if(OrderType() == OP_BUY) { if(Bid >= OrderOpenPrice() + breakeven*myPoint && (OrderStopLoss() < OrderOpenPrice() || OrderStopLoss()==0)/* && NormalizeDouble(OrderStopLoss(),myDigits)!=NormalizeDouble(OrderOpenPrice() + BreakEvenPipsToProtect*myPoint,myDigits)*/) { ModifyProfitTarget(OrderTicket(), OrderTakeProfit(),NormalizeDouble(OrderOpenPrice() + breakeven_plus_pips*myPoint,Digits)); } } else if(OrderType() == OP_SELL) { if(Ask <= OrderOpenPrice() - breakeven*myPoint && (OrderStopLoss() > OrderOpenPrice() || OrderStopLoss()==0) /*&& NormalizeDouble(OrderStopLoss(),myDigits)!=NormalizeDouble(OrderOpenPrice() - BreakEvenPipsToProtect*myPoint,myDigits)*/) { ModifyProfitTarget(OrderTicket(), OrderTakeProfit(),NormalizeDouble(OrderOpenPrice() - breakeven_plus_pips*myPoint,Digits)); } } } } } void DrawLabel(string sName, string strText, double xAxis, double yAxis, color cLineClr=CLR_NONE, int size=1, int corner=0) { string sObjName = sName; if(ObjectFind(sObjName) == -1){ // create object ObjectCreate(sObjName,OBJ_LABEL, 0, 0,0); } ObjectSetText(sObjName,strText,size); ObjectSet(sObjName,OBJPROP_XDISTANCE,xAxis); ObjectSet(sObjName,OBJPROP_YDISTANCE,yAxis); ObjectSet(sObjName,OBJPROP_CORNER,corner); ObjectSet(sObjName, OBJPROP_COLOR, cLineClr); } void DrawArrow(string Name, double price, datetime time , color myColor, int size, int arrowcode) { int win_number=0; ObjectCreate(Name,OBJ_ARROW,win_number,0,0); ObjectSet(Name,OBJPROP_ARROWCODE,arrowcode); ObjectSet(Name,OBJPROP_PRICE1,price); ObjectSet(Name,OBJPROP_TIME1,time); ObjectSet(Name,OBJPROP_COLOR, myColor); ObjectSet(Name,OBJPROP_WIDTH, size); return; } bool DrawRectLabel(const long chart_ID=0, // chart's ID const string name="RectLabel", // label name const int sub_window=0, // subwindow index const int x=0, // X coordinate const int y=0, // Y coordinate const int width=50, // width const int height=18, // height const color back_clr=C'236,233,216', // background color const ENUM_BORDER_TYPE border=BORDER_SUNKEN, // border type const ENUM_BASE_CORNER base_corner=CORNER_LEFT_UPPER, // chart corner for anchoring const color clr=clrRed, // flat border color (Flat) const ENUM_LINE_STYLE style=STYLE_SOLID, // flat border style const int line_width=1, // flat border width const bool back=false, // in the background const bool selection=false, // highlight to move const bool hidden=true, // hidden in the object list const long z_order=0) // priority for mouse click { //--- reset the error value ResetLastError(); //--- create a rectangle label if(ObjectFind(0,name)==-1) { if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE_LABEL,sub_window,0,0)) { Print(__FUNCTION__, ": failed to create a rectangle label! Error code = ",GetLastError()); return(false); } } //--- set label coordinates ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x); ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y); //--- set label size ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width); ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height); //--- set background color ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr); //--- set border type ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border); //--- set the chart's corner, relative to which point coordinates are defined ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,base_corner); //--- set flat border color (in Flat mode) ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr); //--- set flat border line style ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style); //--- set flat border width ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,line_width); //--- display in the foreground (false) or background (true) ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back); //--- enable (true) or disable (false) the mode of moving the label by mouse ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection); ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection); //--- hide (true) or display (false) graphical object name in the object list ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden); //--- set the priority for receiving the event of a mouse click in the chart ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order); //--- successful execution return(true); } double CompoundLoss() { double result = 0; for(int i=OrdersHistoryTotal()-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) { if(OrderMagicNumber()==magic_number && OrderSymbol()==Symbol() && OrderProfit()>0)break; if(OrderMagicNumber()==magic_number && OrderSymbol()==Symbol() && OrderProfit()<0)result+=OrderProfit(); } else { Print("OrderSelect error "+IntegerToString(GetLastError())); } } result = MathAbs(result); return (result); } int CompoundLossCount() { int result = 0; for(int i=OrdersHistoryTotal()-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) { if(OrderMagicNumber()==magic_number && OrderSymbol()==Symbol() && OrderProfit()>0)break; if(OrderMagicNumber()==magic_number && OrderSymbol()==Symbol() && OrderProfit()<0)result++; } else { Print("OrderSelect error "+IntegerToString(GetLastError())); } } return (result); } int TotalAdded () { int result=0; for(int i=0;i