Buy at empty on first bar of the day

Dear Seniors,

I am getting an Empty Buy/Sell signal at the first bar of the day. Please see the attached AFL and image. Also on certain days, the range line are getting angled. Please help to fix the buy bug.

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() );
sig = Null;
pos=Param("size",20,1,3000,1);
SetPositionSize(pos,spsShares);
iATR= Ref(MA(H-L,20),-1);
tslf= Param("TSL Factor",2,1, 10,0.5);

newday = Day() != Ref(Day(),-1);  //check if new day or not

starttime = ValueWhen(newday,TimeNum());
IBendtime = starttime+1000;
minh = ValueWhen(newday,TimeFrameGetPrice("H",in5Minute*2));
minl = ValueWhen(newday,TimeFrameGetPrice("L",in5Minute*2));


TimeRange = ParamToggle("Time","No|Yes",1);
Starttime = Param("Starttime",090000,090000,151500,0);
Closetime = Param("Closetime",151500,090000,151500,0);
ExitToday = (Ref(DateNum(),1) > DateNum());
extime= TimeNum()>152500;

PH=TimeFrameGetPrice("H",inDaily,-1);
PL= TimeFrameGetPrice("L",inDaily,-1);
PC= TimeFrameGetPrice("C",inDaily,-1);



printf("%g",IBendtime);

DayOpen = TimeFrameGetPrice("O",inDaily);
DayHigh = TimeFrameGetPrice("H",inDaily);
DayLow = TimeFrameGetPrice("L",inDaily);

ORBH = IIf(TimeNum() < IBendtime, Null ,minh);
ORBL = IIf(TimeNum() < IBendtime, Null, minl);
FIBO = .618;
PREV_Day_Range= PH-PL;
Current_Day_Range=ORBH-ORBL;

FIBO_RANGE = ( PREV_Day_Range + Current_Day_Range ) * FIBO;
// Calcualte .618 range from yesterdays close..
Buy_Range_High = PC + FIBO_RANGE;
Sell_Range_Low = PC - FIBO_RANGE;
/// If todays price is gapup or gapbelow  .618 range.
Condition1 = minh > Buy_Range_High;
Condition2= minl < Sell_Range_Low;
ExtraCondition =  Condition1 OR Condition2;

Up =  IIf(ExtraCondition, ORBH, Buy_Range_High);
DN =  IIf(ExtraCondition, ORBL, Sell_Range_Low);

B1  = Cross(H,up) ;

//S1= C<=Dn ;
Sh1= Cross(dn,L);

//Co1= C>=Up;



//Plot( IIf(ExtraCondition, minh, Buy_Range_High), "Upper Break Out", colorYellow , styleDashed);
//Plot( IIf( ExtraCondition, minl, Sell_Range_Low), "Lower Break Down", colorYellow, styleDashed);

     dtDayStartComp = TimeFrameCompress( DateTime(), inDaily, compressOpen );
	 dtDayStartExp = TimeFrameExpand( dtDayStartComp, inDaily, expandFirst );
	 dtDayEndComp = TimeFrameCompress( DateTime(), inDaily, compressLast );
	 dtDayEndExp = TimeFrameExpand( dtDayEndComp, inDaily, expandFirst );
	 DayCond = DateTime() >= dtDayStartExp AND DateTime() < dtDayEndExp;	
	 //DayCond1 =  DayCond AND (TimeNum() > 091000)


	 Plot( IIf( DayCond, UP, Null ), "Upper Breakout", colorYellow, styleDashed, Null, Null, 0 );
	 //Plot( IIf( DayCond, UP, Null ), "Upper Breakout", colorAqua, styleLine, Null, Null, 2 );
	 
	 Plot( IIf( DayCond, DN, Null), "Lower Breakout", colorYellow, styleDashed, Null, Null, 0 );
	 //Plot( IIf( DayCond, DN, Null), "Lower Breakout", colorAqua, styleLine, Null, Null, 2 );
	 

Buy = IIf(TimeRange==False,B1,B1 AND TimeNum() > Starttime AND TimeNum() < Closetime);
Short = IIf(Timerange==False,Sh1,Sh1 AND TimeNum() > Starttime AND TimeNum() < Closetime);

Cover =  TimeNum() > Closetime;
Sell  =TimeNum() > Closetime;

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

Short=ExRem(Short,Cover);
Cover=ExRem(Cover,Short);
BuyPrice=up;
ShortPrice=Dn;
dist = 1.5*ATR(10);
for( i = 0; i < BarCount; i++ )
{
if( Buy[i] ) PlotText( "Buyn@" + up[ i ], i, L[ i ]-dist[i], colorGreen );
if( Short[i] ) PlotText( "shortn@" + dn[ i ], i, H[ i ]+dist[i], colorRed, colorYellow );
}
//PlotShapes(IIf(SSL , shapeStar, shapeNone),colorBlue , 0,High,Offset=30);
tsl=tsls=0;
slarr=Null;
bflag=0;
sflag=0;
BP=SP=0;
BSL=SSL=0;
sl=Param("stoploss",0.4,0.3,0.6,0.01);
for( i = 1; i < BarCount; i++ )
{

if(Buy[i]==1)
{
tsl= C[i]-tslf*iatr[i];
bfalg=1;
BP=ValueWhen(Buy,C,1);
BSL = ValueWhen(Buy,BP-((BP/100)*sl),1);
}

if(tsl>0)
{
if(C[i]-tslf*iatr[i]>tsl) tsl= C[i]-tslf*iatr[i];

if (tsl[i]<BSL[i])
{
slarr[i]=BSL[i];
}
else
{
slarr[i]=tsl[i];
}
}


if((L[i]<slarr[i] AND C[i]<O[i]) OR extime[i] OR ExitToday[i] )
{
Sell[i]=1;
bflag=0;
tsl=0;
SellPrice=slarr[i];
}

if(Short[i]==1)
{
tsls= C[i]+tslf*iatr[i];
sflag=1;
SP=ValueWhen(Short,C,1);
SSL=ValueWhen(Short,SP+((SP/100)*sl),1);
}

if(tsls>0)
{
if(C[i]+tslf*iatr[i]<tsls) tsls= C[i]+tslf*iatr[i];
if(tsls[i]>SSL[i])
{
slarr[i]=SSL[i];
}
else
{
slarr[i]=tsls[i];
}
}

if((H[i]>slarr[i] AND C[i]>O[i]) OR extime[i] OR ExitToday[i])
{
Cover[i]=1;
sfalg=0;
tsls=0;
CoverPrice=slarr[i];
}

}



Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

Short=ExRem(Short,Cover);
Cover=ExRem(Cover,Short);
Plot(slarr,"sl",colorAqua);

StopLoss=Param("stoploss",0.43,0.2,0.6,0.02);
ApplyStop(Type=0,Mode=1,Amount=StopLoss);

//Plot(RSI(11),"rsi",colorBlue,styleOwnScale);


PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(IIf(Sell , shapeStar, shapeNone),colorRed , 0,High,Offset=20);
PlotShapes(IIf(Cover , shapeStar, shapeNone),colorGreen, 0,Low,Offset=-20);

Untitled

Buy and sell signals can come only if the price crosses the range after the first 10 mins in the market.

Thanks in advance.

Regards,
Sumit

Just having had quick look...

First you should fix this one

And this one

ValueWhen is an array function and does not belong within your loop.

So modify upper variables to these ones

BP = C[i];
BSL = BP*(1 - sl/100);

And these ones

SP = C[i];
SSL = SP*(1 + sl/100);

or better to this one

//BEFORE the loop
BSL_level = C*(1-sl/100);

// Wthin the loop
BSL = BSL_level[i];

And to this one

//BEFORE the loop
SSL_level = C*(1+sl/100);

// Wthin the loop
SSL = SSL_level[i];

And remove subscripts ([i]) of all SSL and BSL variables. They are not array anymore but type number.

Hi @fxshrat,

As always very kind of you to point the issue.

Thanks again.

Kind Regards,
Sumit

_SECTION_BEGIN( "Sumit code v1" );

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() );

//StartTime = ParamTime( "End time", "11:50:00");
//Entry = TimeNum()>115000 AND TimeNum()<170000;
//Exit = TimeNum()>174500;



StartTime = ParamTime( "Start time", "09:15:00" );
Entry = TimeNum() > 091500 AND TimeNum() < 030000;
Exit = TimeNum() > 031500;

newday = Day() != Ref( Day(), -1 );

starttime = ValueWhen( newday, TimeNum() );
orb = "10min";


//Go to 10 Min time fram
if( orb == "10min" )
{
    IBendtime = starttime + 1000;
    minh = ValueWhen( newday, TimeFrameGetPrice( "H", in5Minute * 3 ) );
    minl = ValueWhen( newday, TimeFrameGetPrice( "L", in5Minute * 3 ) );
}

//*************************************************************************************************************************************
// Current Day 10 min high /low
current_day_10_min_high = IIf( TimeNum() < IBendtime, Null , minh );
current_day_10_min_low = IIf( TimeNum() < IBendtime, Null, minl );
//Previous day high low close
prev_day_close = ValueWhen( newday, TimeFrameGetPrice( "C", inDaily, -1 ) );
prev_day_High = ValueWhen( newday, TimeFrameGetPrice( "H", inDaily, -1 ) );
prev_day_LOW = ValueWhen( newday, TimeFrameGetPrice( "L", inDaily, -1 ) );
prev_day_open = TimeFrameGetPrice( "O", inDaily, 0 );
printf( "\n prev_day_close = %.2f", prev_day_close );
printf( "\n prev_day_High = %.2f", prev_day_High );
printf( "\n prev_day_LOW = %.2f", prev_day_LOW );
printf( "\n cur_day_10h = %.2f \n", current_day_10_min_high );
printf( "\nscur_day_10l = %.2f \n", current_day_10_min_low );

//*************************************************************************************************************************************

// Plotting buy and sell value....

FIBO = .618;
PREV_Day_Range = prev_day_High - prev_day_LOW;
Current_Day_Range = current_day_10_min_high - current_day_10_min_low;
printf( "\n PREV_Day_Range = %.2f", PREV_Day_Range );
printf( "\n Current_Day_Range = %.2f", Current_Day_Range );

FIBO_RANGE = ( PREV_Day_Range + Current_Day_Range ) * FIBO;
// Calcualte .618 range from yesterdays close..
Buy_Range_High = prev_day_close + FIBO_RANGE;
Sell_Range_Low = prev_day_close - FIBO_RANGE;
/// If todays price is gapup or gapbelow  .618 range.
Condition1 = current_day_10_min_high > Buy_Range_High;
Condition2 = current_day_10_min_low < Sell_Range_Low;
ExtraCondition =  Condition1 OR Condition2;

Upper_buy_Range = IIf( ExtraCondition, current_day_10_min_high, Buy_Range_High );
BuyPrice = Upper_buy_Range;
Plot( IIf( ExtraCondition, current_day_10_min_high, Buy_Range_High ), "Upper_buy_Range", colorYellow , styleLine );

Lower_break_Down = IIf( ExtraCondition, current_day_10_min_low, Sell_Range_Low );
shortPrice = Lower_break_Down;
Plot( IIf( ExtraCondition, current_day_10_min_low, Sell_Range_Low ), "Lower Break Down", colorRed, styleLine );


///Buy and Sell StopLoss

Normal_Buy_Stoploss = ( BuyPrice - ( BuyPrice * ( 0.5 / 100 ) ) );
Normal_Sell_Stoploss = ( ShortPrice + ( ShortPrice * ( 0.5 / 100 ) ) );

ExtraCondition_Buy_Stoploss = ( BuyPrice - Current_Day_Range );
ExtraCondition_Sell_Stoploss = ( ShortPrice + Current_Day_Range );

Buy_StopLoss = IIf( ExtraCondition, Max( Normal_Buy_Stoploss , ExtraCondition_Buy_Stoploss ) , Normal_Buy_Stoploss );
Sell_StopLoss = IIf( ExtraCondition, Min( Normal_Sell_Stoploss , ExtraCondition_Sell_Stoploss ), Normal_Sell_Stoploss );

printf( "\n bsl = %.2f \n", Buy_StopLoss );
printf( "\n Sell_StopLoss = %.2f \n", Sell_StopLoss );


Plot( ValueWhen(!IsNull(current_day_10_min_high),Buy_StopLoss), "Buy SL", colorYellow , styleDashed);
Plot( ValueWhen( !IsNull( current_day_10_min_low ), Sell_StopLoss ), "Sell SL", colorRed, styleDashed );


Buy=TimeNum() >= 092000 AND Cross(High,Upper_buy_Range) AND TimeNum()<150000;
Short=TimeNum() >= 092000 AND Cross(Lower_break_Down,Low)  AND TimeNum()<150000;

Buy = Buy AND Sum( Buy, BarsSince( newDay) +1 ) <= 2;
Short = Short AND Sum( Short, BarsSince( newDay) +1 ) <= 2;

Sell = L <= Buy_StopLoss OR TimeNum() > 031000;  
Cover = H >= Sell_StopLoss OR TimeNum() > 031000;
Buy_SL_Hit = L <= Buy_StopLoss;
SellPrice = ValueWhen(Sell, IIf(Buy_SL_Hit,Buy_StopLoss,C));
Short_SL_Hit = H >= Sell_StopLoss;
CoverPrice = ValueWhen(Cover, IIf(Short_SL_Hit,Sell_StopLoss,C));


Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

_SECTION_END();




Hi @fxshrat sir,

I updated the code logic. I need your guidance to set the selling price and cover price.
The strategy should close the position if SL is hit or time >= 3:20. If stop-loss is hit the selling price /cover price should be Buy_StopLoss/ Sell_StopLoss values and if SL is not hit then closing value at 3:20.

I tried to code it, but sell/cover signal is coming at the next bar :frowning: I am not too sure where I am going wrong. Kindly guide. Thanks in advance.

Kind Regards,
Sumit

I even tried this.

Buy=TimeNum() >= 092000 AND Cross(High,Upper_buy_Range) AND TimeNum()<150000;
Short=TimeNum() >= 092000 AND Cross(Lower_break_Down,Low)  AND TimeNum()<150000;

Buy = Buy AND Sum( Buy, BarsSince( newDay) +1 ) <= 2;
Short = Short AND Sum( Short, BarsSince( newDay) +1 ) <= 2;

Sell = L <= Buy_StopLoss OR TimeNum() > 031000;  
Cover = H >= Sell_StopLoss OR TimeNum() > 031000;
SellPrice = (ValueWhen(Sell, IIf(L <= Buy_StopLoss,Buy_StopLoss,C)));
CoverPrice =  (ValueWhen(Cover ,IIf( H >= Sell_StopLoss,Sell_StopLoss,C))); 
Sell = L <= Buy_StopLoss OR TimeNum() > 031000;  
Cover = H >= Sell_StopLoss OR TimeNum() > 031000;

You have to use 24H time format. what you have used is 3:10am
so it will be 151000

Awesome NSM51. Thanks for the reply....

It has been explained many times in this forum already:
For (proper) stop loss (or target stop) use ApplyStop() function (or if it is inevitable then looping).
Looking at your code you only need regular Sell (for time exit) and Applystop.

Your code so far is not correct.