Here's a quick conversion (untested.)
Note the two #includes, you'll get the files from here: https://www.mql5.com/en/code/16006
//+------------------------------------------------------------------+ //| TrailingStopMA_v1-0.mq5 | //| Luca Spinello | //| https://mql4tradingautomation.com | //+------------------------------------------------------------------+ #property copyright "Luca Spinello - mql4tradingautomation.com" #property link "https://mql4tradingautomation.com" #property version "1.00" #property strict #property description "This EA performs a Trailing Stop following a moving average" #property description " " #property description "DISCLAIMER: This code comes with no guarantee, you can use it at your own risk" #property description "We recommend to test it first on a Demo Account" #define MT4_TICKET_TYPE #include <MT4orders.mqh> // https://www.mql5.com/en/code/16006 #include <MQL4_to_MQL5.mqh> // https://www.mql5.com/en/code/16006 //Configure the external variables input int MAPeriod=25; //Moving Average Period input ENUM_MA_METHOD MAMethod=MODE_SMA; //Moving Average Method (0=Simple, 1=Exponential) input bool OnlyMagicNumber=false; //Modify only orders matching the magic number input int MagicNumber=0; //Matching magic number input bool OnlyWithComment=false; //Modify only orders with the following comment input string MatchingComment=""; //Matching comment input int Delay=0; //Delay to wait between modifying orders (in milliseconds) //input double Slippage=2; //Slippage <--- commented out since it's unused //Flag to check if code can be run bool CanExecute=true; //Digits normalized double nDigits; int MAhandle; //Function to normalize the digits double CalculateNormalizedDigits() { if(_Digits<=3){ return(0.01); } else if(_Digits>=4){ return(0.0001); } else return(0); } void Initialize(){ //Normalization of the digits nDigits=CalculateNormalizedDigits(); if(_Digits==3 || _Digits==5){ // Slippage=Slippage*10; } } //Function to Scan and Update the orders void UpdatePositions(){ //Scan the open orders backwards for(int i=OrdersTotal()-1; i>=0; i--){ //Select the order, if not selected print the error and continue with the next index if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false ) { Print("ERROR - Unable to select the order - ",GetLastError()); continue; } //Check if the order can be modified matching the criteria, if criteria not matched skip to the next if(OrderSymbol()!=_Symbol) continue; if(OnlyMagicNumber && OrderMagicNumber()!=MagicNumber) continue; if(OnlyWithComment && StringCompare(OrderComment(),MatchingComment)!=0) continue; //Prepare the prices double TakeProfitPrice=OrderTakeProfit(); double StopLossPrice=OrderStopLoss(); double OpenPrice=OrderOpenPrice(); double NewStopLossPrice=StopLossPrice; double NewTakeProfitPrice=TakeProfitPrice; //Moving Average Value of the current symbol, current timeframe, MAPeriod and Type, previous candle static double buffer[1]; int shift=1; int amount=1; if(CopyBuffer(MAhandle,MAIN_LINE,shift,amount,buffer)!=amount){ Print("CopyBuffer failed, error ",_LastError); ExpertRemove(); return; } double MAValue=buffer[0]; // MQL4: iMA(_Symbol,0,MAPeriod,0,MAType,PRICE_CLOSE,1); //Get updated prices and calculate the new Stop Loss and Take Profit levels, these depends on the type of order RefreshRates(); if(OrderType()==OP_BUY){ if(MAValue>StopLossPrice && MAValue<Close[0] && MAValue<TakeProfitPrice){ NewStopLossPrice=NormalizeDouble(MAValue,_Digits); } } if(OrderType()==OP_SELL){ if(MAValue<StopLossPrice && MAValue>Close[0] && MAValue>TakeProfitPrice){ NewStopLossPrice=NormalizeDouble(MAValue,_Digits); } } //If the new Stop Loss and Take Profit Levels are different from the previous then I try to update the order if(NewStopLossPrice!=StopLossPrice){ Print("Modifying order ",OrderTicket()," Open Price ",OpenPrice," New Stop Loss ",NewStopLossPrice," New Take Profit ",NewTakeProfitPrice); if(OrderModify(OrderTicket(),OpenPrice,NewStopLossPrice,NewTakeProfitPrice,0,Yellow)){ Print("Order modified"); } else{ Print("Order failed to update with error - ",GetLastError()); } } //Wait a delay Sleep(Delay); } } //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- if(MAMethod!=MODE_SMA && MAMethod!=MODE_EMA) CanExecute=false; if(!CanExecute) Print("The method for moving average must be SMA or EMA"); Initialize(); MAhandle=iMA(_Symbol,_Period,MAPeriod,0,MAMethod,PRICE_CLOSE); if(MAhandle==INVALID_HANDLE) { Print("invalid MA handle, error ",_LastError); return INIT_FAILED; } //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- //If the pre-checks are passed I can proceed with the trailing stop if(CanExecute){ UpdatePositions(); } } //+------------------------------------------------------------------+
MT4Orders
- www.mql5.com
This library allows to work with the orders in MQL5 (MT5-hedge) in the same way as in MQL4. That is, the order language system (OLS) becomes identical to MQL4. At the same time, it is still possible to use the MQL5 order system in parallel. In particular, the standard MQL5 library will continue to fully operate. It is not necessary to choose...
Files:
TrailingStopMA_v1-0.mq5
13 kb
Thank you very much
It does not work by the way. it doesn't not move the SL at all
Hi
Not sure what to do here. I am not a coder. If you could please give a step by step guide that would be highly appreciated.
Run it on chart with its default settings. Run a trade for this symbol. Set an initial SL and TP level. It seems you are unsure about working with EAs so I suggest to post a job in Freelance to get someone to help you.
Trading applications for MetaTrader 5 to order
- www.mql5.com
Hi dear Developer We build a binary bridge together and now we can do the finishing touches - Add missing functions like digits in/out ect. - Update the indicator based signal so it opens on the exact signal ( currently its not always working, maybe add look for signal in the expert tab) - Add copy Trader function please find a picture of...
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Hi
Does anyone know where I can find a expert that closes my deal once price closes above or below a moving average? I found the code for MT4 but not for MT5.