I would like to sell when the buyprice is less than Close price of 10th bar from Buy. For previous bars, we use Ref(Close,-1) and I am not sure how to code for this case. Could you please guide me or share any link which is similar to it?
Your requirement is Nbar Stop.
So for stops either use ApplyStop function or Looping.
As for looping see here
If I understand your sentence correctly you would have to modify SellSignal line to
SellSignal = Close[ i ] > buyentryprice AND i == buyentrybar + 10;
Replacing or operator ( || , OR ) by AND operator.
This would check for sell if close is greater than buyprice 10 bars after Buy entry.
So only at that point.
If you want to check >= nbar (instead of ==) then:
SellSignal = Close[ i ] > buyentryprice AND i >= buyentrybar + 10;
I have coded as below for below conditions:
Buy when Close crosses above Supertrend and TSI > 1.85.
Sell when Supertrend crosses above Close or Buyprice crosses above Close price of 10th bar.
//SuperTrend code is copied from Library link: //http://www.amibroker.com/members/library/formula.php?id=1505
//TSI
Ratio = abs(close - Ref(Close, -10)) / ATR(10);
TSI = MA(MA(Ratio,10),100);
Plot(TSI, "TSI", colorRed, styleLine);
//Barsince
B10 = BarsSince(Cross( Close, superTrend ) AND Ref(TSI > 1.85,-1));
B10P = ValueWhen(B10 = 9,C,-9);
//Logical Buy/Sell Rules
Buy = Cross( Close, superTrend ) AND Ref(TSI > 1.85,-1);
Sell = Cross( superTrend, Close ) OR Cross(BuyPrice,B10P);
Please correct me if anything wrong in the coding.
As mentioned either use ApplyStop or looping code.
So instead of upper looping code you may use ApplyStop ValidFrom/To arguments of some profit stop.
In ApplyStop you may use profittarget type and with smallest profit amount (e.g. TickSize) since you just want Close to be greater than Buyprice. And since you want to apply stop only after nbars you can use ValidFrom ValidTo arguments of ApplyStop.
So either profit being valid at nbar after entry (see Close[ i ] > buyentryprice AND i == buyentrybar + nbar). So ValidFrom and ValidTo have to have equal value (last two arguments of below ApplyStop line):
Please find the code below and let me know whether my understanding is correct.
// Code as below for: When buyprice is greater than close price of 10th bar, book profit.
nbar = 9;
amount = 0.01;//Ticksize
exitatstop = 0;
ApplyStop(stopTypeProfit, stopModePoint, amount, exitatstop, False, 0, nbar);
//Code as below for: When buyprice is lesser than close price of 10th bar, book Loss.
nbar = 9;
amount = 0.01;//Ticksize
exitatstop = 0;
ApplyStop(stopTypeLoss, stopModePoint, amount, exitatstop, False, 0, nbar);