How to trigger StopLoss or TakeProfit in Mql4

 
void OnTradeTransaction(const MqlTradeTransaction& trans, const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {

   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
   if(type==TRADE_TRANSACTION_DEAL_ADD)
     {
      if(HistoryDealSelect(trans.deal))
        {
         m_deal.Ticket(trans.deal);

        }
      else
        {
         Print(__FILE__," ",__FUNCTION__,", ERROR: HistoryDealSelect(",trans.deal,")");
         return;
        }

      long reason=-1;
      if(!m_deal.InfoInteger(DEAL_REASON,reason))
        {
         Print(__FILE__," ",__FUNCTION__,", ERROR: InfoInteger(DEAL_REASON,reason)");
         return;
        }

      if((ENUM_DEAL_REASON)reason==DEAL_REASON_SL)
        {
         if(triggerSL)
           {

            double priceBuy = trans.price_sl - priceDistanceLimit;
            double priceSell = trans.price_sl + priceDistanceLimit;
            priceAskSL = priceBuy;
            priceBidSL = priceSell;
            executeBuy(priceBuy);
            executeSell(priceSell);
            triggerSL= false;
            newStopLossHedge = false;
           }
        }
      else
        {
         if((ENUM_DEAL_REASON)reason==DEAL_REASON_TP)
           {
            double priceBuy = trans.price_tp - priceDistanceLimit;
            double priceSell = trans.price_tp + priceDistanceLimit;
            priceAskSL = priceBuy;
            priceBidSL = priceSell;
            executeBuy(priceBuy);
            executeSell(priceSell);
           }
        }
     }
  }


 
I have code function trigger in mql5, but I just switch use mql4, I don't know how to solve it
 
Your topic has been moved to the section: MQL4 and MetaTrader 4
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
OnTradeTransaction is not Available with MQL4. You have to read historical deals all the time to catch the event.
 
Xuan Dat #: I have code function trigger in mql5, but I just switch use mql4, I don't know how to solve it

To learn MQL4, please read the documentation ... MQL4 Reference

However, MT4/MQL4 is very outdated and no longer developed for many years.

MQL4 Reference
MQL4 Reference
  • docs.mql4.com
MQL4 Reference
 
Xuan Dat #: I have code function trigger in mql5, but I just switch use mql4, I don't know how to solve it

When in doubt, think!

Not tested, not compiled, just typed.

void LastTradeTransaction(){
   static lastTradeTime=0; int lastTradeTicket=0; bool lastTradeTP;
   for(int iPos=OrderHistoryTotal()-1 ; iPos >= 0; --iPos) if(
      OrderSelect(iPos, SELECT_BY_POS, MODE_HISTORY)
   && OrderMagicNumber() == …
   && OrderType()        <= OP_SELL        // Closed orders only
   && OrderCloseTime()   >  lastTradeTime  // Not already processed.
  ){
      lastTradeTime   = OrderCloseTime();
      lastTradeTicket = OrderTicket();
           double ocp = OrderClosePrice(), otp = OrderTakeProfit(), osl = OrderStopLoss();
      lastTradeTP     = MathAbs(ocp - otp) < MathAbs(ocp - osl); // Assumes close by stops only
   }
   if(lastTradeTicket == 0) return;
   OrderSelect(lastTradeTicket, SELECT_BY_TICKET)
   if(lastTradeTP){ // reason==DEAL_REASON_TP 
      ⋮
  } else {          // reason==DEAL_REASON_SL
      ⋮
  }
} // LastTradeTransaction()

Not tested, not compiled, just typed.

 

This is what I recently used for take profit detection. For stop loss, you can modify it by analogy with take profit.

bool isSelectedOrderClosedByTp()
  {
   double priceClose = NormalizeDouble(OrderClosePrice(), Digits());
   double takeProfit = NormalizeDouble(OrderTakeProfit(), Digits());
   if(takeProfit == 0.0)
      return(false);
   if(OrderType() == 0)
     {
      if(priceClose >= takeProfit)
         return(true);
      return(StringFind(OrderComment(), "[tp]") >= 0);
     }
   else if(OrderType() == 1)
     {
      if(priceClose <= takeProfit)
         return(true);
      return(StringFind(OrderComment(), "[tp]") >= 0);
     }
   else
     {
      Alert(__FUNCTION__, " Incorrect order type: ", OrderType());
      return(false);
     }
  }
 
Vladislav Boyko #: This is what I recently used for take profit detection. For stop loss, you can modify it by analogy with take profit.
  1.    double priceClose = NormalizeDouble(OrderClosePrice(), Digits());
       double takeProfit = NormalizeDouble(OrderTakeProfit(), Digits());

    You used NormalizeDouble, It's use is usually wrong, as it is in your case.

    1. Floating point has an infinite number of decimals, it's you were not understanding floating point and that some numbers can't be represented exactly. (like 1/10.)
                Double-precision floating-point format - Wikipedia, the free encyclopedia

      See also The == operand. - MQL4 programming forum (2013)

    2. Print out your values to the precision you want with DoubleToString - Conversion Functions - MQL4 Reference.

    3. SL/TP (stops) need to be normalized to tick size (not Point) — code fails on non-currencies.
                On 5Digit Broker Stops are only allowed to be placed on full pip values. How to find out in mql? - MQL4 programming forum #10 (2011)

      And abide by the limits Requirements and Limitations in Making Trades - Appendixes - MQL4 Tutorial and that requires understanding floating point equality Can price != price ? - MQL4 programming forum (2012)

    4. Open price for pending orders need to be adjusted. On Currencies, Point == TickSize, so you will get the same answer, but it won't work on non-currencies. So do it right.
                Trailing Bar Entry EA - MQL4 programming forum (2013)
                Bid/Ask: (No Need) to use NormalizeDouble in OrderSend - MQL4 programming forum (2012)

    5. Lot size must also be adjusted to a multiple of LotStep and check against min and max. If that is not a power of 1/10 then NormalizeDouble is wrong. Do it right.
                (MT4 2013)) (MT5 2022))

    6. MathRound() and NormalizeDouble() are rounding in a different way. Make it explicit.
                MT4:NormalizeDouble - MQL5 programming forum (2017)
                How to Normalize - Expert Advisors and Automated Trading - MQL5 programming forum (2017)

    7. Prices you get from the terminal are already correct (normalized).

    8. PIP, Point, or Tick are all different in general.
                What is a TICK? - MQL4 programming forum (2014)

  2.       return(StringFind(OrderComment(), "[tp]") >= 0);

    Not a good idea to use comments, brokers can change comments, including complete replacement.

    Only some brokers add "[tp]" to comments on close.

  3.       if(priceClose >= takeProfit)
    The closing price may not be equal to the take profit because of slippage.
 
William Roeder #:
You used NormalizeDouble, It's use is usually wrong, as it is in your case.

If all prices that are compared are normalized using NormalizeDouble, then there will be absolutely no problems.

William Roeder #:
as it is in your case

Why is using NormalizeDouble wrong in my case?

Can you give an example of OrderClosePrice() and OrderTakeProfit() values that would cause the comparison result from my code to be incorrect? What should OrderClosePrice() and OrderTakeProfit() return so that my comparison would give an incorrect result?


William Roeder #:
Prices you get from the terminal are already correct (normalized).

As I already told you once, I could not find confirmation of your statement in the documentation. Therefore, I normalize the order prices received from the terminal. I also normalize Ask and Bid. I won't rely on the fact that the terminal returns normalized prices until it is explicitly stated in the documentation.


William Roeder #:
PIP, Point, or Tick are all different in general.

PIP doesn't exist for me. I believe PIP should be a thing of the past.

 
William Roeder #:
Not a good idea to use comments, brokers can change comments, including complete replacement.

It's not a good idea to use comments to store information. Using a comment to search for "[tp]" (written by the broker) is quite reliable.

William Roeder #:
Only some brokers add "[tp]" to comments on close.

And other brokers do not add anything or add something different?

Has anyone met a broker who does not add “[tp]” when the take profit is triggered? If yes, please reply to this post.

William Roeder #:
The closing price may not be equal to the take profit because of slippage.

In this case (only in this case), the advisor will check the comment.

 
William Roeder #:
Not tested, not compiled, just typed.

Your code will not work correctly if the advisor also uses OrderClose.

My code is used in an advisor that also uses OrderClose.


Could you please show an example of code that will work correctly when both SL/TP and OrderClose are used?

William Roeder #:

Not a good idea to use comments, brokers can change comments, including complete replacement.

Only some brokers add "[tp]" to comments on close.

It would be really cool if your implementation didn't use a comment