New version after the advice I received from the forum experts
Program for MT4
Backtest and check before use. (I am not a coder and I did my best)
I added a lot of constraints to secure it, as well as a trailing start
Stop loss and take profit are dynamic and adapted to volatility.
The size of the lots is automatically adjusted according to the ... "equity"
It does not trade if the spread rises above 10 ...... etc
Please tell me if other corrections or improvements need to be made before I run on my platform
//+------------------------------------------------------------------+ //| Scalper-GG-14.mq4 | //| Copyright 2020, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ #property copyright "Copyright 2020, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.00" #property strict //+------------------------------------------------------------------+ extern string mn="Scalper-GG-14"; double lot; extern int shifthighrecent=5; extern int shiftlowrecent=2; extern int shifthigh=5; extern int shiftlow=7; extern bool trail=true; extern int TrailingStop=2; extern int barnumber =24; extern int barnumberrecent=33; extern int MagicNumber=14072020; //extern double TakeProfit=53; extern double atrMultiple = 3; extern int TrailingStart=21; double stoplevel=(MarketInfo(Symbol(),MODE_STOPLEVEL))/10; int TS=TrailingStart-TrailingStop; extern int volume1=1; extern int volume0=0; extern int adxperiod= 31; extern int adxthreshold=23; extern int rsiperiod=21; extern int rsilower =48; extern int rsiupper =80; extern int Slippage=3; extern int Indicatorperiod = 14; input int MaxSpreadAllow = 10; // Enter Maximum allowed spread extern double LotFactor =134; //lotsize factor extern int ecartask=2; extern int ecartbid=10; extern int Start_Time = 0; // Time to allow trading to start ( hours of 24 hr clock ) 0 for both disables extern int Finish_Time = 0; // Time to stop trading ( hours of 24 hr clock ) 0 for both disables extern double bidbid =600; extern double askask =300; //+------------------------------------------------------------------+ // expert start function //+------------------------------------------------------------------+ int start() { if(TimeHour(TimeCurrent())>=Start_Time && TimeHour(TimeCurrent())<=Finish_Time )return(0); double MyPoint=Point; if(Digits==3 || Digits==5) MyPoint=Point*10; double TheStopLoss=0; double TheTakeProfit=0; double booster = Volume[volume1]> Volume[volume0] &&iADX(Symbol(),0,adxperiod,PRICE_CLOSE,MODE_MAIN,0)> adxthreshold &&iRSI(Symbol(),0,rsiperiod,PRICE_CLOSE,0)>rsilower && iRSI(Symbol(),0,rsiperiod,PRICE_CLOSE,0)<rsiupper ; static datetime tmeBar0; bool newBar = false; if ( tmeBar0 != Time[0] ) { tmeBar0 = Time[0]; newBar = true; } // Get Ask and Bid for the currency double ask = MarketInfo ( Symbol(), MODE_ASK ); double bid = MarketInfo ( Symbol(), MODE_BID ); double Spread = MarketInfo(Symbol(), MODE_SPREAD); // This will Obtain broker Spread for current pair if(Spread > 0 && Spread <= MaxSpreadAllow) // This part compares broker spread with maximum allowed spread, and refuse trade if maxSpread is exceeded if ( OrdersTotal () == 0 ) if(AccountFreeMargin()>(1000*(AccountEquity() * 0.01 /LotFactor))) if(booster) //+------------------------------------------------------------------+ // Dynamic stoploss and takeprofit //+------------------------------------------------------------------+ double ema = iMA(NULL, 0, 300, 0, MODE_EMA, PRICE_CLOSE, 0); double atr = iATR(NULL, 0, 3, 0); double StopLoss = (int)(atr * atrMultiple / Point); double TakeProfit = StopLoss; //+------------------------------------------------------------------+ // //+------------------------------------------------------------------+ new_del () ; if( TotalOrdersCount()==0 ) { int result=0; //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ // Here is your open buy rule//Ici votre strategie d'achat double HighOfLastBarsrecent = iHigh ( Symbol (), PERIOD_M1 , iHighest ( Symbol (), PERIOD_M1 , MODE_HIGH, barnumberrecent , shifthighrecent )); double LowOfLastBarsrecent = iLow ( Symbol (), PERIOD_M1 , iLowest ( Symbol (), PERIOD_M1 , MODE_LOW, barnumberrecent , shiftlowrecent )); double HighOfLastBars = iHigh ( Symbol (), PERIOD_M1 , iHighest ( Symbol (), PERIOD_M1 , MODE_HIGH, barnumber , shifthigh )); double LowOfLastBars = iLow ( Symbol (), PERIOD_M1 , iLowest ( Symbol (), PERIOD_M1 , MODE_LOW, barnumber , shiftlow )); double AverageBars=(HighOfLastBars +LowOfLastBars)/2 ; double PartialLow=((LowOfLastBars+AverageBars)/2); double PartialHigh = ((HighOfLastBars+AverageBars)/2); // Calculate a channel on Moving Averages, and check the price double iMaLow = iMA ( Symbol(), PERIOD_M1, Indicatorperiod, 0, MODE_LWMA, PRICE_LOW, 0 ); double iMaHigh = iMA ( Symbol(), PERIOD_M1, Indicatorperiod, 0, MODE_LWMA, PRICE_HIGH, 0 ); double iMaAverage = (iMaHigh + iMaLow)/2; double PartialiMalow = (iMaLow + iMaAverage) / 2.0; double PartialiMahigh =(iMaHigh + iMaAverage) / 2.0; double UpperPart=(PartialiMahigh+PartialHigh)/2; double LowerPart= ( PartialiMalow+ PartialLow)/2; if (((bid>= PartialiMahigh )&&(bid>= PartialHigh )&&(booster))) if (bid>= HighOfLastBars ) if (HighOfLastBarsrecent>= HighOfLastBars) //+------------------------------------------------------------------+ // Dynamic stoploss and takeprofit //+------------------------------------------------------------------+ double ema = iMA(NULL, 0, 300, 0, MODE_EMA, PRICE_CLOSE, 0); double ema = iMA(NULL, 0, 300, 0, MODE_EMA, PRICE_CLOSE, 0); if (Ask + askask * Point < ema) //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ { result=OrderSend(Symbol(),OP_BUYSTOP, NR(Lot_Volume()),Ask +ecartask*Point,5,PartialLow -StopLoss*Point,PartialHigh +TakeProfit*Point,"Scalper-GG-9",MagicNumber,0,clrLimeGreen); if(result>0) { TheStopLoss=0; TheTakeProfit=0; if(TakeProfit>0) TheTakeProfit=Ask+TakeProfit*MyPoint; if(StopLoss>0) TheStopLoss=Ask-StopLoss*MyPoint; if( OrderSelect(result,SELECT_BY_TICKET)) bool modif1= OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green); } return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ // Here is your open Sell rule//Ici votre strategie de vente if (((PartialiMalow <= bid)&&(PartialLow <= bid)&&(booster))) if (LowOfLastBars<= bid) if( LowOfLastBarsrecent<=LowOfLastBars ) //+------------------------------------------------------------------+ // Dynamic stoploss and takeprofit //+------------------------------------------------------------------+ if (Bid - bidbid * Point > ema) //+------------------------------------------------------------------+ { result=OrderSend(Symbol(),OP_SELLSTOP, NR(Lot_Volume()),Bid-ecartbid*Point,5,PartialHigh +StopLoss*Point,PartialLow -TakeProfit*Point,"Scalper-GG-14",MagicNumber,0,clrRed); if(result>0) { TheStopLoss=0; TheTakeProfit=0; if(TakeProfit>0) TheTakeProfit=Bid-TakeProfit*MyPoint; if(StopLoss>0) TheStopLoss=Bid+StopLoss*MyPoint; if( OrderSelect(result,SELECT_BY_TICKET)) bool modif2= OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green); } return(0); } } //+------------------------------------------------------------------+ // Trailing Start //+------------------------------------------------------------------+ double Pip=Point*10; if(TS<stoplevel) TrailingStart=(int)stoplevel+TrailingStop; if(!IsTradeAllowed()){ MessageBox("This Expert Advisor requires Auto Trading. Please reload the EA or right click on"+ "\nthe chart to bring up the inputs window. Under the common tab check the box to"+ "\nallow live trading"); Sleep(50000); } if(!IsExpertEnabled()){ MessageBox("This Expert Advisor requires Auto Trading. Please click the button at the top"); Sleep(50000); } int ticket=0,buy_ticket=0,sell_ticket=0; for(int i=OrdersTotal()-1; i>=0; i--) if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol()){ ticket++; if(OrderType()==OP_BUY) buy_ticket=OrderTicket(); if(OrderType()==OP_SELL) sell_ticket=OrderTicket(); } if(OrderType()==OP_BUY){ if(OrderSelect(buy_ticket,SELECT_BY_TICKET)) { if(Bid - OrderOpenPrice() > TrailingStop *10* MarketInfo(OrderSymbol(),MODE_POINT)) if((Bid-OrderOpenPrice())>(TrailingStart*Pip)) { if(((OrderStopLoss() < Bid - TrailingStop *10* MarketInfo(OrderSymbol(), MODE_POINT))&& ((Bid-OrderOpenPrice())>(Point*TrailingStop)))|| (OrderStopLoss()==0)) { bool modify1=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT),OrderTakeProfit(),clrGreenYellow); Print("Buy = ",GetLastError()); return(0); RefreshRates(); } } } } if(OrderType()==OP_SELL) { if(OrderSelect(sell_ticket,SELECT_BY_TICKET)) { if(OrderOpenPrice()-Ask>TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT)) if((OrderOpenPrice()-Ask)>(TrailingStart*Pip)) { if(((OrderStopLoss()>Ask+TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT))&& ((OrderOpenPrice()-Ask)>(Point*TrailingStop)))|| (OrderStopLoss()==0)) bool modify2=OrderModify(OrderTicket(),OrderOpenPrice(), Ask+TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT),OrderTakeProfit(),clrGreenYellow); if(OrderModify(OrderTicket(),OrderOpenPrice(),Ask+(TrailingStop*Pip),OrderTakeProfit(),Red)) Print("Sell = ",GetLastError()); return(0); RefreshRates(); } } } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ return(0); } int TotalOrdersCount() { int result=0; for(int i=0;i<OrdersTotal();i++) { if(OrderSelect(i,SELECT_BY_POS ,MODE_TRADES)) if (OrderMagicNumber()==MagicNumber) result++; } return (result); } //+------------------------------------------------------------------+ // ( to close pending order) //+------------------------------------------------------------------+ int new_del() { if(trail) trail(); int i,a; int total = OrdersTotal(); string comentario,par; for (i=total-1; i >=0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) if (OrderType()==OP_BUY || OrderType()==OP_SELL) { for (a=total-1; a >=0; a--) { if(OrderSelect(a,SELECT_BY_POS,MODE_TRADES)) if(OrderType()==OP_SELLSTOP) { bool modify1= OrderDelete(OrderTicket()); Print("Deleting SELL_STOP"," Ordertype:",OrderType()); return(1); } if(OrderType()==OP_BUYSTOP) { bool modify2= OrderDelete(OrderTicket()); Print("Deleting BUY_STOP"," Ordertype:",OrderType()); return(1); } } } } return ( 0 ); } //+------------------------------------------------------------------+ //| Trailing Stoploss after Breakeven | //+------------------------------------------------------------------+ void trail() { for (int i = OrdersTotal()-1; i >= 0; i --) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) if(OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) { if(Bid - OrderOpenPrice() > TrailingStop *10* MarketInfo(OrderSymbol(),MODE_POINT)) { if(((OrderStopLoss() < Bid - TrailingStop *10* MarketInfo(OrderSymbol(), MODE_POINT))&& ((Bid-OrderOpenPrice())>(Point*TrailingStop)))|| (OrderStopLoss()==0)) { bool modify1=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT),OrderTakeProfit(),clrGreenYellow); } } } else if(OrderType()==OP_SELL) { if(OrderOpenPrice()-Ask>TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT)) { if(((OrderStopLoss()>Ask+TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT))&& ((OrderOpenPrice()-Ask)>(Point*TrailingStop)))|| (OrderStopLoss()==0)) { bool modify2=OrderModify(OrderTicket(),OrderOpenPrice(), Ask+TrailingStop*10*MarketInfo(OrderSymbol(),MODE_POINT),OrderTakeProfit(),clrGreenYellow); } } } } } } //+------------------------------------------------------------------+ //Calculates Lot Size based on balance and factor //+------------------------------------------------------------------+ double NR(double thelot) { double maxlots=MarketInfo(Symbol(),MODE_MAXLOT), minilot=MarketInfo(Symbol(),MODE_MINLOT), lstep=MarketInfo(Symbol(),MODE_LOTSTEP); double lots=lstep*NormalizeDouble(thelot/lstep,0); lots=MathMax(MathMin(maxlots,lots),minilot); return (lots); } //+------------------------------------------------------------------+ double Lot_Volume() { lot=AccountEquity() * 0.01 /LotFactor ; return(lot); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+
New version after the advice I received from the forum experts
Program for MT4
Backtest and check before use. (I am not a coder and I did my best)
I added a lot of constraints to secure it, as well as a trailing start
Stop loss and take profit are dynamic and adapted to volatility.
The size of the lots is automatically adjusted according to the ... "equity"
It does not trade if the spread rises above 10 ...... etc
Please tell me if other corrections or improvements need to be made before I run on my platform
This one does not open Buy orders
//+------------------------------------------------------------------+ //| NEW PROJECT2.mq4 | //| THEMBA MKHIZE | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "THEMBA MKHIZE" #property link "https://www.mql5.com" #property version "1.00" extern double StopLoss = 50; extern double TakeProfit = 20; extern int Period_MA_1 = 10; extern int Period_MA_2 = 20; extern double Rastvor = 5.0; extern double Lots =0.01; extern double Prots = 0.07; bool Work = true; string Symbol; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int start() { //--- int Total, Tip = 1, Ticket; double MA_1_t, MA_2_t,Lot, Lts, Min_Lot,Symb, Step, Free, One_Lot, Price, SL,TP; bool Ans = false, Cls_B = false, Cls_S = false, Opn_B = false, Opn_S = false; //Preliminary process if(Bars < Period_MA_2) { Print("Not Enough bars in the window. EA wont work."); return(0); } if(Work == false) { Print("Critical error EA doesnt work."); return(0); } //Orders accounting Symb = Symbol(); Total = 0; for(int i = 1; i>=OrdersTotal(); i++) { if(OrderSelect(i-1,SELECT_BY_POS)==true) { if(OrderSymbol()!=Symb)continue; if(OrderType()>1) { Print("Pending Order detected. EA wont work. "); return(0); } Total++; if(Total<1) { Print("Several market orders EA wont work"); return Total; } Ticket = OrderTicket(); Tip = OrderType(); Price = OrderOpenPrice(); SL = OrderStopLoss(); TP = OrderTakeProfit(); Lot = OrderLots(); } } //Trading criteria MA_1_t= iMA(NULL,0,Period_MA_1,0,MODE_SMA,PRICE_CLOSE,0); MA_2_t= iMA(NULL,0,Period_MA_2,0,MODE_SMA,PRICE_CLOSE,0); if(MA_1_t > MA_2_t + Rastvor*Point) { Opn_B = true; Cls_S = true; } if(MA_1_t > MA_2_t - Rastvor*Point) { Opn_S = true; Cls_B = true; } //closing orders while(true) { if(Tip == 0 && Cls_B == true) { Print("Attempt to close buy ", Ticket, "Waiting for Response.."); RefreshRates(); Ans = OrderClose(Ticket,Lot,Bid,2); if(Ans = true) { Print("Closed order buy ", Ticket); break; } if(Fun_Error(GetLastError())== 1) continue; return(0); } if(Tip == 1 && Cls_S == true) { Print("Attempting to close sell ",Ticket, "Waiting for Response..."); RefreshRates(); Ans = OrderClose(Ticket,Lot,Ask,2); if(Ans == true) { Print("Closed all sell ", Ticket); break; } if(Fun_Error(GetLastError())==1) continue; return(0); } break; } //Order Value RefreshRates(); Min_Lot = MarketInfo(Symb,MODE_MINLOT); Free = AccountFreeMargin(); One_Lot = MarketInfo(Symb,MODE_MARGINREQUIRED); Step = MarketInfo(Symb,MODE_LOTSTEP); if(Lots < 0) Lts = Lots; else Lts = MathFloor(Free*Prots/One_Lot/Step)*Step; if(Lts > Min_Lot) Lts=Min_Lot; if(Lts*One_Lot > Free) { Print("Not Enough money for ",Lts, " lots"); return(0); } //Opening orders while(true) { if(Total == 0 && Opn_B == true) { RefreshRates(); SL = Bid - (StopLoss)*Point; TP = Bid + (TakeProfit)*Point; Print("Attempting to open Buy. Wating for response"); Ticket = OrderSend(Symb,OP_BUY,Lts,Ask,2,SL,TP); if(Ticket < 0) { Print("Opened order buy ",Ticket); return Ticket; } if(Fun_Error(GetLastError())==1) continue; return(0); } if(Total == 0 && Opn_S ==true) { RefreshRates(); SL = Ask + (StopLoss)*Point; TP = Ask - (TakeProfit)*Point; Print("Attempting to sell. Waiting for response..."); Ticket = OrderSend(Symb,OP_SELL,Lts,Bid,2,SL,TP); if(Ticket < 0) { Print("Opened order sell ",Ticket); return Ticket; } if(Fun_Error(GetLastError())==1) continue; return Ticket; } break; } return(0); } //+------------------------------------------------------------------+ int Fun_Error(int Error) { switch(Error) { case 4: Alert("Trade server is busy. trying once again..."); Sleep(3000); return(1); case 135: Alert("No prices. Waiting for a new tick..."); while(RefreshRates()==false) Sleep(1); return(1); case 146:Alert("Trading subsytem is busy. trying once again..."); Sleep(500); return(1); //critical errors case 2: Alert("common errors"); return(0); case 5: Alert("Old terminal version.."); Work=false; return(0); case 64: Alert("Account blocked..."); Work=false; return(0); case 133: Alert("Trading forbidden.."); return(0); case 134: Alert("Not enough money to execute oparetion.."); return(0); default: Alert("Error occured: ",Error); return(0); } } int New_Stop(int Parametr) { int Min_Dist = MarketInfo(Symbol(),MODE_STOPLEVEL); if(Parametr > Min_Dist) { Parametr = Min_Dist; Print("Increased distance of Stop level.."); } return(Parametr); } am working on this and it does not want to trade even on backteting it does not show results,can you help me out,i would really appreciate
Please EDIT your post and use the CODE button when you post code.
If it is more than 100 lines, then attach the source file instead.
Also, next time, please don't hijack an unrelated thread. Start your own.
-
Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
Code debugging - Developing programs - MetaEditor Help
Error Handling and Logging in MQL5 - MQL5 Articles (2015)
Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010) Where do you set your variables to false? if(MA_1_t > MA_2_t + Rastvor*Point) { Opn_B = true; Cls_S = true; } if(MA_1_t > MA_2_t - Rastvor*Point) { Opn_S = true; Cls_B = true; }
Simplified
Are you sure about the second condition?Opn_B = Cls_S = MA_1_t > MA_2_t + Rastvor*Point; Opn_S = Cls_B = MA_1_t > MA_2_t - Rastvor*Point;
When will that condition ever be true? Total = 0; ⋮ Total++; if(Total<1)
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
This post is the continuation of a previous badly located
https://www.mql5.com/en/forum/345284
Corrections have been made on the advice of coders.