Wednesday, September 9, 2015

Calculating the distance in pips for SL and TP (based on USD amount) in Metatrader 4

I know I said in my last post that I would do a generic version of a function for closing all orders (both BUY and SELL), but that's simply too easy. Until I get a request for it in the comments, we'll go further to learning more interesting MT4 programming stuff.

For instance, let's assume you want your 0.5 lots orders to either lose $30, or win $30 (when the TP is hit), but you don't know how many pips the EA should set the stoploss and takeprofit from the open price.
Here is how you calculate that:



double GetPipDistanceForAmount(string symbol,double amount,double lots)
  {
   double pipValue=MarketInfo(Symbol(),MODE_TICKVALUE);
   double point=MarketInfo(symbol,MODE_POINT);

   return  ((amount/lots)/pipValue)*point;
  }


The inputs are the amount in dollars you want to lose or gain (i.e. 30) and the volume of the trade (i.e. 0.5 lots).
This function will get you the number of pips you need to set the SL or the TP from the entry price so that you lose or win exactly $30 dollars with a 0.5 lots.
Let me know if this is useful to you and whether you need any help.

If however you do know how many pips your SL and TP should have, but you also want them to lose or gain a specific amount of USD (or whatever the account base currency is), then you need to dynamically calculate the lot-size, while keeping the SL and TP distance and their won/lost amount fixed. Following next, precisely that.

No comments:

Post a Comment