TRADERS’ TIPS

May 2009

Here is this month’s selection of Traders’ Tips, contributed by various developers of technical analysis software to help readers more easily implement some of the strategies presented in this and other issues.

Other code appearing in articles in this issue is posted in the Subscriber Area of our website at https://technical.traders.com/sub/sublogin.asp. Login requires your last name and subscription number (from mailing label). Once logged in, scroll down to beneath the “Optimized trading systems” area until you see “Code from articles.” From there, code can be copied and pasted into the appropriate technical analysis program so that no retyping of code is required for subscribers.

You can copy these formulas and programs for easy use in your spreadsheet or analysis software. Simply “select” the desired text by highlighting as you would in any word processing program, then use your standard key command for copy or choose “copy” from the browser menu. The copied text can then be “pasted” into any open spreadsheet or other software by selecting an insertion point and executing a paste command. By toggling back and forth between an application window and the open web page, data can be transferred with ease.

This month’s tips include formulas and programs for:

Return to Contents

TRADESTATION: STOP METHODS

Sylvain Vervoort’s article in this issue, “Using Initial And Trailing Stops,” describes a technique for generating stop-and-reverse trading signals. Once the initial entry is made, any number of reversals may follow. The strategy’s first trade date and first trade direction are established by user inputs.

To download the EasyLanguage code for this study, go to the TradeStation and EasyLanguage Support Forum and search for the file “VervoortPctTrailStop.eld.”

This article is for informational purposes. No type of trading or investment recommendation, advice, or strategy is being made, given or in any manner provided by TradeStation Securities or its affiliates.

Figure 1: TRADESTATION, FIXED-PERCENTAGE TRAILING STOP. The “VervoortPctTrail” strategy is displayed on a chart of Google (GOOG). The levels at which the strategy enters new long positions are displayed by the cyan lines. The short entry levels are displayed by the magenta lines.

Strategy: VervoortPctTrailStop

{ Fixed Percentage Trailing Stop }
inputs:
	Quantity( 100 ),
	InitialMonth( 1 ),
	InitialDay( 1 ),
	InitialYear( 2009 ),
	FirstTrade( 1 ), { enter 1 for Long, any other value
	 for Short }
	Percent( 12 ) ; { trailing stop percentage }

variables:
	WaitingForEntry( true ),
	Trail( 0 ),
	Loss( 0 ),
	LineNum( 0 ),
	ReturnVal( 0 ) ;

Loss = Close * Percent * 0.01 ;

if WaitingForEntry 
	and Year( Date ) + 1900 >= InitialYear
	and Month( Date ) >= InitialMonth 
	and DayOfMonth( Date ) >= InitialDay 
then
	begin
	if FirstTrade = 1 then 
		begin
		Buy Quantity shares this bar Close ;
 	    WaitingForEntry = false ;
		Trail = Close - Loss ;
		end 
	else
		begin
		SellShort Quantity shares this bar at Close ; 
	 	WaitingForEntry = false ;
		Trail = Close + Loss ;
		end ;
	end 
else if WaitingForEntry[1] = false then
	begin
	{ continued long }
	if Close > Trail[1] and Close[1] > Trail[2] then
		Trail = MaxList( Trail[1], Close - Loss )
	{ continued short }
	else if Close < Trail[1] and Close[1] < Trail[2]
	 then
		Trail = MinList( Trail[1], Close + Loss )
	else if Close > Trail[1] then
		Trail = Close - Loss
	else
		Trail = Close + Loss ;

	if MarketPosition = -1 
		and Close > Trail 
		and Trail > 0
	then
		begin
		Buy Quantity shares this bar Close ;
		LineNum = TL_New( Date[1], Time[1], Trail[1],
		 Date, Time, Trail[1] ) ;
		ReturnVal = TL_SetColor( LineNum, Cyan ) ;
		end 
	else if MarketPosition = 1 and Close < Trail then
		begin
		Sellshort Quantity shares this bar at Close ;  
		LineNum = TL_New( Date[1], Time[1], Trail[1],
		 Date, Time, Trail[1] ) ;
		ReturnVal = TL_SetColor( LineNum, Magenta ) ;
		end 
	else if Trail[1] > 0 then
		begin
		LineNum = TL_New( Date[1], Time[1], Trail[1],
		 Date, Time, Trail ) ; 
		if Close > Trail then
			ReturnVal = TL_SetColor( LineNum, Magenta )
		else
			ReturnVal = TL_SetColor( LineNum, Cyan ) ;
		end ;
	end ;

—Mark Mills
TradeStation Securities, Inc.
A subsidiary of TradeStation Group, Inc.
www.TradeStation.com

BACK TO LIST

eSIGNAL: FIXED-PERCENTAGE TRAILING STOP

For this month’s Traders’ Tips, we’ve provided two formulas, FixedPctTrailingStop.efs and FixedPctTrailingStop_Strategy.efs, based on the formula code from Sylvain Vervoort’s article, “Using Initial And Trailing Stops.”

Both formulas plot the fixed-percentage trailing stop (Figure 2). The second formula with “_Strategy” in the filename is also configured for backtesting, which will provide backtest results for either the long or short signals. The formulas contain parameters that may be configured through the Edit Studies option to change the trailing loss periods and several additional options for displaying the trailing stop, labels, arrows, and cursor labels.

To discuss this study or download complete copies of the formula code, please visit the Efs Library Discussion Board forum under the Forums link at www.esignalcentral.com or visit our Efs KnowledgeBase.

Figure 2: eSIGNAL, FIXED-PERCENTAGE TRAILING STOP

Fixed Percentage Trailing Stop_Strategy.efs


/*********************************
Provided By: 
    eSignal (Copyright c eSignal), a division of Interactive Data
    Corporation. 2009. All rights reserved. This sample eSignal
    Formula Script (EFS) is for educational purposes only and may be
    modified and saved under a new file name.  eSignal is not responsible
    for the functionality once modified.  eSignal reserves the right
    to modify and overwrite this EFS file with each new release.
  

Description:       
    Fixed-Percentage Trailing Stop Strategy

Version:            1.0  03/16/2009

Formula Parameters:                     Default:
    Trailing Loss                       14
    Long or Short                       Long
    Show Line Trailing Stop             True
    Show Labels                         True
    Show Arrows                         True
    Display Cursor Labels               True

Notes:
    The related article is copyrighted material. If you are not a 
    subscriber of Stocks & Commodities, please visit www.traders.com.

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

var fpArray = new Array();

function preMain() {
    setPriceStudy(true);
    setStudyTitle("Fixed-Percentage Trailing Stop");
    setCursorLabelName("Trailing Stop", 0);
    setShowTitleParameters(false);

    setDefaultBarFgColor(Color.red, 0);
    setPlotType(PLOTTYPE_LINE, 0);
    setDefaultBarThickness(2, 0);

    askForInput();
    var x=0;
    fpArray[x] = new FunctionParameter("nTrailingLoss", 
                     FunctionParameter.NUMBER);
    with(fpArray[x++]){
        setName("Trailing Loss");
        setLowerLimit(0);       
        setUpperLimit(100);       
        setDefault(14);
    }

    fpArray[x] = new FunctionParameter("sStrategy", 
                     FunctionParameter.STRING);
    with(fpArray[x++]){
        setName("Long or Short");
        addOption("Long");
        addOption("Short");       
        setDefault("Long");
    }

    fpArray[x] = new FunctionParameter("bShowTS", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Show Line Trailing Stop");
        addOption("true");
        addOption("false");       
        setDefault("true");
    }

    fpArray[x] = new FunctionParameter("bShowL", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Show Labels");
        addOption("true");
        addOption("false");       
        setDefault("true");
    }

    fpArray[x] = new FunctionParameter("bShowArrows", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Show Arrows");
        addOption("true");
        addOption("false");       
        setDefault("true");
    }   

    fpArray[x] = new FunctionParameter("ViewValue", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Display Cursor Labels");
        setDefault(true);
    }       
}

var bInit = false;
var bVersion = null;
var nRef = 0;
var xS_R = null;

function main(sStrategy, nTrailingLoss, bShowTS, bShowL, bShowArrows, 
              ViewValue){
var nClose = close(0);
var nClose1 = close(-1);
var nX_R = 0;
var nX_R1 = 0;
    if (bVersion == null) bVersion = verify();
    if (bVersion == false) return;  

    if(bInit==false){
        setShowCursorLabel(ViewValue);
        xS_R = efsInternal("TrailingStop", nTrailingLoss);
        bInit=true;
    }

    if (getCurrentBarIndex() == 0) return;

    nX_R = xS_R.getValue(0);
    nX_R1 = xS_R.getValue(-1);
    if (nX_R1 == null) return;

    if (nClose1 < nX_R1 && nClose > nX_R) {
        if (bShowArrows) drawShape( Shape.UPARROW, BelowBar2, 
                                   Color.green);
        if (sStrategy == "Long") {
            if (bShowL) drawTextRelative(-3, low(0),  " LONG", 
                         Color.white, Color.green, 
                         Text.FRAME, "Arial Black", 10, 
                         "b"+(getCurrentBarCount()), -5);
            Strategy.doLong("Long", Strategy.MARKET, Strategy.THISBAR);
        } else {
            if (bShowL) drawTextRelative(-3, high(0),  " EXIT", 
            Color.white, Color.green, Text.FRAME, "Arial Black", 10, 
             "b"+(getCurrentBarCount()), -5);
            if (Strategy.isShort()) Strategy.doCover("Exit Short", 
            Strategy.MARKET, Strategy.THISBAR);
        }
    }
    if (nClose1 > nX_R1 && nClose < nX_R) {
        if (bShowArrows) drawShape( Shape.DOWNARROW, AboveBar2, 
            Color.red);
        if (sStrategy == "Long") {
            if (bShowL) drawTextRelative(-3, high(0),  " EXIT", 
                Color.white, Color.red, Text.FRAME | Text.TOP, 
                 "Arial Black", 10, "b"+(getCurrentBarCount()), -5);
            if (Strategy.isLong()) Strategy.doSell("Exit Long", 
                Strategy.MARKET, Strategy.THISBAR);
        } else {
            if (bShowL) drawTextRelative(-3, high(0),  "SHORT", 
                Color.white, Color.red, Text.FRAME , "Arial Black", 
                10, "b"+(getCurrentBarCount()), -5);
            Strategy.doShort("Short", Strategy.MARKET, Strategy.
                             THISBAR);
        }   
    }

    if (bShowTS == false) return;
    return xS_R.getValue(0);
}

function TrailingStop(nTrailingLoss){
var Close = close(0);
var loss = Close * nTrailingLoss / 100;
var nRes = 0;
var nRef = ref(-1);
    if (nRef == null) nRef = Close;
    if (Close > nRef && close(-1) > nRef) {
        nRes = Math.max(nRef, Close - loss)
    } else {
        if (Close < nRef && close(-1) < nRef) {
            nRes = Math.min(nRef, Close + loss)
        } else {
            if (Close > nRef) {
                nRes = Close - loss;
            } else {
                nRes = Close + loss;
            }
        }
    }
    return nRes;
}

function verify() {
    var b = false;
    if (getBuildNumber() < 779) {
        drawTextAbsolute(5, 35, "This study requires version 8.0 
                                or later.",
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.
                           RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, "error");
        drawTextAbsolute(5, 20, "Click HERE to upgrade.
                   @URL=https://www.esignal.com/download/default.asp",
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.
                           RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, "upgrade");
        return b;
    } else {
        b = true;
    }
    return b;
}


Fixed Percentage Trailing Stop.efs


/*********************************
Provided By: 
    eSignal (Copyright c eSignal), a division of Interactive Data
    Corporation. 2009. All rights reserved. This sample eSignal
    Formula Script (EFS) is for educational purposes only and may be
    modified and saved under a new file name.  eSignal is not 
    responsible for the functionality once modified.  eSignal reserves 
    the right to modify and overwrite this EFS file with each new 
    release.
  

Description:       
    Fixed-Percentage Trailing Stop

Version:            1.0  03/16/2009

Formula Parameters:                     Default:
    Trailing Loss                       14
    Long or Short                       Long
    Show Line Trailing Stop             True
    Show Labels                         True
    Show Arrows                         True
    Display Cursor Labels               True

Notes:
    The related article is copyrighted material. If you are not a 
    subscriber of Stocks & Commodities, please visit www.traders.com.

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

var fpArray = new Array();

function preMain() {
    setPriceStudy(true);
    setStudyTitle("Fixed-Percentage Trailing Stop");
    setCursorLabelName("Trailing Stop", 0);
    setShowTitleParameters(false);

    setDefaultBarFgColor(Color.red, 0);
    setPlotType(PLOTTYPE_LINE, 0);
    setDefaultBarThickness(2, 0);

    askForInput();
    var x=0;
    fpArray[x] = new FunctionParameter("nTrailingLoss", 
                     FunctionParameter.NUMBER);
    with(fpArray[x++]){
        setName("Trailing Loss");
        setLowerLimit(0);       
        setUpperLimit(100);       
        setDefault(14);
    }

    fpArray[x] = new FunctionParameter("sStrategy", 
                     FunctionParameter.STRING);
    with(fpArray[x++]){
        setName("Long or Short");
        addOption("Long");
        addOption("Short");       
        setDefault("Long");
    }

    fpArray[x] = new FunctionParameter("bShowTS", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Show Line Trailing Stop");
        addOption("true");
        addOption("false");       
        setDefault("true");
    }

    fpArray[x] = new FunctionParameter("bShowL", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Show Labels");
        addOption("true");
        addOption("false");       
        setDefault("true");
    }

    fpArray[x] = new FunctionParameter("bShowArrows", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Show Arrows");
        addOption("true");
        addOption("false");       
        setDefault("true");
    }   

    fpArray[x] = new FunctionParameter("ViewValue", 
                     FunctionParameter.BOOLEAN);
    with(fpArray[x++]){
        setName("Display Cursor Labels");
        setDefault(true);
    }       
}

var bInit = false;
var bVersion = null;
var nRef = 0;
var xS_R = null;

function main(sStrategy, nTrailingLoss, bShowTS, bShowL, 
              bShowArrows, ViewValue){
var nClose = close(0);
var nClose1 = close(-1);
var nX_R = 0;
var nX_R1 = 0;
    if (bVersion == null) bVersion = verify();
    if (bVersion == false) return;  

    if(bInit==false){
        setShowCursorLabel(ViewValue);
        xS_R = efsInternal("TrailingStop", nTrailingLoss);
        bInit=true;
    }

    nX_R = xS_R.getValue(0);
    nX_R1 = xS_R.getValue(-1);
    if (nX_R1 == null) return;

    if (nClose1 < nX_R1 && nClose > nX_R) {
        if (bShowArrows) drawShape( Shape.UPARROW, BelowBar2, 
                                    Color.green);
        if (sStrategy == "Long") {
            if (bShowL) drawTextRelative(-3, low(0),  " LONG", 
              Color.white, Color.green, Text.FRAME, "Arial Black", 10, 
               "b"+(getCurrentBarCount()), -5);
        } else {
            if (bShowL) drawTextRelative(-3, high(0),  " EXIT", 
              Color.white, Color.green, Text.FRAME, "Arial Black", 10, 
                 "b"+(getCurrentBarCount()), -5);
        }
    }
    if (nClose1 > nX_R1 && nClose < nX_R) {
        if (bShowArrows) drawShape( Shape.DOWNARROW, AboveBar2, 
                                    Color.red);
        if (sStrategy == "Long") {
            if (bShowL) drawTextRelative(-3, high(0),  " EXIT", 
         Color.white, Color.red, Text.FRAME | Text.TOP, "Arial Black", 
          10, "b"+(getCurrentBarCount()), -5);
        } else {
            if (bShowL) drawTextRelative(-3, high(0),  "SHORT", 
                   Color.white, Color.red, Text.FRAME , "Arial Black", 
                             10, "b"+(getCurrentBarCount()), -5);
        }   
    }

    if (bShowTS == false) return;
    return xS_R.getValue(0);
}

function TrailingStop(nTrailingLoss){
var Close = close(0);
var loss = Close * nTrailingLoss / 100;
var nRes = 0;
var nRef = ref(-1);
    if (nRef == null) nRef = Close;
    if (Close > nRef && close(-1) > nRef) {
        nRes = Math.max(nRef, Close - loss)
    } else {
        if (Close < nRef && close(-1) < nRef) {
            nRes = Math.min(nRef, Close + loss)
        } else {
            if (Close > nRef) {
                nRes = Close - loss;
            } else {
                nRes = Close + loss;
            }
        }
    }
    return nRes;
}

function verify() {
    var b = false;
    if (getBuildNumber() < 779) {
        drawTextAbsolute(5, 35, "This study requires version 8.0 
        or later.",
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.
                     RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, "error");
        drawTextAbsolute(5, 20, "Click HERE to upgrade.
                @URL=https://www.esignal.com/download/default.asp",
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.
                     RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, "upgrade");
        return b;
    } else {
        b = true;
    }
    return b;
}

ARTICLE


—jason Keck
eSignal, a division of Interactive Data Corp.
800 815-8256, www.esignalcentral.com

BACK TO LIST

WEALTH-LAB: STOP METHODS

Generally, when I think of setting a trailing stop, I immediately reach for Wealth-Lab’s ExitAtTrailingStop function. That method differs from the trailing stop method presented in Sylvain Vervoort’s article in this issue, “Using Initial And Trailing Stops,” which exits a position if the closing price is beyond the stop trigger price. The ExitAtTrailingStop method, on the other hand, immediately exits a position if the stop price is “touched” by any intraday excursion.

The WealthScript code presented here adds two “slider” parameters so that you can easily switch between the two different stop methods as well as the stop percentage in order to make on-the-fly comparisons (Figure 3).

Figure 3: WEALTH-LAB, COMPARISON OF STOP METHODS. In our raw profit backtest, the article’s “stop on close” method had a significantly higher profit than the touch-stop method.

WealthScript Code (C#):
using System;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;

namespace WealthLab.Strategies
{
   public class SAC_FixedPctTrailingStop : WealthScript
   {
      private StrategyParameter _pctTrail = null;
      private  StrategyParameter _touchStop = null;
      public SAC_FixedPctTrailingStop()
      {
         _pctTrail = CreateParameter(“Pct Trail”, 14d, 5d, 30d, 1d);
         _touchStop = CreateParameter(“Touch Stop=1”, 0, 0, 1, 1); 
      }
      
      // Custom indicator
      public DataSeries PercentLine(double pct)
      {
         double perc = 1 - pct/100;
         double perc2 = 1 + pct/100;
         DataSeries result = new DataSeries(Bars, 
                                          “PercentLine(“ + pct + “)”);
         
         // Create the trailing stop series
         bool bull = true;
         result[0] = Close[0] * perc;  
         for(int bar = 1; bar < Bars.Count; bar++)
         {         
            double prev = result[bar - 1];
            if( bull )
            {
               if (Close[bar] >= prev)
                  result[bar] = Math.Max(prev, Close[bar] * perc);
               else
               {
                  bull = false;
                  result[bar] = Close[bar] * perc2;
               }
            }
            else if (Close[bar] <= prev)     
               result[bar] = Math.Min(prev, Close[bar] * perc2);  
            else
            {
               bull = true;
               result[bar] = Close[bar] * perc;
            }   
         }   
         return result;
      }
      
      // Execute the strategy
      protected override void Execute()
      {      
         DataSeries stopLine = PercentLine(_pctTrail.Value);
         PlotSeries(PricePane, stopLine, Color.Blue, LineStyle.Dashed,
                     1);
         
         for(int bar = 1; bar < Bars.Count; bar++)
         {            
            if (IsLastPositionActive)
            {
               Position p = LastPosition;
               if ( _touchStop.ValueInt == 1 )
                  ExitAtTrailingStop(bar + 1, p, stopLine[bar]);
               else
               {
                  if( CrossUnder(bar, Close, stopLine) )
                     SellAtClose(bar, p);
               }               
            }
            else if( CrossOver(bar, Close, stopLine) )
               BuyAtClose(bar);            
         }         
      }
   }
}



—Robert Sucher
TradeStation Securities, Inc.
www.wealth-lab.com

BACK TO LIST

AMIBROKER: INITIAL STOP METHODS

In “Using Initial And Trailing Stops” in this issue, author Sylvain Vervoort compares a fixed-percentage trailing stop with an Atr-based trailing stop. Implementing such stops is easy using the AmiBroker Formula Language thanks to its built-in looping support, so we don’t need any external Dlls.

A ready-to-use formula based on Vervoort’s article is shown in Listing 1. It allows you to use both the fixed-percentage and Atr-based “chandelier” stop. To use it, enter the formula in the Editor, then press “Apply indicator.” To adjust the stop mode and its parameters, click on the chart (Figure 4) with the right-mouse button and select “Parameters” from the context menu.

Figure 4: AMIBROKER, FIXED-PERCENTAGE TRAILING STOP. Here you see a 14% fixed-percentage trailing stop on the daily chart of AMD with buy (green) and sell (red) arrows.

LISTING 1

Version(5.20); // requires v5.20 
SetBarsRequired(sbrAll); 

// get start date 
Start = Cross( DateNum(), ParamDate(„Start date”, „2005-10-30” ) ); 
Started = Flip( Start, 0 ); 

StopMode = ParamToggle(„Stop Mode”, „Fixed|Chandelier” ); 
StopLevel = Param(„Fixed perc %”, 14, 0.1, 50, 0.1)/100; 
StopATRFactor = Param(„Chandelier ATR multiple”, 4, 0.5, 10, 0.1 ); 
StopATRPeriod = Param(„Chandelier ATR period”, 14, 3, 50 ); 

// calculate support and resistance levels 
if( StopMode == 0 ) // fixed percent trailing stop 
{ 
 sup = C * ( 1 - stoplevel ); 
 res = C * ( 1 + stoplevel ); 
} 
else // Chandelier ATR-based stop 
{ 
 sup = C - StopATRFactor * ATR( StopATRPeriod ); 
 res = C + StopATRFactor * ATR( StopATRPeriod ); 
} 

// 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 
Buy = Start OR Cross( C, trailArray ); 
Sell = Cross( trailArray, C ); 

PlotShapes(Buy*shapeUpArrow,colorGreen,0,trailarray); 
PlotShapes(Sell*shapeDownArrow,colorRed,0,trailarray); 

Plot( Close,”Price”,colorBlack,styleBar); 
Plot( trailARRAY,”trailing stop level”, colorRed );

—Tomasz Janeczko
amibroker.com

BACK TO LIST

AIQ: FIXED-PERCENTAGE TRAILING STOP

The Aiq code is shown here for a date-specific version of Sylvain Vervoort’s fixed-percentage trailing stop system described in his article in this issue, “Using Initial And Trailing Stops.”

To use a fixed-percentage trailing stop in a backtest in Aiq, you can use the built-in stop of this nature. Consequently, this type of stop does not need to be coded to be used in either the Eds module or the Portfolio Manager module. The date-specific version (where a start date is manually entered in the Eds code as an input and then the stop starts trailing as of that date) has been coded and provided here. Be sure to set all the inputs to match your objective.

Figure 5: AIQ, FIXED-PERCENTAGE TRAILING STOP. This shows APOL with a 14% trailing stop from an arbitrary entry date of 10/2/2008. The trailing stop was touched on 2/19/2009, which triggered an exit for a profit of 31%.

!! USING INITIAL STOP METHODS (DATE SPECIFIC VERSION)
! Author: Sylvain Vervoort, TASC, May 2009
! Coded by: Richard Denning 3/14/09


! INPUTS:
TLpct  	is 	14.
mo 	is 	10.
da 	is 	2.
yr 	is 	2008.
isLong 	is 	1.          !  1 = for longs, 0 = for shorts

! ABBREVIATIONS:
C is [close].
C1 is valresult(C,1).

! FIXED-PERCENTAGE TRAILING STOP FROM DATE
startDate is makeDate(mo,da,yr).
daysSinceStart is scanany(ruledate() = startDate, 5040) 
	then offSetToDate(month(),day(),year()).
loss  	is C * TLpct / 100.    
longStop 	is C-Loss.
shortStop is C+Loss.
maxVal 	is iff(reportdate() >= startDate,^highresult
               (longStop,^daysSinceStart+1),C). 
minVal 	is iff(reportdate() >= startDate,^lowresult
               (shortStop,^daysSinceStart+1),C).

! PLOT “TRAIL” AS CUSTOM INDICATOR TO SEE STOP ON CHART:
trail is 	iff(reportdate() >= startDate and  isLong = 1,maxVal,
	iff(reportdate() >= startDate and  isLong <> 1,minVal,C)).

Buy 	if reportdate() = startDate and isLong = 1.
Exit 	if C < trail. 
SellShort if reportdate() = startDate and isLong <> 1.
Cover 	if C > trail.

Figure 5 shows a chart of Apol with an arbitrary entry long on 10/2/2009 at the close. The 14% trailing stop then starts on that date and the close stays above the trailing stop until 2/19/2009. This was one of the few long trades that worked out during this time period.

This code can be downloaded from the Aiq website at www.aiqsystems.com and also from www.TradersEdgeSystems.com/traderstips.htm.


—Richard Denning
richard.denning@earthlink.net
for AIQ Systems

BACK TO LIST

TRADERSSTUDIO: FIXED PERCENTAGE TRAILING STOP SYSTEM

The TradersStudio code is given here for the fixed-percentage trailing stop trading system (as well as a date-specific version) along with the indicator code and related functions, based on Sylvain Vervoort’s article in this issue, “Using Initial And Trailing Stops.”

The fixed-percentage trailing stop system is interesting in that it is very simple and has only one parameter. This system, if traded both long and short, would be always in, but the author only trades the long side of the system.

The author tested the system in a period that contained mostly a long-term uptrend, since the test period started in 2003 and ended on 11/10/2008. However, the results from 10/1/2008 to 3/13/2009 are not good, and it seems that both the long and short side should be traded based on some type of general market trend-following filter. Consequently, the coded version that I supply here has options for trading either long only, short only, or both long and short. It also has the option to apply a market trend filter using the Standard & Poor’s 500 index (Spx) to determine whether to trade long or short.

I decided to stick with the author’s list of stocks for the tests. One major advantage to testing with TradersStudio on stocks over some other programs is that both the original, unadjusted price series as well as the split-adjusted series are available in the tests. This can make a big difference in the computation of commissions when commissions are computed based on the number of shares traded, such as is the case with some brokerages. Unless you know the actual price of the stock and the actual number of shares that would have been traded, commissions cannot be computed accurately when using brokers that can’t supply this information.

Figure 6: TRADERSSTUDIO, EQUITY CURVE COMPARISON FOR FIXED-PERCENTAGE TRAILING STOP SYSTEM. This shows a comparison of equity curves: the original system (long only) on the left versus a modified system on the right that trades both long and short and uses a market timing trend filter.

In addition, we are able to correctly apply a minimum-price rule to eliminate very low-priced stocks. When only split-adjusted data is available, we cannot accurately apply a price filter, because we don’t know whether a stock is low-priced due to a split or was actually trading at a low price in real time. TradersStudio also has the ability to compute the dividends that you would have received (or paid, if short).

In Figure 6, I show a comparison of equity curves: The left one represents trading long-only with the Vervoort’s parameter of 14%, versus the equity curve on the right, which represents trading both long and short using a trend filter on the Spx with optimized parameters. To measure the robustness of the parameter sets from the modified system, I show two three-dimensional models in Figure 7.

Figure 7: TRADERSSTUDIO, 3D PARAMETER MAPS. This is an example of three-dimensional parameter maps of the modified system for the two parameters compared to net profit on the left and maximum drawdown on the right.

The left model shows the two parameters compared to the net profit, and the right model shows the two parameters compared to the maximum drawdown. The percent trailing parameter is less sensitive to changes than the market timing trend filter. The range of good parameters is 17% to 23% for the percent trailing stop, and 200 to 300 days for the moving average length on the Spx trend filter. I used the TradersStudio add-in to produce these three dimensional models.

The code can be downloaded from the TradersStudio website at www.TradersStudio.com ->Traders Resources->FreeCode and also from www.TradersEdgeSystems.com/traderstips.htm.

TradersStudio code
  
‘ USING INITIAL STOP METHODS
‘ Author: Sylvain Vervoort, TASC, May 2009
‘ Coded by: Richard Denning 3/14/09

Sub FIXED_PCT_TSSR(tsStartDate,pctTrailValue,longOnly,useMktTm,spxLen)
‘tsStartDate = date that trading is to start after bars back has been 
‘satisfied use TradeStation date format of YYYMMDD example 1/20/2003 
‘= 1030120 pctTrailValue = 11, unitSiz = 1, longOnly = 2 (both long 
‘and short) longOnly = 1 (trade long side only), longOnly = -1 (short 
‘side only)
‘useMktTm = 1 will apply an SPX trend filter so that trades are taken 
‘only in the direction of the trend of the SP500 index; any other value
‘and no market timing filter is applied
Dim unitSiz
Dim trail As BarArray
Dim rsAIQst As BarArray
Dim size As BarArray
Dim SPXc As BarArray
Dim OKtoBuy, OKtoSell
unitSiz = 1
SPXc = C Of independent1
OKtoBuy = SPXc > Average(SPXc,spxLen,0) And SPXc[1] > 
    Average(SPXc,spxLen,1)
OKtoSell = SPXc < Average(SPXc,spxLen,0) And SPXc[1] < 
    Average(SPXc,spxLen,1)
trail = FIXED_PCT_TRAIL_STOP(pctTrailValue)
size = (1000 / TSCLose) / unitSiz

If Not CrossesOver(C,trail,0) And Not CrossesUnder(C,trail,0) Then 
        size = size[1]
If useMktTm = 1 Then
    If Date >= MigrateDate(tsStartDate) Then
        If longOnly >= 1 And OKtoBuy Then
            If CrossesOver(C,trail,0) Then Buy(“LE”,size,0,CloseEntry,
            Day)
            If CrossesUnder(C,trail,0) Then ExitLong(“LX”,””,size[1],
            0,CloseExit,Day)
        End If 
        If (longOnly <= 0 Or longOnly = 2) And OKtoSell Then
            If CrossesUnder(C,trail,0) Then Sell(“SE”,size,0,
                CloseEntry,Day)
            If CrossesOver(C,trail,0) Then ExitShort(“SX”,””,size[1],
                0,CloseExit,Day)
        End If
    End If
Else
    If Date >= MigrateDate(tsStartDate) Then
        If longOnly >= 1 Then
            If CrossesOver(C,trail,0) Then Buy(“LE”,size,0,
               CloseEntry,Day)
            If CrossesUnder(C,trail,0) Then ExitLong(“LX”,””,size[1],
               0,CloseExit,Day)
        End If 
        If (longOnly <= 0 Or longOnly = 2) Then
            If CrossesUnder(C,trail,0) Then Sell(“SE”,size,0,
               CloseEntry,Day)
            If CrossesOver(C,trail,0) Then ExitShort(“SX”,””,size[1],
               0,CloseExit,Day)
        End If
    End If
End If
End Sub

‘---------------------------------------------------------------------

‘ USING INITIAL STOP METHODS
‘ Author: Sylvain Vervoort, TASC, May 2009
‘ Coded by: Richard Denning 3/14/09

Function FIXED_PCT_TRAIL_STOP(pctTrailValue)
Dim loss
Dim longStop
Dim shortStop
Dim maxVal
Dim minVal
Dim trail As BarArray
loss = C * pctTrailValue / 100
longStop = C - loss
shortStop = C + loss
maxVal = Max(trail[1],longStop)
minVal = Min(trail[1],shortStop)
If C>trail[1] And C[1]>trail[2] Then
    trail = maxVal
Else If Ctrail[1] And C[1]trail[2] Then
    trail = shortStop
Else
    trail = C
End If
End If
End If
End If
    
FIXED_PCT_TRAIL_STOP = trail

End Function

‘---------------------------------------------------------------------

‘ USING INITIAL STOP METHODS
‘ Author: Sylvain Vervoort, TASC, May 2009
‘ Coded by: Richard Denning 3/14/09

Function DATE_PCT_TRAIL_STOP(pctTrailValue,tsDate,isLong)
Dim loss
Dim longStop
Dim shortStop
Dim maxVal
Dim minVal
Dim trail As BarArray
Dim reset As BarArray
loss = C * pctTrailValue / 100
longStop = C - loss
shortStop = C + loss
maxVal = Max(trail[1],longStop)
minVal = Min(trail[1],shortStop)
If Date >= MigrateDate(tsDate) Then
    If isLong = 1 Then
        If Date = MigrateDate(tsDate) Then
            trail = longStop
        Else 
            If C > trail[1] Then
                trail = maxVal
                reset = 1
            Else 
                If reset = 1 Or reset[1] = 1 Then 
                    trail = C
                End If
            End If
        End If
    Else 
        If Date = MigrateDate(tsDate) Then
            trail = shortStop
        Else
            If C < trail[1] Then
                trail = minVal
                reset = 1
            Else
                If reset = 1 Or reset[1] = 1 Then 
                    trail = C
                End If
            End If
        End If    
    End If
Else
    trail = C
End If    
    
DATE_PCT_TRAIL_STOP = trail

End Function

‘---------------------------------------------------------------------

‘ USING INITIAL STOP METHODS (INDICATOR1)
‘ Author: Sylvain Vervoort, TASC, May 2009
‘ Coded by: Richard Denning 3/14/09

sub FIXED_PCT_TRAIL_STOP_IND(pctTrailValue)
plot1(FIXED_PCT_TRAIL_STOP(pctTrailValue))
End Sub

‘---------------------------------------------------------------------

‘ USING INITIAL STOP METHODS
‘ Author: Sylvain Vervoort, TASC, May 2009
‘ Coded by: Richard Denning 3/14/09

Sub DATE_PCT_TRAIL_STOP_IND(pctTrailValue,tsDate,isLong)
plot1(DATE_PCT_TRAIL_STOP(pctTrailValue,tsDate,isLong))
End Sub

—Richard Denning
richard.denning@earthlink.net
for TradersStudio

BACK TO LIST

STOCKFINDER: INITIAL STOP METHODS

The fixed-percentage trailing stop method presented in Sylvain Vervoort’s article in this issue can be implemented in StockFinder using RealCode.

RealCode is based on the Microsoft Visual Basic.Net framework and uses the Visual Basic (VB) language syntax. RealCode is compiled into a .Net assembly and run by the StockFinder application. Unlike the scripting language that other trading applications use, RealCode is fully compiled and runs at the same machine-language level as the StockFinder application itself. This gives you unmatched performance running at the same speed as if we (the developers of StockFinder) wrote the code ourselves, with the flexibility of “run-time development and assembly” that you get by writing your own custom code.

The chart in Figure 8 can be added to your layout by clicking the Share menu in StockFinder and looking for fixed-percentage trailing stop on the Chart tab.

Figure 8: STOCKFINDER, FIXED-PERCENTAGE TRAILING STOP. The initial stop is set at the last low point of April 26, 2005, at $13.60 with a trailing stop of 8%. The trade was closed on August 15, 2005, with a nice profit when the closing price dropped below the trailing stop.

Here’s an example of the RealCode used to implement the trailing stop on the chart:

‘# StartMonth = UserInput.Integer = 1
‘# StartDay = UserInput.Integer = 1
‘# StartYear = UserInput.Integer = 2009
‘# Long1Short2 = UserInput.Integer = 1
‘# InitStop = UserInput.Single = 0
‘# Perc = UserInput.Single = 12
Static State As Integer
Static Trail As Single
Static Start As Date
If isFirstBar Then
	If Long1Short2 = 2 Then
		State = -1
	Else
		State = 1
	End If
	Start = New Date(StartYear, StartMonth, StartDay)
	Trail = Single.NaN
End If
If State = 2 Then
	If Price.Last < Trail Then
		State = -2
		Trail = Price.Last * (1 + Perc / 100)
		Label = “Short”
	Else
		Trail = System.Math.Max(Trail, Price.Last * (1 - Perc / 100))
	End If
Else If State = -2 Then
	If Price.Last > Trail Then
		State = 2
		Trail = Price.Last * (1 - Perc / 100)
		Label = “Long”
	Else
		Trail = System.Math.Min(Trail, Price.Last * (1 + Perc / 100))
	End If
Else If State = 1 Then
	If Price.DateValue >= Start Then
		State = 2
		If InitStop > 0 Then
			Trail = InitStop
		Else
			Trail = Price.Last * (1 - Perc / 100)
		End If
		Label = “Long”
	End If
Else If State = -1 Then
	If Price.DateValue >= Start Then
		State = -2
		If InitStop > 0 Then
			Trail = InitStop
		Else
			Trail = Price.Last * (1 + Perc / 100)
		End If
		Label = “Short”
	End If
End If
Plot = Trail

For more information or to start a free trial, please visit www.StockFinder.com.


—Bruce Loebrich and Patrick Argo
Worden Brothers, Inc.

BACK TO LIST

STRATASEARCH: FIXED PERCENTAGE TRAILING STOP

The use of stops in the current market environment is a good idea, so Sylvain Vervoort’s discussion of this subject in this issue in his article, “Using Initial And Trailing Stops,” is timely. Vervoort’s formula for a trailing stop is also a welcome addition to the standard library of stop formulas.

In implementing the fixed-percentage trailing stop (Fpts), the author suggests that it can be used as a full trading system, buying when the closing price rises above the Fpts and selling when the closing price drops below the Fpts. Our tests confirmed that this approach produced profitable results; however, profitability per trade never rose above 50% and the system didn’t do well when tested exclusively in 2008. Thus, the system may not be sufficient on its own without the help of supporting indicators.

Using buy signals from other indicators and using the Fpts exclusively for exiting, the indicator performed quite well. Run against 10,000 unique trading systems, the use of the Fpts clearly decreased the average loss per trade of the system and helped increase the return of the system in general.

StrataSearch users can benefit from this indicator by adding the trailing stop to their automated searches. Alternatively, traders can use the Fpts as their base system and run an automated search to see whether supporting indicators can turn this into a winning system.

As with all other Traders’ Tips, additional information, including plug-ins, can be found in the Shared Area of the StrataSearch user forum.

A sample chart is shown in Figure 9.

Figure 9: STRATASEARCH, Fixed-Percentage Trailing Stop. Using the fixed-percentage trailing stop method exclusively as an exit indicator and not as a trading system on its own, traders should exit their positions when the closing price drops below the fixed-percentage trailing stop line.

//****************************************************
// Fixed-Percentage Trailing Stop
//****************************************************
FPTS_API int FPTS(Prices *pPrices, Values *pResults, 
int nTotDays, Values *pValue, Values *pPercent) {

	int x;
	double loss;
	double trail;
	double PREV=0;

	// bypass first day due to PREV reference
	pResults[0].chIsValid = 0;
	pResults[0].dValue = 0;

	// begin a loop of all the days in the price file
	for(x=0; x<nTotDays; x++) {

		// bypass days that haven’t been seeded
		if(pValue[x].chIsValid != ‘Y’) {
			pResults[x].chIsValid = 0;
			pResults[x].dValue = 0;
			continue;
		}

		loss = pValue[x].dValue * pPercent->dValue / 100;
		if(pValue[x].dValue > PREV && 
pValue[x-1].dValue > PREV) {
			trail = __max(PREV, pValue[x].dValue-loss);
		} else {
			if(pValue[x].dValue < PREV && 
pValue[x-1].dValue < PREV) {
				trail = __min(PREV, pValue[x].dValue+loss);
			} else {
				if(pValue[x].dValue > PREV) {
					trail = pValue[x].dValue-loss;
				} else {
					trail = pValue[x].dValue+loss;
				}
			}
		}

		pResults[x].dValue = trail;
		pResults[x].chIsValid = ‘Y’;
		PREV = trail;
	}
	return 0;
}

—Pete Rast
Avarin Systems Inc.
www.StrataSearch.com

BACK TO LIST

NEUROSHELL TRADER: FIXED-PERCENTAGE TRAILING STOP

The fixed-percentage trailing stop described by Sylvain Vervoort in his article in this issue (“Using Initial And Trailing Stops”) is one of NeuroShell Trader’s 800+ indicators and is easily implemented in a trading system. To recreate Vervoort’s fixed-percentage trailing stop reversal system, select “New Trading Strategy…” from the Insert menu and enter the following in the appropriate locations of the Trading Strategy Wizard:

Long protective stop:

	Trailing Price: Percent( Trading Strategy, 14 )

Short protective stop:

	Trailing Price: Percent( Trading Strategy, 14 )

To recreate the fixed-percentage trailing stop entry/exit system (Figure 10), first set up the reversal system described above and then select “New Trading Strategy…” from the Insert menu and enter the following in the appropriate locations of the Trading Strategy Wizard:

Buy Long when all of the following conditions are true:

Cross Above(High, Trailing Price: Percent( Trading Strategy, 14 )) 

Long protective stop:

Trailing Price: Percent( Trading Strategy #2, 14 )

Figure 10: NEUROSHELL TRADER, FIXED-PERCENTAGE TRAILING STOP SYSTEMS

To create a trailing stop system that is based on both an initial stop and a fixed-percentage trailing stop, enter the following in the appropriate locations of the Trading Strategy Wizard:

Buy Long when all of the following conditions are true:

	High Channel Breakout ( Close, 10 )

Long protective stop:

Value When Entry Activated ( Trading Strategy #3, Minimum (Low, 20), 1 )
Trailing Price: Percent( Trading Strategy #3, 14 )

In his article, Vervoort uses a fixed date entry that restricts backtesting and future trading to a single trade. To avoid this restriction, a high channel breakout entry condition was used. To use this system with your own entry rules, simply substitute your rules for the high channel breakout. In addition, if you want the initial stop to be something other than the most recent low price, simply substitute your initial stop calculation for the minimum price calculation used in the above formula.

If you have NeuroShell Trader Professional, you can also choose whether system parameters should be optimized. After backtesting the trading strategies, use the “Detailed Analysis…” button to view the backtest and trade-by-trade statistics for each strategy.


—Marge Sherald, Ward Systems Group, Inc.
301 662-7950, sales@wardsystems.com
www.neuroshell.com

BACK TO LIST

TRADECISION: STOP METHODS

In his article “Using Initial And Trailing Stops” in this issue, Sylvain Vervoort demonstrates the importance of considering a warning signal and sets the initial stop at the appropriate time to avoid getting stopped out by the normal noise of the market.

Using the Function Builder in Tradecision, you can recreate the PercentTrailingStop function for a fixed-percentage trailing stop value on the closing price, as in the following code:

function (PercLoss:numeric=14):Numeric;
var
perc:=PercLoss;
loss:=C * perc / 100;
trail:=0;
end_var

if HISTORYSIZE>0 then begin

if C>this\1\ AND C\1\ > this\1\  then return Max(this\1\,C-loss);

if C<this\1\ AND C\1\ < this\1\ then return Min(this\1\,C+loss);

if C>this\1\ then return C-loss;
end;
return C+loss;

Then specify the strategy rules in Tradecision’s Strategy Builder:

Entry Long:
if Date() = 080102 then return true;
return false;

Exit Long:
return CrossBelow(PercentTrailingStop(14),C);

Entry Short:
if Date() = 081201 then return true;
return false;

Exit Short:
return CrossAbove(PercentTrailingStop(14),C);

You need to enter the starting date manually, as mentioned in the article. To define Date(), use a numeric value in the YYMMDD format. Date returns “080102” if the day is January 2, 2008, for example.

A sample chart is shown in Figure 11.

Figure 11: TRADECISION, FIXED-PERCENTAGE TRAILING STOP INDICATOR. Here is a demonstration of the 14% fixed trailing stop plotted on a chart of INTC.

To import the strategy into Tradecision, visit the area “Traders’ Tips from Tasc Magazine“ or copy the code from the Stocks & Commodities website at www.traders.com.


—Yana Timofeeva, Alyuda Research
510 931-7808, sales@tradecision.com
www.tradecision.com

BACK TO LIST

NEOTICKER: INITIAL STOP METHODS

In “Using Initial And Trailing Stops” in this issue, Sylvain Vervoort presents code for implementing a percentage stop.

In NeoTicker, the percentage stop is one of the stop methods provided in Backtest EZ (Figure 12). Traders can use these stop methods by simply selecting the desired stop method and entering long/short singles written in NeoTicker formula language in the long entry/short entry condition fields.

Figure 12: NEOTICKER, PERCENTAGE Trailing Stop. In NeoTicker, the percentage stop is one of the stop methods provided in Backtest EZ.

Vervoort’s article gives a percentage trailing stop system that buys when the stock breaks above the trailing stop and uses the trailing stop to exit the long position. This system can be implemented in NeoTicker’s formula language as shown in Listing 1. The code does not include a field for the start date, since the date setting is already available in the indicator system tab.

This system returns two plots: the first plot is the trailing stop plot, and second plot is the equity plot for the system.

LISTING 1
‘trial stop percentage
$prec := choose(param2 < 0, 0, param2 > 100, 100, param2);
$loss := c*$prec/100;
trail := choose(c > trail(1) and c(1) > trail(1),
                maxlist(trail(1), c-$loss),
                c < trail(1) and c(1) < trail(1),
                minlist(trail(1), c+$loss),
                c > trail(1),
                c-$loss, c+$loss);
longatmarket ( c > trail and openpositionflat > 0, defaultordersize,
              “go long when break above trail stop”);
longexitstop ( openpositionlong > 0, trail, defaultordersize, 
               “long exit stop at trail”);
plot1 := trail;
success1 := date(0) > param1;
plto2 := currentequity;

A downloadable version of the system code will be available at the NeoTicker blog site.


—Kenneth Yuen , TickQuest Inc.
www.tickquest.com

BACK TO LIST

VT TRADER: INITIAL STOP METHODS

Our Traders’ Tip submission is inspired by the article “Using Initial And Trailing Stops“ by Sylvain Vervoort in this issue. We’ll be offering the fixed-percentage trailing stop-loss reversal level indicator for download in our online forums. The VT Trader code and instructions for recreating the indicator are as follows:

  1. Navigator Window>Tools>Indicator Builder>[New] button
  2. In the Indicator Bookmark, type the following text for each field:
    Name: TASC - 05/2009 - Trailing Stoploss Reversal Level (Fixed %)
    Short Name: tasc_TSRLFP
    Label Mask: TASC - 05/2009 - Trailing Stoploss Reversal Level 
                (Fixed %%) (%price%,%perc%) | %TSL%
    Placement: Price Frame
    Inspect Alias: tasc_TSRLFP
    
  3. In the Input Bookmark, create the following variables:
    [New] button... Name: price , Display Name: Price , Type: price ,
                     Default: close
     [New] button... Name: perc , Display Name: Trailing Stop % , 
                     Type: float (with bounds) , Default: 1.0000 , 
                     Min. Bounds: 0.0000 , Max. Bounds: 100.0000
  4. In the Output Bookmark, create the following variables:
    [New] button...
    Var Name: TSL
    Name: (TSL)
    Line Color: red
    Line Width: thin
    Line Type: dashed
    
  5. In the Formula Bookmark, copy and paste the following formula:
    {Provided By: Capital Market Services, LLC & Visual Trading 
                           Systems, LLC}
    {Copyright: 2009}
    {Description: TASC, May 2009 - “Stops and More Stops; Using 
                      Initial Stop Methods” by Sylvian Vervoort}
    {File: tasc_TSRLFP.vtsrc - Version 1.0}
    
    Loss:= price * perc/100;
    
    TSL:= if(BarCount()>=2,
          if(ref(price,-1)>PREV(0) AND price>PREV(0),max(PREV(0)
                 ,price-Loss),
          if(ref(price,-1)<PREV(0) AND price<PREV(0),min(PREV(0)
                 ,price+Loss),
          if(Cross(price,PREV(0)),price-Loss,
          if(Cross(PREV(0),price),price+Loss,
          if(price=PREV(0),PREV(0),PREV(0)))))),
          NULL);
  6. Click the “Save” icon to finish building the fixed % trailing stoploss reversal level indicator.

To attach the indicator to a chart (Figure 13), click the right mouse button within the chart window and select “Add Indicator” -> “Tasc - 05/2009 - Trailing Stoploss Reversal Level (Fixed %)” from the indicator list.


Figure 13: VT TRADER, Fixed % Trailing Stop-loss Reversal Level indicator. Here is a demonstration of the fixed-percentage trailing stop-loss reversal level indicator attached to a EUR/USD 30-minute candlestick chart.

To learn more about VT Trader, please visit www.cmsfx.com.


—Chris Skidmore
CMS Forex
(866) 51-CMSFX, trading@cmsfx.com
www.cmsfx.com

BACK TO LIST

NINJATRADER: FIXED-PERCENTAGE TRAILING STOP

The fixed-percentage trailing stop presented by Sylvain Vervoort in “Using Initial And Trailing Stops” in this issue has been implemented as a sample indicator available for download at www.ninjatrader.com/SC/May2009SC.zip.

Once it has been downloaded, from within the NinjaTrader Control Center window, select the menu File > Utilities > Import NinjaScript and select the downloaded file. This indicator is for NinjaTrader version 6.5 or greater.

Figure 14: NINJATRADER, FIXED-PERCENTAGE TRAILING STOP. This screenshot shows the fixed-percent trailing stop indicator running on a daily chart of AAPL.

You can review the indicator’s source code by selecting the menu Tools > Edit NinjaScript > Indicator from within the NinjaTrader Control Center window and selecting “May2009SC.”

NinjaScript strategies are compiled Dlls that run native, not interpreted, which provides you with the highest performance possible.


—Raymond Deux & Josh Pengs
NinjaTrader, LLC
www.ninjatrader.com

BACK TO LIST

WAVE59: FIXED-PERCENTAGE STOP

Sylvain Vervoort’s fixed-percentage stop technique can be implemented in QScript using the following code. Note that Wave59 users can download this script directly from the QScript Library by clicking Scripts: Online QScript Library: Browse and Download from within the software.

#Percent: percentage of closing price to trail by
#Act_as_System: if true, use as trading system, otherwise just lines

input:percent(14),act_as_system(false),color(red),thickness(1);

#initialize variables
if (barnum==barsback) {
   perc=percent/100;
   stopval=close-(close*perc);
   buysell=1;
}

#calculate long stops
if (buysell>0) {
   stopval=close-(close*perc);
   stopval=max(stopval,stopval[1]);
   if (close<stopval) {
      buysell=-1;
      stopval=close+(close*perc);
      if (act_as_system==true) exitlong(0,close,”market”,”onebar”);
   }
}

#calculate stort stops
else if (buysell<0) {
     stopval=close+(close*perc);
     stopval=min(stopval,stopval[1]);
     if (close>stopval) {
        buysell=1;
        stopval=close-(close*perc);
        if (act_as_system==true) buy(1,close,”market”,”onebar”);
     }
}

#plot the lines
plot1=stopval;
color1=color;
thickness1=thickness;

In order to manage an individual position entered on a specific date, a second script will be required. Simply enter the starting date and position direction using the inputs, and the following script will plot the appropriate stop level for each bar until the position is exited.

#Percent: percentage of closing price to trail by
#Startyear, Startmonth, Startday: Day to Begin plotting on

input:startyear(2009),startmonth(1),startday(1),longposition(true),
   percent(14),color(red),thickness(1);

#initialize variables
if (barnum==barsback) {
   startbar=date_to_bar(startyear,startmonth,startday,time);
   perc=percent/100;
   stopval=close-(close*perc);
   buysell=1;
   if (longposition==false) buysell=-1;
   txref=text(barnumber, close, “”, color, tx_left, 8);
}

if (barnum<startbar)
{
   if (buysell>0) stopval=close-(close*perc);
   else stopval=close+(close*perc);
}
else
{
    #calculate long stops
    if (buysell>0) {
       stopval=close-(close*perc);
       stopval=max(stopval,stopval[1]);
       if (close<stopval) {
          buysell=-1;
          stopval=close+(close*perc);
       }
    }

    #calculate stort stops
    else if (buysell<0) {
         stopval=close+(close*perc);
         stopval=min(stopval,stopval[1]);
         if (close>stopval) {
            buysell=1;
            stopval=close-(close*perc);
         }
    }

    #plot the lines
    plot1=stopval;
    color1=color;
    thickness1=thickness;

    #plot a label
    text_setbar(txref,barnum+5);
    text_setprice(txref,stopval);
    text_setstring(txref,to_string(stopval));
}

A sample chart is shown in Figure 15.

Figure 15: WAVE59, fixed-percentage stop. Vervoort’s approach caught the entire bull move up from 2003 in the DJIA, then entered a timely short after the high in early 2008.


—Earik Beann
Wave59 Technologies Int’l, Inc.
www.wave59.com

BACK TO LIST

TRADE-IDEAS: STOP METHODS

“He was utterly fearless but never reckless. He could, and did, turn on a twinkling if he found he was wrong.”—Jesse Livermore, American author and investor

In “Using Initial And Trailing Stops” in this issue, author Sylvain Vervoort offers an analysis of trailing stop methods (specifically the fixed-percentage trailing stop) on a portfolio of 25 stocks for a backtest period ranging from 1/16/2003 to 11/10/2008.

Subscribers to Trade-Ideas Pro who use The OddsMaker, our event-based backtesting tool, already understand the different premise these tools use to find high-probability winning trades. To recap briefly, The OddsMaker doesn’t just look at 25 stocks, à priori, to generate backtest results; instead, it considers any stock that matches a desired pattern in the market, finds that stock, and applies the backtest’s rule set before summing up the results into a detailed set of totals: win rate, average winner, average loser, net winnings, and confidence factor. As such, we provide an alternative stop method for your consideration.

The Wiggle
At Trade-Ideas, we use a custom stop that takes into account a stock’s 15-minute average volatility multiplied by the relative volume (that is, an indexed ratio of what the current volume is over the historical volume of the stock at the time a trade is made). This measure is called the wiggle.

The wiggle can be further explained with an example. Nflx’s 15-minute average volatility would be $0.3306/15 minutes. If the relative volume of Nflx at the time of an alert is 1.5 (that is, trading at 50% above what it normally trades at this time of the day of the alert based on accumulated volume of the day), then the wiggle is $0.50 (that is, $0.3306 * 1.5). Look up the volatility values of any stock at the Trade-Ideas.com Stock Research section. Imagine using a $0.50 stop and attempting to stay in a GS short or long; chances are, you are right on the trade but get stopped out only to watch the stock do exactly what you thought it would, which is painful. The wiggle creates a customized stop that takes into account certain characteristics of each stock.

The wiggle is used in a strategy named “long on % down stocks” and is based on the Trade-Ideas inventory of alerts and filters found in our flagship product, Trade-Ideas Pro. The trading rules are modeled and backtested in its add-on tool, The OddsMaker.

Description:  “Long on % Down Stocks” 
Provided by:
Trade Ideas (copyright © Trade Ideas LLC 2009). All rights reserved. 
For educational purposes only.  Remember these are sketches meant to 
give an idea how to model a trading plan. Trade-Ideas.com and all 
individuals affiliated with this site assume no responsibilities for 
trading and investment results.

Type or copy/paste the following shortened string directly into a browser, then copy/paste the full-length link into Trade-Ideas Pro using the “Collaborate” feature (right-click in any strategy window):

https://bit.ly/1WrpZ     [case sensitive]

This strategy also appears on the Trade-Ideas blog at https://marketmovers.blogspot.com/ or you can build the strategy from the screen capture shown in Figure 16.

Figure 16: TRADE-IDEAS. Here is the combination of alerts and filters used to create the “long on percentage down strategy.”

Figure 16 shows the configuration of this strategy, where one alert and nine filters are used with the following settings:

  • % down for the day, 3%
  • Min price filter = 5 ($)
  • Max price filter = 40 ($)
  • Min spread = 10 (pennies)
  • Max spread = 150 (pennies)
  • Max distance from inside market filter = 0.01 (%)
  • Min daily volume filter = 50,000 (shares/day)
  • Max daily volume filter = 2,000,000 (shares/day)
  • Min today’s range = 55%
  • Min up from close = -10%

The definitions of these indicators appear here: https://www.trade-ideas.com/Help.html.

That’s the strategy, but what about the trading rules? How should the opportunities that the strategy finds be traded? Here is what The OddsMaker tested for the past four weeks ended 3/16/2009 given the following trade rules:

  • On each alert, buy long the symbol (price moves up to be a successful trade)
  • Schedule an exit for the stocks 30 minutes after entry
  • Start trading from the open and stop trading five minutes later (or 385 minutes before market close)
  • Set a stop at $0.75 + the value of each stock’s wiggle.

The OddsMaker summary provides the evidence of how well this strategy and our trading rules did. The settings are shown in Figure17.

Figure 17: TRADE-IDEAS, ODDSMAKER. Shown here is the OddsMaker backtesting configuration for the “long on percentage down strategy.”

The results (last backtested for the four-week period ended 3/16/2009) are shown in Figure 18.

Figure 18: TRADE-IDEAS, RESULTS. Here is the OddsMaker results for the “long on percentage down strategy.”

The summary reads as follows: This strategy generated 291 trades of which 229 were profitable for a win rate of 78.69%. The average winning trade generated $0.42 in profit and the average loser lost $0.44. The net winnings of using this strategy for 20 trading days generated $72.78 points. If you normally trade in 100-share lots, this strategy would have generated $7278. The z-score or confidence factor that the next set of results will fall within this strategy’s average winner and loser is 100%.

Learn about these backtest results from The OddsMaker in more detail by reading the user’s manual at https://www.trade-ideas.com/OddsMaker/Help.html.


—Dan Mirkin and David Aferiat
david@trade-ideas.com
Trade Ideas, LLC
www.trade-ideas.com

BACK TO LIST

METASTOCK: FIXED PERCENTAGE STOP

The code for MetaStock to implement the fixed-percentage stop method, as described by author Sylvain Vervoort In “Using Initial And Trailing Stops” in this issue, is provided below.

 {SVE_Stop_Trail%_Date: Fixed percentage trailing stop from date}
InpMonth:=Input("Month",1,12,1);
InpDay:=Input("Day",1,31,1);
InpYear:=Input("Year",1800,2050,2009);
LongShort:=Input("1=Long or 2=Short? ",1,2,1);
InitStop:=Input("Initial Stop Price",0.1,10000,10);
Perc:=Input("Trailing Stop Percentage",1,30,12);
Loss:=C*Perc/100;
Entry:= InpYear=Year() AND InpMonth=Month() AND InpDay=DayOfMonth();
StopLong:=ExtFml("AdvancedStop.StopLong", Entry,InitStop,0,C-Loss,0,0,0,0);
StopShort:=ExtFml("AdvancedStop.StopShort",Entry,
Initstop,0,C+Loss,0,0,0,0);
Trail:=If(LongShort=1,Stoplong,Stopshort);
Trail 

—Sylvain Vervoort
sve.vervoort@scarlet.be
https://stocata.org

BACK TO LIST

Return to Contents