Help with Stop Loss condition on a trading strategy

I am using below afl which I trade on a positional basis the AFL is working fine the only issue is gap up and gap down in market ...In case of Gap up day if price opens above my SL level the position gets exited but in the backtest it takes the lowest price of Stop candle as Stop loss price and not the open price. In live trades the position is exiting at market open however from the AFL backtest results perspective it is taking the lowest price of the SL candle.
Similarly for Gap down if price opens below SL level the backtest result takes high price of the SL candle rather then the open price. Appreciate if anyone in the forum can solution for this Issue

P.S - I am not a technical guy and have a very little knowledge about coding the AFL. I have picked up this AFL from public forum and the backtest results seems good; however due to this issue I have to backtest each candle manually. Appreciate the help and support

function Compute_Trend( HalfLife, ChanLen, startindex, Out_TrendUpArray, Out_TrendDownArray, Out_Trend )
{

    //Init required variables
    TrendUp = VarGet( Out_TrendUpArray );
    TrendDown = VarGet( Out_TrendDownArray );
    trend = VarGet( Out_Trend );

    shrink		= 2 ^ ( -HalfLife );
    shrink2	= 1 - shrink;

    topChan[0]	= High[0];
    botChan[0]	= Low[0];

    HH	= HHV( High, ChanLen );
    LL	= LLV( Low, Chanlen );

    for( i = startindex; i < BarCount - 1; i++ )
    {
        topChan[i] = shrink * H[i] + shrink2 * topChan[i - 1] ;
        botChan[i] = shrink * L[i] + shrink2 * botChan[i - 1] ;

        if( HH[i] >= topChan[i] )	topChan[i] = HH[i];

        if( LL[i] <= botChan[i] )	botChan[i] = LL[i];
    }

    Up = topChan;
    Dn = botChan;
    /*TrendUp=TrendDown=Null;
    trend[0]=1;*/
    changeOfTrend = 0;
    flag = flagh = 0;

    for( i = startindex; i < BarCount - 1; i++ )
    {

        TrendUp[i] = Null;
        TrendDown[i] = Null;
        trend[i] = 1;

        if( Close[i] > Up[i - 1] )
        {
            trend[i] = 1;

            if( trend[i - 1] == -1 ) changeOfTrend = 1;
        }
        else
            if( Close[i] < Dn[i - 1] )
            {
                trend[i] = -1;

                if( trend[i - 1] == 1 ) changeOfTrend = 1;
            }
            else
                if( trend[i - 1] == 1 )
                {
                    trend[i] = 1;
                    changeOfTrend = 0;
                }
                else
                    if( trend[i - 1] == -1 )
                    {
                        trend[i] = -1;
                        changeOfTrend = 0;
                    }

        if( trend[i] < 0 && trend[i - 1] > 0 )
        {
            flag = 1;
        }
        else
        {
            flag = 0;
        }

        if( trend[i] > 0 && trend[i - 1] < 0 )
        {
            flagh = 1;
        }
        else
        {
            flagh = 0;
        }

        if( trend[i] > 0 && Dn[i] < Dn[i - 1] )
        {
            Dn[i] = Dn[i - 1];
        }

        if( trend[i] < 0 && Up[i] > Up[i - 1] )
        {
            Up[i] = Up[i - 1];
        }

        if( flag == 1 )
        {
            Up[i] = topchan[i];
        }

        if( flagh == 1 )
        {
            Dn[i] = botChan[i];
        }

        if( trend[i] == 1 )
        {
            TrendUp[i] = Dn[i];

            if( changeOfTrend == 1 )
            {
                TrendUp[i - 1] = TrendDown[i - 1];
                changeOfTrend = 0;
            }
        }
        else
            if( trend[i] == -1 )
            {
                TrendDown[i] = Up[i];

                if( changeOfTrend == 1 )
                {
                    TrendDown[i - 1] = TrendUp[i - 1];
                    changeOfTrend = 0;
                }

            }

    } //end for

    VarSet( Out_TrendUpArray, TrendUp );
    VarSet( Out_TrendDownArray, TrendDown );
    VarSet( Out_Trend, trend );

}

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

_SECTION_BEGIN( "Range Breakout Strategy 7.0" );


//SetBarsRequired( sbrAll, sbrAll );
SetOption( "InitialEquity", 200000 );
SetTradeDelays( 0, 0, 0, 0 );

Noofcontractparam = Param("No of Contract/share", 1, 1, 500, 1);
Noofcontract = IIf(RoundLotSize>0, RoundLotSize*Noofcontractparam, Noofcontractparam);
SetPositionSize( Noofcontract, spsShares ); // trade 1 contract

PER = Param( "Select Range", 21 );
HalfLife = param( "Channel halflife", 5, 1, 20, 1 );
ChanLen	= param( "Channel length", 21 , 1, 21, 1 );
minperiods = Param( "RWI Min Periods", 9, 1, 200, 1 );
maxperiods = Param( "RWI Max Periods", 40, 1, 200, 1 );

TrendUp = TrendDown = Null;
Trend[0] = 1;

Compute_Trend( HalfLife, ChanLen, 1, "TrendUp", "TrendDown", "Trend" );

BASE_SYMBOL = ParamStr( "Base Symbol?", "Nifty 50" );
VOLUME_THRESHHOLD = Param( "Volume Above ?", 500000, 0, 1000000, 50000 );
CAPITAL = Param( "Initial Capital", 100000, 50000, 500000, 50000 );
Risk_Per_Trade = Param( "Risk per trade", 1, 0.5, 2, 0.1 );
Risk = ( Risk_Per_Trade / 100 ) * CAPITAL;
TickSize = 0.05;

tslmultiple = Param( "TSL Multiple (ATR)", 4, 1, 10, 0.1 );


/*------ Plot EMAs --------*/
Period1 = Param( "EMA Period 1", 10 );
EMA1 = EMA( C, Period1 );
EMA1_COLOR = ParamColor( "Color1", colorRed );
//Plot( EMA1, _DEFAULT_NAME(), EMA1_COLOR, styleLine );


Period2 = Param( "EMA Period 2", 21 );
EMA2 = EMA( C, Period2 );
EMA2_COLOR = ParamColor( "Color2", colorGreen );
//Plot( EMA2, _DEFAULT_NAME(), EMA2_COLOR, styleLine );


Period3 = Param( "EMA Period 3", 50 );
EMA3 = EMA( C, Period3 );
EMA3_COLOR = ParamColor( "Color3", colorBlue );
//Plot( EMA3, _DEFAULT_NAME(), EMA3_COLOR, styleLine );


//tn = TimeNum();
//startTime = 92459; // start in HHMMSS format
//endTime = 150000;  // end in HHMMSS format
//tradeEndTime = 152000;
//timeOK = tn >= startTime AND tn <= endTime;

atrarr = ATR( 14);


range_hi = HHV( H, PER );
range_lo = LLV( L, PER );
range_hi = Ref( range_hi, -1 );
range_lo = Ref( range_lo, -1 );

rh= RWIHi(minperiods, maxperiods)*RWIHi(minperiods, maxperiods);
rl= RWILo(minperiods, maxperiods)*RWILo(minperiods, maxperiods);


//defining entry conditions
Buy0 = H > range_hi AND ( L > range_lo );// AND timeOK;
Sell0 = L < range_lo AND ( H < range_hi );// AND timeOK;

// Volume validation
VOL_PER = 5;
TimeFrameSet( inDaily );
VALID_VOLUME_DAILY = MA(Ref(V,-1), VOL_PER) >= VOLUME_THRESHHOLD AND Ref(V,-1) >= VOLUME_THRESHHOLD;
TimeFrameRestore();
VALID_VOLUME = TimeFrameExpand( VALID_VOLUME_DAILY, inDaily );
Buy0 = Buy0 AND VALID_VOLUME;
Sell0 = Sell0 AND VALID_VOLUME;


Buy1=Sell1=Null;

Buy1 = ( EMA( C, Period1 ) > EMA( C, Period2 ) AND EMA( C, Period2 ) > EMA( C, Period3 ) );
Sell1 = ( EMA( C, Period1 ) < EMA( C, Period2 ) AND EMA( C, Period2 ) < EMA( C, Period3 ) );

Buy1 = Buy1 AND Trend == 1;
Sell1 = Sell1 AND Trend == -1;

Buy1 = Ref(Buy1, -1);
Sell1 = Ref(Sell1, -1);

Buy0 = Buy0 AND Buy1;
Sell0 = Sell0 AND Sell1;

//inilitize buy, sell, short, cover
Buy = Sell = Short = Cover = Null;
tslBarr = tgtBarr = Null;
tslSarr = 99999;
bflag = sflag = 0;
longtrade_stoploss = 0;
longtrade_target = 0;
longtrade_entry = 0;
shorttrade_stoploss = 0;
shorttrade_target = 0;
shorttrade_entry = 0;
buy_init_stoploss=0;short_init_stoploss=0;

for( i = 1; i < BarCount; i++ )
{
    if( Buy0[i] AND bflag == 0 AND sflag == 0 )
    {
        Buy[i] = 1;
        bflag = 1;
        BuyPrice[i] = range_hi[i];
        longtrade_entry = BuyPrice[i];
        
        longtrade_stoploss = Max( tslBarr[i - 1], longtrade_entry - tslmultiple * atrarr[i] );
        //Set the position size for each trade..
        //trade_risk_price = ( longtrade_entry - longtrade_stoploss );

        //if( trade_risk_price > 0 ) PositionSize[i] = ( Risk / trade_risk_price ) * longtrade_entry;
    }

    if( bflag )
    {
        // Trailing stoploss for buy trades
        if( Buy[i] ) tslBarr[i] = Max( tslBarr[i - 1], longtrade_entry - tslmultiple * atrarr[i] );
        else tslBarr[i] = Max( tslBarr[i - 1], H[i] - tslmultiple * atrarr[i] );
    }

    if( ( Sell0[i] OR L[i] <= tslBarr[i - 1] /*OR tn[i] > tradeEndTime*/ ) AND bflag == 1 )
    {
        Sell[i] = 1;
        bflag = 0;
        SellPrice[i] = C[i];
		
        if( L[i] <= tslBarr[i - 1] ) SellPrice[i] = tslBarr[i - 1];
		
		
       
    }

    // Short conditions
    if( Sell0[i] AND sflag == 0 AND bflag == 0 )
    {
        Short[i] = 1;
        sflag = 1;
        ShortPrice[i] = range_lo[i];
        shorttrade_entry = ShortPrice[i];
        
        shorttrade_stoploss = Min( tslSarr[i - 1], shorttrade_entry + tslmultiple * atrarr[i] );

        //Set the position size for each trade..
        //trade_risk_price = ( shorttrade_stoploss - shorttrade_entry );

        //if( trade_risk_price > 0 ) PositionSize[i] = ( Risk / trade_risk_price ) * shorttrade_entry;
    }

    if( sflag )
    {
        if( Short[i] ) tslSarr[i] = Min( tslSarr[i - 1], shorttrade_entry + tslmultiple * atrarr[i] );
        else tslSarr[i] = Min( tslSarr[i - 1], L[i] + tslmultiple * atrarr[i] );

    }

    if( ( Buy0[i] OR H[i] >= tslSarr[i - 1] /*OR tn[i] > tradeEndTime*/ ) AND sflag == 1 )
    {
        Cover[i] = 1;
        sflag = 0;
        CoverPrice[i] = C[i];

        if(H[i] >= tslSarr[i - 1]) CoverPrice[i] = tslSarr[i - 1];
		

    }


}

tslSarr = IIf( tslSarr == 99999, Null, tslSarr );

Plot( tslBarr, "TSL Buy", colorYellow, styleDashed );
Plot( tslSarr, "TSL Short", colorYellow, styleDashed );

Plot( range_hi, "Highest High", colorGreen, styleLine );
Plot( range_lo, "Lowest Low", colorRed, styleLine );

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( Sell, shapeDownArrow, shapeNone ), colorRed, 0, H, 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( Cover, shapeUpArrow, shapeNone ), colorBlue, 0, L, Offset = -45 );

Title = Name() + " " + Interval( 2 ) + " " + Date() + EncodeColor( colorWhite ) + EncodeColor( colorWhite ) + " O: " + O + "  " + "H: " + H + "  " + "L: " + L + "  " + "C: " + C + "  " +
        "\nRange Breakout Strategy 7.0" + " - Buy0: " +  Buy0 + "  Sell0: " + Sell0 + " Range Hi: " + range_hi + " Range Lo: " + range_lo + " SL: " +tslSarr + " BL: " + tslBarr;

_SECTION_END();

1 Like

Your code is currently taking the Close price!

Change to this method:

myLongStop = x;
myShortStop = x;

SellPrice[i] = Min(Open[i], myLongStop[i]);
CoverPrice[i] = Max(Open[i], myShortStop[i]);
1 Like

Hi @TrendSurfer , Thanks for your reply and providing the correct code. As I said I am not a coder myself and picked up this AFL from public site and using it in the Raw form. If you can guide me where I have to replace the given code or if you can provide the updated AFL code that would be great! The issue is only in the cases of GAP up and Gap down days . On normal days as soon as price touches the SL ATR line the SL gets triggered and in the back also it is reflecting correctly so not sure if I the code will be changed for other days as well.Appreciate your support !

Yes and that's fine - but that doesn't mean you make no effort at all!

This is not a 'copy & paste' school nor a free coding service forum. It is however a forum where you have the great luxury of the developer himself participating (which you don't get elsewhere) and many generous people willing to help (for free!).

So you need to at least make an effort at your end and post up your attempted code and you will find you will receive the assistance you are looking for.

1 Like

Apologies, didnt mean to annoy anyone out here and I have always mentioned in my comment that I appreciated all the help that has been provided to me in this group. I was just stating the fact that i am from a non coding background which doesnt know even basics of coding. But again @TrendSurfer Appreciate your support on providing the solution. I would probably reach out to some developer locally and provide this solution. Thanks alot for your help and support!!

That's not necessary, just have a go at it (instead of making no effort) and post up your attempt!

So am I!

@TrendSurfer I have tried to modify the code as suggested by you. I have added the below two additional lines on the code

myLongStop = x;
myShortStop = x;

and replaced the sell price and the cover price code with the code provided by you as below.

SellPrice[i] = Min(Open[i], myLongStop[i]);
CoverPrice[i] = Max(Open[i], myShortStop[i]);

Not sure I have done it correctly but tried , will try to learn coding going forward.

function Compute_Trend( HalfLife, ChanLen, startindex, Out_TrendUpArray, Out_TrendDownArray, Out_Trend )
{

    //Init required variables
    TrendUp = VarGet( Out_TrendUpArray );
    TrendDown = VarGet( Out_TrendDownArray );
    trend = VarGet( Out_Trend );

    shrink		= 2 ^ ( -HalfLife );
    shrink2	= 1 - shrink;

    topChan[0]	= High[0];
    botChan[0]	= Low[0];

    HH	= HHV( High, ChanLen );
    LL	= LLV( Low, Chanlen );

    for( i = startindex; i < BarCount - 1; i++ )
    {
        topChan[i] = shrink * H[i] + shrink2 * topChan[i - 1] ;
        botChan[i] = shrink * L[i] + shrink2 * botChan[i - 1] ;

        if( HH[i] >= topChan[i] )	topChan[i] = HH[i];

        if( LL[i] <= botChan[i] )	botChan[i] = LL[i];
    }

    Up = topChan;
    Dn = botChan;
    /*TrendUp=TrendDown=Null;
    trend[0]=1;*/
    changeOfTrend = 0;
    flag = flagh = 0;

    for( i = startindex; i < BarCount - 1; i++ )
    {

        TrendUp[i] = Null;
        TrendDown[i] = Null;
        trend[i] = 1;

        if( Close[i] > Up[i - 1] )
        {
            trend[i] = 1;

            if( trend[i - 1] == -1 ) changeOfTrend = 1;
        }
        else
            if( Close[i] < Dn[i - 1] )
            {
                trend[i] = -1;

                if( trend[i - 1] == 1 ) changeOfTrend = 1;
            }
            else
                if( trend[i - 1] == 1 )
                {
                    trend[i] = 1;
                    changeOfTrend = 0;
                }
                else
                    if( trend[i - 1] == -1 )
                    {
                        trend[i] = -1;
                        changeOfTrend = 0;
                    }

        if( trend[i] < 0 && trend[i - 1] > 0 )
        {
            flag = 1;
        }
        else
        {
            flag = 0;
        }

        if( trend[i] > 0 && trend[i - 1] < 0 )
        {
            flagh = 1;
        }
        else
        {
            flagh = 0;
        }

        if( trend[i] > 0 && Dn[i] < Dn[i - 1] )
        {
            Dn[i] = Dn[i - 1];
        }

        if( trend[i] < 0 && Up[i] > Up[i - 1] )
        {
            Up[i] = Up[i - 1];
        }

        if( flag == 1 )
        {
            Up[i] = topchan[i];
        }

        if( flagh == 1 )
        {
            Dn[i] = botChan[i];
        }

        if( trend[i] == 1 )
        {
            TrendUp[i] = Dn[i];

            if( changeOfTrend == 1 )
            {
                TrendUp[i - 1] = TrendDown[i - 1];
                changeOfTrend = 0;
            }
        }
        else
            if( trend[i] == -1 )
            {
                TrendDown[i] = Up[i];

                if( changeOfTrend == 1 )
                {
                    TrendDown[i - 1] = TrendUp[i - 1];
                    changeOfTrend = 0;
                }

            }

    } //end for

    VarSet( Out_TrendUpArray, TrendUp );
    VarSet( Out_TrendDownArray, TrendDown );
    VarSet( Out_Trend, trend );

}

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

_SECTION_BEGIN( "Range Breakout Strategy 7.0" );


//SetBarsRequired( sbrAll, sbrAll );
SetOption( "InitialEquity", 200000 );
SetTradeDelays( 0, 0, 0, 0 );

Noofcontractparam = Param("No of Contract/share", 1, 1, 500, 1);
Noofcontract = IIf(RoundLotSize>0, RoundLotSize*Noofcontractparam, Noofcontractparam);
SetPositionSize( Noofcontract, spsShares ); // trade 1 contract

PER = Param( "Select Range", 21 );
HalfLife = param( "Channel halflife", 5, 1, 20, 1 );
ChanLen	= param( "Channel length", 21 , 1, 21, 1 );
minperiods = Param( "RWI Min Periods", 9, 1, 200, 1 );
maxperiods = Param( "RWI Max Periods", 40, 1, 200, 1 );

TrendUp = TrendDown = Null;
Trend[0] = 1;

Compute_Trend( HalfLife, ChanLen, 1, "TrendUp", "TrendDown", "Trend" );

BASE_SYMBOL = ParamStr( "Base Symbol?", "Nifty 50" );
VOLUME_THRESHHOLD = Param( "Volume Above ?", 500000, 0, 1000000, 50000 );
CAPITAL = Param( "Initial Capital", 100000, 50000, 500000, 50000 );
Risk_Per_Trade = Param( "Risk per trade", 1, 0.5, 2, 0.1 );
Risk = ( Risk_Per_Trade / 100 ) * CAPITAL;
TickSize = 0.05;

tslmultiple = Param( "TSL Multiple (ATR)", 4, 1, 10, 0.1 );


/*------ Plot EMAs --------*/
Period1 = Param( "EMA Period 1", 10 );
EMA1 = EMA( C, Period1 );
EMA1_COLOR = ParamColor( "Color1", colorRed );
//Plot( EMA1, _DEFAULT_NAME(), EMA1_COLOR, styleLine );


Period2 = Param( "EMA Period 2", 21 );
EMA2 = EMA( C, Period2 );
EMA2_COLOR = ParamColor( "Color2", colorGreen );
//Plot( EMA2, _DEFAULT_NAME(), EMA2_COLOR, styleLine );


Period3 = Param( "EMA Period 3", 50 );
EMA3 = EMA( C, Period3 );
EMA3_COLOR = ParamColor( "Color3", colorBlue );
//Plot( EMA3, _DEFAULT_NAME(), EMA3_COLOR, styleLine );


//tn = TimeNum();
//startTime = 92459; // start in HHMMSS format
//endTime = 150000;  // end in HHMMSS format
//tradeEndTime = 152000;
//timeOK = tn >= startTime AND tn <= endTime;

atrarr = ATR( 14);


range_hi = HHV( H, PER );
range_lo = LLV( L, PER );
range_hi = Ref( range_hi, -1 );
range_lo = Ref( range_lo, -1 );

rh= RWIHi(minperiods, maxperiods)*RWIHi(minperiods, maxperiods);
rl= RWILo(minperiods, maxperiods)*RWILo(minperiods, maxperiods);


//defining entry conditions
Buy0 = H > range_hi AND ( L > range_lo );// AND timeOK;
Sell0 = L < range_lo AND ( H < range_hi );// AND timeOK;

// Volume validation
VOL_PER = 5;
TimeFrameSet( inDaily );
VALID_VOLUME_DAILY = MA(Ref(V,-1), VOL_PER) >= VOLUME_THRESHHOLD AND Ref(V,-1) >= VOLUME_THRESHHOLD;
TimeFrameRestore();
VALID_VOLUME = TimeFrameExpand( VALID_VOLUME_DAILY, inDaily );
Buy0 = Buy0 AND VALID_VOLUME;
Sell0 = Sell0 AND VALID_VOLUME;


Buy1=Sell1=Null;

Buy1 = ( EMA( C, Period1 ) > EMA( C, Period2 ) AND EMA( C, Period2 ) > EMA( C, Period3 ) );
Sell1 = ( EMA( C, Period1 ) < EMA( C, Period2 ) AND EMA( C, Period2 ) < EMA( C, Period3 ) );

Buy1 = Buy1 AND Trend == 1;
Sell1 = Sell1 AND Trend == -1;

Buy1 = Ref(Buy1, -1);
Sell1 = Ref(Sell1, -1);

Buy0 = Buy0 AND Buy1;
Sell0 = Sell0 AND Sell1;

//inilitize buy, sell, short, cover
Buy = Sell = Short = Cover = Null;
tslBarr = tgtBarr = Null;
tslSarr = 99999;
bflag = sflag = 0;
longtrade_stoploss = 0;
longtrade_target = 0;
longtrade_entry = 0;
shorttrade_stoploss = 0;
shorttrade_target = 0;
shorttrade_entry = 0;
myLongStop = x;
myShortStop = x;

buy_init_stoploss=0;short_init_stoploss=0;

for( i = 1; i < BarCount; i++ )
{
    if( Buy0[i] AND bflag == 0 AND sflag == 0 )
    {
        Buy[i] = 1;
        bflag = 1;
        BuyPrice[i] = range_hi[i];
        longtrade_entry = BuyPrice[i];
        
        longtrade_stoploss = Max( tslBarr[i - 1], longtrade_entry - tslmultiple * atrarr[i] );
        //Set the position size for each trade..
        //trade_risk_price = ( longtrade_entry - longtrade_stoploss );

        //if( trade_risk_price > 0 ) PositionSize[i] = ( Risk / trade_risk_price ) * longtrade_entry;
    }

    if( bflag )
    {
        // Trailing stoploss for buy trades
        if( Buy[i] ) tslBarr[i] = Max( tslBarr[i - 1], longtrade_entry - tslmultiple * atrarr[i] );
        else tslBarr[i] = Max( tslBarr[i - 1], H[i] - tslmultiple * atrarr[i] );
    }

    if( ( Sell0[i] OR L[i] <= tslBarr[i - 1] /*OR tn[i] > tradeEndTime*/ ) AND bflag == 1 )
    {
        Sell[i] = 1;
        bflag = 0;
        SellPrice[i] = Min(Open[i], myLongStop[i]);
		
        if( L[i] <= tslBarr[i - 1] ) SellPrice[i] = tslBarr[i - 1];
		
		
       
    }

    // Short conditions
    if( Sell0[i] AND sflag == 0 AND bflag == 0 )
    {
        Short[i] = 1;
        sflag = 1;
        ShortPrice[i] = range_lo[i];
        shorttrade_entry = ShortPrice[i];
        
        shorttrade_stoploss = Min( tslSarr[i - 1], shorttrade_entry + tslmultiple * atrarr[i] );

        //Set the position size for each trade..
        //trade_risk_price = ( shorttrade_stoploss - shorttrade_entry );

        //if( trade_risk_price > 0 ) PositionSize[i] = ( Risk / trade_risk_price ) * shorttrade_entry;
    }

    if( sflag )
    {
        if( Short[i] ) tslSarr[i] = Min( tslSarr[i - 1], shorttrade_entry + tslmultiple * atrarr[i] );
        else tslSarr[i] = Min( tslSarr[i - 1], L[i] + tslmultiple * atrarr[i] );

    }

    if( ( Buy0[i] OR H[i] >= tslSarr[i - 1] /*OR tn[i] > tradeEndTime*/ ) AND sflag == 1 )
    {
        Cover[i] = 1;
        sflag = 0;
        CoverPrice[i] = Max(Open[i], myShortStop[i]);

        if(H[i] >= tslSarr[i - 1]) CoverPrice[i] = tslSarr[i - 1];
		

    }


}

tslSarr = IIf( tslSarr == 99999, Null, tslSarr );

Plot( tslBarr, "TSL Buy", colorYellow, styleDashed );
Plot( tslSarr, "TSL Short", colorYellow, styleDashed );

Plot( range_hi, "Highest High", colorGreen, styleLine );
Plot( range_lo, "Lowest Low", colorRed, styleLine );

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( Sell, shapeDownArrow, shapeNone ), colorRed, 0, H, 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( Cover, shapeUpArrow, shapeNone ), colorBlue, 0, L, Offset = -45 );

Title = Name() + " " + Interval( 2 ) + " " + Date() + EncodeColor( colorWhite ) + EncodeColor( colorWhite ) + " O: " + O + "  " + "H: " + H + "  " + "L: " + L + "  " + "C: " + C + "  " +
        "\nRange Breakout Strategy 7.0" + " - Buy0: " +  Buy0 + "  Sell0: " + Sell0 + " Range Hi: " + range_hi + " Range Lo: " + range_lo + " SL: " +tslSarr + " BL: " + tslBarr;

_SECTION_END();

'x' is your stop loss value. Replace 'x' with your stop loss variable/s.

Remove excess BuyPrice/SellPrice/ShortPrice/CoverPrice code lines.

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.