Partial Close

 
I'd like to know how i would write a function that will close a partial of all open positions that are in profit every 10 pips. I'm writing a grid EA which has sell stops placed every 10 pips below the opening price and buy stops every 10 pips above the opening price. So how could i go about this?
 
  • If you show your attempts and describe your problem clearly, you will most probably receive an answer from the community.
  • You can also look at the Codebase if something already similar exists, so that you may study it.
  • Finally, you also have the option to hire a programmer in the Freelance section.
 

Here is a sample code from the CodeBase ...

Code Base

closing partially script and Stop loss to Break Even point

Mehmet Bastem, 2021.06.24 16:55

closing partially script and Stop loss to Break Even point
 

Your question is not related to the section you posted so it has been moved to the appropriate section: MQL5 forum: Expert Advisors and Automated Trading

 

here is what i came up with but when it is ran in the strategy tester it freezes as soon as the first stop order is hit.

I would like to know how to close partial profits on an open position every ten pips, so for example if a position was opened at 1.10000 i would like it to close a 10% partial at 1.10100 and then another 10% at 1.0200 and another 10% at 1.10300 and so on. I would like it to do this for all positions.

void ClosePartials()
{
   double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   int totalPositions = PositionsTotal();
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong ticket = PositionGetTicket(i);
      if(PositionSelectByTicket(ticket))
      {
         double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         double posVolume = PositionGetDouble(POSITION_VOLUME);
         double pipsProfit = (((openPrice-currentPrice)/_Point))/10;
         pipsProfit = NormalizeDouble(pipsProfit,_Digits);
        
         for(i; i<totalPositions; i++)
            {
               double lotsToClose = posVolume*0.1;
               if(pipsProfit>0&&(int)pipsProfit%10==0)
               {
                  trade.PositionClosePartial(ticket,lotsToClose);
               }
            }
      }
   }
}
 

I have edited your Improperly formatted code. In future, please use the CODE button (Alt-S) when inserting code.

Code button in editor

 
joshkelly1 #:

here is what i came up with but when it is ran in the strategy tester it freezes as soon as the first stop order is hit.

I would like to know how to close partial profits on an open position every ten pips, so for example if a position was opened at 1.10000 i would like it to close a 10% partial at 1.10100 and then another 10% at 1.0200 and another 10% at 1.10300 and so on. I would like it to do this for all positions.

@joshkelly1, that's crazy i was trying to achieve the exact same thing but for a fixed amount, the problem was that when i closed out the lot 10% after every 10pts in my case, the complete sum of all closed out positions did not reach my profit target by a long shot my target is 1% or $100 per trade, i ended up getting $43 after adding all the partially closed positions which i need some light why that is

1. i have included a helper function that calculates the exact lot that risk a specific amount (in this case its 1% per trade), for a $10,000 account that should be $100 per trade 

double CalculateUnitSize(string pMarket, double pMoneyCapital, double pRiskPercentage, int pStoplossPoints, double pAllowedMaxUnitSize) 
   {
      //---Calculate LotSize based on Equity, Risk in decimal and StopLoss in points
      double maxLots, minLots, oneTickValue, moneyRisk, lotsByRisk, lotSize;
      int totalTickCount;

      maxLots = MaxUnitSizeAllowedForMargin(pMarket, pMoneyCapital, pAllowedMaxUnitSize);
      minLots = SymbolInfoDouble(pMarket, SYMBOL_VOLUME_MIN);
      oneTickValue = SymbolInfoDouble(pMarket, SYMBOL_TRADE_TICK_VALUE); // Tick value of the asset

      moneyRisk = (pRiskPercentage/100) * pMoneyCapital;
      totalTickCount = ToTicksCount(pMarket, pStoplossPoints);

      //---Calculate the Lot size according to Risk.
      lotsByRisk = moneyRisk / (totalTickCount * oneTickValue);
      lotSize = MathMax(MathMin(lotsByRisk, maxLots), minLots);      
      lotSize = NormalizeLots(pMarket, lotSize);
      return (lotSize);
   }

   double MaxUnitSizeAllowedForMargin(string pMarket, double pMoneyCapital, double pAllowedMaxUnitSize) 
   {
      // Calculate Lot size according to Equity.
      double marginForOneLot, lotsPossible;
      if(OrderCalcMargin(ORDER_TYPE_BUY, pMarket, 1, SymbolInfoDouble(pMarket, SYMBOL_ASK), marginForOneLot)) { // Calculate margin required for 1 lot
         lotsPossible = pMoneyCapital * 0.98 / marginForOneLot;
         lotsPossible = MathMin(lotsPossible, MathMin(pAllowedMaxUnitSize, SymbolInfoDouble(pMarket, SYMBOL_VOLUME_MAX)));
         lotsPossible = NormalizeLots(pMarket, lotsPossible);
      } else {
         lotsPossible = SymbolInfoDouble(pMarket, SYMBOL_VOLUME_MAX);
      }   
      return (lotsPossible);
   }

   int ToTicksCount(string pMarket, uint pPointsCount) 
   {
      double uticksize = SymbolInfoDouble(pMarket, SYMBOL_TRADE_TICK_SIZE);
      int utickscount = uticksize > 0 ? (int)((pPointsCount / uticksize) * uticksize) : 0; //-- fix prices by ticksize
      return utickscount;
   }

   double NormalizeLots(string pMarket, double pLots) {       
      double lotstep   = SymbolInfoDouble(pMarket, SYMBOL_VOLUME_STEP);
      int lotdigits    = (int) - MathLog10(lotstep);
      return NormalizeDouble(pLots, lotdigits);   
   } 

2. i place a trade using a breakout strategy and obviously only risk 1% each time thanks to the above function , but there is one small dilemma;

sometimes the price breaks through but can't quite hit the TP which is set by me arbitrarily, I was wondering if there is a way to close as much of the running trade as possible,

so for example;

since we are only risking $100 per trade,

if we have a BUY trade with a TP set at 100pts,

and my function above accurately calculated we need to place around 1lot to make $100 at 100pts,

and SL set at the same 100pts so 1:1 RR,

how can one close out 10$ partially after every 10 point increase in price towards my TP programmatically,

figuring out exactly how much out of the 1lot to partially close out each time is extremely tricky in code because remember the distance from the point the trade was taken increases as price gets closer to the TP in this example

e.g

at 10 points from the BUY price we need to close out x amount of lots ,

at 20 points from the BUY price we need to close out y amount of lots ,

at 30 points from the BUY price we need to close out z amount of lots ,

...and so on until we reach 90points

at which point if we add all the lot we closed it should still equal 1lot which is what we placed the trade with

in summary i want to take a $100 trade and close out 10$ after each 10% move towards the price , THANKS

 

Just for your information: partial closures, trailing stops, breakeven and all similar stuffs in most of cases will decrease your expected payoff without giving significant improovements: they will never transform a loosing strategy into a profitable one.

If your trades have difficulties to hit your TP you should firstly try to decrease your TP value.

 
Fabio Cavalloni #:

Just for your information: partial closures, trailing stops, breakeven and all similar stuffs in most of cases will decrease your expected payoff without giving significant improovements: they will never transform a loosing strategy into a profitable one.

If your trades have difficulties to hit your TP you should firstly try to decrease your TP value.

yeah thanks a lot  for the input Fabio , but I'm a scalper on 5m, I'm on a strict 1:1 R:R, decreasing the Tp for me means more risk than reward because if i correspondingly reduce the risk, I will statistically loose more trades anyway (price needs room to jump), so i want to at least breakeven on bad trades...my strategy is not a loosing strategy... I adapted it from hedge funds like renaissance


I believe there is a smart way to solve this problem because i don't assume to know everything in life, i just don't know how yet;

could it be multiple TPs?

could it be multiple buy stops?

could it be that i should only be trying to breakeven with partial close?


food for thought...
 
simonushie #:


It is always important to remember that no single strategy is a winner 100% of the time, therefore: deciding when to accept a full loss trade is always the crux of all trading. Analysing and modifying a strategy comes to a point when you compromise the winning strategy, itself, therefore taking a full loss every now and then is often far better for both the strategy and our loss of sanity that we lose while "over analysing" these things.