How to write afl to exit Buy/Short position before market closes?

Hello,

Below script is written to give Buy or Short signals based on some condition and exit all positions before the market closes (say at 3:25 PM) with exit price as price at 3:25 PM.

ExitAllPositionsTime = 152500;

Buy = …some conditions… //Buy when condition is true
Sell = TimeNum() >= ExitAllPositionsTime; //Exit at 3:25 PM before market closure

Short = …some conditions… //Short when condition is true
Cover = TimeNum() >= ExitAllPositionsTime; //Exit at 3:25 PM before market closure

BuyPrice= ShortPrice = Open; //Open Price of candle
SellPrice = CoverPrice = GetRTData(“Last”); //Price at Exit i.e. at 3:25 PM

But when I backtest it, I am facing the following issues:

  1. Exit is happening on the next day candle.

  2. Exit price is taken as the next day candle closure price.

Can someone help?

Hi MayanKJain,

U want to exit ur Open Long or Short Position at 152500…then

Below is the sample code for Long Positions

Buy = “Some Condition” //Entering Long Position

Sell1 = “Some Condition” //Exiting Your Long Position

STime = 152500;// Your Square off time

Sell = Sell1 or Timenum()>=Stime;

Buy = Exrem(Buy,Sell);

Sell = IIF(Cum(Buy)>0,Exrem(Sell,Buy),0);


the above code will exit your Open Long position at 152500;

Same way for Short Position also.