Need a backtestable AFL code for repainitng EMA Crossover strategy

Below are the conditions of this strategy:-

  1. Buy Condition -> 3 EMA crosses above 5 EMA on daily chart
  2. SELL Condition -> 3 EMA crosses below 5 EMA on daily chart
  3. SHORT Condition -> 3 EMA crosses below 5 EMA on daily chart
  4. COVER Condition -> 3 EMA crosses above 5 EMA on daily chart
  5. Additional Conditions -> It should be repainting strategy. That is signal should be taken even before the close of current candle if any of the above satisfies. However trade should be reversed if the condition vanishes after the close of current candle
  6. Position Size -> Start with an initial capital of 1 Lakh. Entire capital earned should be invested back into the trade.

Basically its a Stop and Reverse strategy.

As per the above condition

AFL

SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );

Buy = Cross (EMA( Close, 3 ), EMA( Close, 5 )) ;
Sell = Cross (EMA( Close, 5 ), EMA( Close, 3 )) ;

PlotShapes (Buy*shapeStar,colorGreen);

PlotShapes (Sell*shapeStar,colorRed);

Plot( EMA( Close, 20 ),"med ema", colorRed,styleThick); 
Plot( EMA( Close, 50 ),"long ema", colorBlue,styleThick); 

In Tradescript

Buy Script:

CROSSOVER(EMA(CLOSE,3),EMA(CLOSE,5))

Sell Script:

CROSSOVER(EMA(CLOSE,5),EMA(CLOSE,3))

Any help on this please?

Thanks for your help. But I wanted an AFL code and not Tradescript. Also the Tradescript code u shared in non-repainting, i.e. trade would be taken only on close of current candle.

Please check answer above

The above AFL takes positions only when 3 and 5 EMA crossover happens at the close of candle. But what if the crossover happens before the close? I mean suppose the positive crossover price is 8000 and candle closes at 8020, then I want to take the buy position at 8000 and not 8020. The same is true for Sell condition.