How to plot simple trailing stoploss of fixed points

josh1

Well-Known Member
#11
Only drawback about this is that it assumes that you are continously trading. Either you hold Long or are holding short. There is no concept of NOT HOLDING any position
:lol: Do not hold any position and you are free from Greed and fear and all the anxiety after holding one. I have begun to feel that key to success is in holding position all the time cause if you are out, when market moves, it moves so fast that you cannot enter at the right time.
 

josh1

Well-Known Member
#12
Hi Josh , I was also contemplating on stop loss based on fixed points.

Can you share the exact AFL code which you have mentioned about solving your problem.

Thanks.
This is the code, slightly altered from original by Pottasch.

_SECTION_BEGIN ("Stoploss");

// E.M.Pottasch, Jul 2010
// from Metastock formula, link:http://stocata.org/metastock/stop_trail_atr.html
// added separate parameters for upward and downward market environment

function vstop_func(trBull,trBear)
{
trailArray[ 0 ] = C[ 0 ]; // initialize
for( i = 1; i < BarCount; i++ )
{
prev = trailArray[ i - 1 ];

if (H[ i ] > prev AND H[ i - 1 ] > prev)
{
trailArray[ i ] = Max(prev,H[ i ] - trBull[ i ]);
}
else if (L[ i ] < prev AND L[ i - 1 ] < prev)
{
trailArray[ i ] = Min(prev,L[ i ] + trBear[ i ]);
}
else if (H[ i ] > prev)
{
trailArray[ i ] = H[ i ] - trBull[ i ];
}
else
{
trailArray[ i ] = L[ i ] + trBear[ i ];
}
}
return trailArray;
}

per = Param("per",9, 1, 150, 1);
multBull = Param("multBull",2, 1, 100, 0.05);
multBear = Param("multBear",2, 1, 100, 0.05);


//The next two lines are for ATR based Stop
//trBull = multBull * ATR(per);
//trBear = multBear * ATR(per);

//These two lines are for Fixed Points Stop
trBull = multBull ;
trBear = multBear ;


trailArray = vstop_func(trBull,trBear);

//SetChartBkColor( ParamColor("ColorBG", ColorRGB( 0, 0, 0 ) ) );
//GraphXSpace = 5;
//SetChartOptions(0, chartShowDates);
Plot(IIf(trailArray >
C,trailArray,Null),"\ntrailShort",ParamColor("ColorTrailShort",ColorRGB(255,0,0)),styleStaircase);
Plot(IIf(trailArray <
C,trailArray,Null),"\ntrailLong",ParamColor("ColorTrailLong",ColorRGB(0,255,0)),styleStaircase);
//Plot( C, "\nCandle",colorWhite, styleCandle );


_SECTION_END ();
 

josh1

Well-Known Member
#13
I was trying to include Fixed point Stop in below code to get options for Stoploss mode. Below code is not complete. It has bugs in it. Mastermind may be able to complete it faster.

//Stopeloss Code

StopMode = ParamList("Stop Mode", "Points|Fixed|Chandelier|Modified ATR" );
StopLevel = Param("Fixed perc %", 1, 0.1, 5, 0.1)/100;
StopATRFactor = k;
StopATRPeriod = Per;


// calculate support and resistance levels
if( StopMode == "Fixed" ) // fixed percent trailing stop
ApplyStop( stopTypeLoss, mode = 1, amount = stoplevel, exitatstop = 1, volatile = False, ReEntryDelay = 0 ) ;
else // Chandelier ATR-based stop
if( StopMode == "Chandelier" )
{
sup = C - StopATRFactor * ATR( StopATRPeriod );
res = C + StopATRFactor * ATR( StopATRPeriod );
}
else
if ( StopMode == "Modified ATR" )
{
HL = H - L;
MAHL = 1.5 * MA( HL, StopATRPeriod );
HiLo = IIf( HL < MAHL, HL, MAHL );
H1 = Ref( H, -1 );
L1 = Ref( L, -1 );
C1 = Ref( C, -1 );
Href = IIf( L <= H1, H - C1, ( H - C1 ) - ( L - H1 ) / 2 );
Lref = IIf( H >= L1, C1 - L, ( C1 - L ) - ( L1 - H ) / 2 );

diff1 = Max( HiLo, HRef );
diff2 = Max( diff1, LRef );

ATRmod = Wilders( diff2, StopATRPeriod );

sup = C - StopATRFactor * ATRmod ;
res = C + StopATRFactor * ATRmod ;
}

else
if ( StopMode == "Points" )
{
ApplyStop( stopTypeTrailing, mode = 1, amount = 40, exitatstop = 1, volatile = True, ReEntryDelay = 0 ) ;
sup = H - 40;
res = L + 40 ;
}

Equity( 1, 0 ); // evaluate stops, all quotes
// calculate trailing stop line
trailARRAY = Null;
trailstop = 0;
for( i = 1; i < BarCount; i++ )
{
//if( Started[ i ] == 0 ) continue;

if( C[ i ] > trailstop AND C[ i - 1 ] > trailstop )
trailstop = Max( trailstop, sup[ i ] );
else
if( C[ i ] < trailstop AND C[ i - 1 ] < trailstop )
trailstop = Min( trailstop, res[ i ] );
else
trailstop = IIf( C[ i ] > trailstop, sup[ i ], res[ i ] );

trailARRAY[ i ] = trailstop;
}

// generate buy/sell signals based on crossover with trail stop line
Cover = Cross( C, trailArray );
Short = Cross( trailArray, C );

PlotShapes(Cover*shapeUpArrow,colorYellow,0,trailarray);
PlotShapes(Short*shapeDownArrow,colorYellow,0,trailarray);

//Plot( Close,"Price",colorBlack,styleBar);
//SetBarFillColor( colorYellow );

TRAILCOLOR =IIf(C>trailARRAY,colorAqua,colorYellow);
Plot( trailARRAY,"trailing stop level", TRAILCOLOR, styleStaircase );

//New Code End
 
#14
I was trying to include Fixed point Stop in below code to get options for Stoploss mode. Below code is not complete. It has bugs in it. Mastermind may be able to complete it faster.

//Stopeloss Code

//New Code End
Hi josh1
do you looking like this one
HTML:
Long = ParamToggle("Long","Y|N",1);
Shrt = ParamToggle("Short","Y|N",0);

StopLevel = 1 - Param("trailing stop %", 3, 0.01, 10, 0.01)/100;

if (Long){
Buy = Cross( MACD(), Signal() ) & C > EMA(C,90);;
Sell = 0;
trailARRAYL = Null;
trailstopL = 0;

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

   if( trailstopL == 0 AND Buy[ i ] ) 
   { 
      trailstopL = High[ i ] * stoplevel;
   }
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstopL > 0 AND Low[ i ] < trailstopL )
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstopL;
      trailstopL = 0;
   }

   if( trailstopL > 0 )
   {   
      trailstopL = Max( High[ i ] * stoplevel, trailstopL );
      trailARRAYL[ i ] = trailstopL;
   }

}

PlotShapes(Buy*shapeUpArrow,10,0,Low+1);
PlotShapes(Sell*shapeSmallUpTriangle,10,0,Low+3);

Plot( Close,"C",colorBlack,styleBar);
Plot( trailARRAYL,"trailing stop level", 10 );}

////////////////////////////////////////////////////////////////////////////

if (Shrt){
Short = Cross( Signal(),MACD() ) & C < EMA(C,90);;
Cover = 0;
trailARRAYS = Null;
trailstopS = 0;

for( i = 2; i < BarCount; i++ )
{

   if( trailstopS == 0 AND Short[ i ] ) 
   { 
      trailstopS = Low[ i ] / stoplevel;
   }
   else Short[ i ] = 0; // remove excess buy signals

   if( trailstopS > 0 AND High[ i ] > trailstopS )
   {
      Cover[ i ] = 1;
      CoverPrice[ i ] = trailstopS;
      trailstopS = 0;
   }

   if( trailstopS > 0 )
   {   
      trailstopS = Min( Low[ i ] / stoplevel, trailstopS );
      trailARRAYS[ i ] = trailstopS;
   }

}


PlotShapes(Short*shapeDownArrow,11,0,H+1);
PlotShapes(Cover*shapeSmallDownTriangle,11,0,High+3);

Plot( Close,"C",colorBlack,styleBar);
Plot( trailARRAYS,"trailing stop level", 11 );}
 

mastermind007

Well-Known Member
#15
:lol: Do not hold any position and you are free from Greed and fear and all the anxiety after holding one. I have begun to feel that key to success is in holding position all the time cause if you are out, when market moves, it moves so fast that you cannot enter at the right time.
Did not quite understand what you are trying to tell in line #1 (bolded).

As for your line#2, I hold the opposite view. For me, complete system shud have Buy, Sell, Short, Cover, Keep-away indicators. With limited funds at disposal, being in a non-trending stock is nerve-wrecking not to mention that blocked funds effectively disable you from venturing elsewhere also.
 

mastermind007

Well-Known Member
#17
I was trying to include Fixed point Stop in below code to get options for Stoploss mode. Below code is not complete. It has bugs in it. Mastermind may be able to complete it faster.
Really, Pls describe the bugs in as much detail as possible and I will take a look at it. I have not seen this code before and just from the cursory look at the code, it appears to be half-completed idea.

On other hand, the code snippet I sent you by PM is complete. It is part of trading system that I use. While I am not implying that it is bug-free, it does not have any bugs that I know about. I use another indicators for Buy or Short and use this to trail SL. I do not create trade signals from it even though technically it is possible.
 

josh1

Well-Known Member
#18
Did not quite understand what you are trying to tell in line #1 (bolded).

As for your line#2, I hold the opposite view. For me, complete system shud have Buy, Sell, Short, Cover, Keep-away indicators. With limited funds at disposal, being in a non-trending stock is nerve-wrecking not to mention that blocked funds effectively disable you from venturing elsewhere also.
Okay the bold line means you can select your Stop Mode in Parameters .
Fixed Points| Fixed Percentage | Chandelier (I do not know what that means) and |Modified ATR.

The rest of the code sets Stop according to choice of Mode.
If Points
..........
else
If Fixed
.....
else
If Chandelier
else
if Modified ATR
.........

Yes. Being in a non-trending stock is nerve-wrecking but market often gives false break outs from sideways channel to shake us out and when it makes real move, we do not believe. We feel it is another false break out and then it moves so swiftly that we sit idle watching the long Trend line until we realise that it went to far.
 

mastermind007

Well-Known Member
#19
Okay the bold line means you can select your Stop Mode in Parameters .
Fixed Points| Fixed Percentage | Chandelier (I do not know what that means) and |Modified ATR.

The rest of the code sets Stop according to choice of Mode.
If Points
..........
else
If Fixed
.....
else
If Chandelier
else
if Modified ATR
.........
My guess is that Chandelier is a person's name. Generally very fancy lighting (with lotsa bulbs or candles) in centre of big rooms is also called chandelier, but there seems to be no connection between this stop loss idea and lighting, so name is more likely to be true.

Yes. Being in a non-trending stock is nerve-wrecking but market often gives false break outs from sideways channel to shake us out and when it makes real move, we do not believe. We feel it is another false break out and then it moves so swiftly that we sit idle watching the long Trend line until we realise that it went to far.
Hmmm ... now understand your viewpoint


Lastly, in the code you've posted, the author has attempted to use ApplyStop which is Amibroker's built in function useful to include SL during backtesting. There is no direct provision to draw the lines from there and it seems that whoever wrote this has tried to guess it to be able to create visual indicator for it. ApplyStop has lots of choices so code is incomplete. Visual Indicator are necessity in the environs we trade in (we read a number from Ami and reenter it into trading terminal). I recall seeing a better Chandelier somewhere. Lemme see if I can find it.
 
Last edited:

josh1

Well-Known Member
#20
Okay. Here is working code. I have used Short /Cover for cross of trailing Stop.
Buy/ Sell can be your preferred logic. Four type of stops can be used and set in Parameters. Buy/Sell Price and Stop Price also can be plotted.
Though I have not checked the prices being displayed.

//Stopeloss Code

StopMode = ParamList("Stop Mode", "FixPoints|FixedPercent|Chandelier|Modified ATR" );
StopLevel = Param("Fixed perc %", 1, 0.1, 5, 0.1)/100;
FixedSL = Param("FixSL", 40,1,1,100);
StopATRFactor = k;
StopATRPeriod = Per;


// calculate support and resistance levels
if( StopMode == "FixedPercent" ) // fixed percent trailing stop
{
sup = C * (1- StopLevel);
res = C * (1+ StopLevel);
}
else // Chandelier ATR-based stop
if( StopMode == "Chandelier" )
{
sup = C - StopATRFactor * ATR( StopATRPeriod );
res = C + StopATRFactor * ATR( StopATRPeriod );
}
else
if ( StopMode == "Modified ATR" )
{
HL = H - L;
MAHL = 1.5 * MA( HL, StopATRPeriod );
HiLo = IIf( HL < MAHL, HL, MAHL );
H1 = Ref( H, -1 );
L1 = Ref( L, -1 );
C1 = Ref( C, -1 );
Href = IIf( L <= H1, H - C1, ( H - C1 ) - ( L - H1 ) / 2 );
Lref = IIf( H >= L1, C1 - L, ( C1 - L ) - ( L1 - H ) / 2 );

diff1 = Max( HiLo, HRef );
diff2 = Max( diff1, LRef );

ATRmod = Wilders( diff2, StopATRPeriod );

sup = C - StopATRFactor * ATRmod ;
res = C + StopATRFactor * ATRmod ;
}

else
if ( StopMode == "FixPoints" )
{
ApplyStop( stopTypeTrailing, mode = 1, amount = FixedSL, exitatstop = 1, volatile = True, ReEntryDelay = 0 ) ;
sup = H - FixedSL;
res = L + FixedSL ;
}

Equity( 1, 0 ); // evaluate stops, all quotes
// calculate trailing stop line
trailARRAY = Null;
trailstop = 0;
for( i = 1; i < BarCount; i++ )
{
//if( Started[ i ] == 0 ) continue;

if( C[ i ] > trailstop AND C[ i - 1 ] > trailstop )
trailstop = Max( trailstop, sup[ i ] );
else
if( C[ i ] < trailstop AND C[ i - 1 ] < trailstop )
trailstop = Min( trailstop, res[ i ] );
else
trailstop = IIf( C[ i ] > trailstop, sup[ i ], res[ i ] );

trailARRAY[ i ] = trailstop;
}

// generate buy/sell signals based on crossover with trail stop line
Cover = Cross( C, trailArray );
Short = Cross( trailArray, C );

PlotShapes(Cover*shapeUpArrow,colorYellow,0,trailarray);
PlotShapes(Short*shapeDownArrow,colorYellow,0,trailarray);

//Plot( Close,"Price",colorBlack,styleBar);
//SetBarFillColor( colorYellow );

TRAILCOLOR =IIf(C>trailARRAY,colorAqua,colorYellow);
Plot( trailARRAY,"trailing stop level", TRAILCOLOR, styleStaircase );

//New Code End

Buy = Your Buy Logic ;
Sell = Your Sell Logic;

Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);
Short=ExRem(Short,Cover);
Cover=ExRem(Cover,Short);
BuyPrice = C; // Substitute your own prices
SellPrice = C; // Substitute your own prices

//dist = 1.5*ATR(15);
for( i = 0; i < BarCount; i++ )
{
if( Cover ) PlotText( "Cover@" + C[ i ], i, Halow-31, colorSkyblue );
AlertIf(Buy, "SOUND H:\\AMIBROKER\\Sound\\ding.WAV", "Audio Alert", 1);
if( Short ) PlotText( "Short@" +C[ i ], i, Hahigh+31, colorRose );
AlertIf(Sell, "SOUND H:\\AMIBROKER\\Sound\\tada.WAV", "Sell", 3);
//if( Sell ) PlotText( "Sell@" +H[ i ], i-4, H[ i ]+Trend+50, colorRed, colorRose );
if( Buy ) PlotText("\n Buy\n "+NumToStr(BuyPrice,1.2),i,BuyPrice-10,colorAqua);
if( Sell ) PlotText("\n Sell\n "+NumToStr(SellPrice,1.2),i,SellPrice+30,colorYellow);

}

PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,Halow,-30);
PlotShapes(IIf(Sell, shapeHollowDownTriangle, shapeNone),colorWhite, 0,Hahigh,-15);
PlotShapes(IIf(Cover, shapeHollowUpTriangle, shapeNone),colorWhite, 0,Halow,-15);
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,Hahigh,-30);
PlotShapes( IIf(Buy, shapeSmallCircle, shapeNone),colorRed, 0, BuyPrice, 0 );
PlotShapes( IIf( Sell, shapeSmallCircle, shapeNone),colorBrightGreen, 0 ,SellPrice, 0 );
PlotShapes(Buy*shapeUpArrow,colorYellow,0,trailarray);
PlotShapes(Sell*shapeDownArrow,colorYellow,0,trailarray);

// Plot the Trade Lines
Sig = Buy OR Sell;
y0 = 0;
y1 = C[0];
FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status( "LastVisibleBar" );
CombinedColor = colorWhite;
CombinedLine = Null;

for ( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++ )
{

if ( Buy )
{
Co = colorRed;
TPrice = BuyPrice;
}
else if ( Sell )
{
Co = colorBrightGreen;
TPrice = SellPrice;
}

if ( Sig )

{

x0 = y0;

x1 = y1;

y0 = b;

y1 = TPrice;

La = LineArray( x0, x1, y0, y1 );

CombinedLine = IIf( IsNull( la ), CombinedLine, la );
CombinedColor = IIf( IsNull( La ), CombinedColor, Co );
}
}

Plot( CombinedLine, "", CombinedColor );
 
Last edited:

Similar threads