August 2007
TRADERS' TIPS

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.

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:

TRADESTATION: BUILDING A TRADING TEMPLATE
eSIGNAL: ENTROPIC ANALYSIS OF EQUITY PRICES
WEALTH-LAB: BUILDING A TRADING TEMPLATE
AMIBROKER: BULIDING A TRADING TEMPLATE
NEUROSHELL TRADER: BULIDING A TRADING TEMPLATE
NEOTICKER: BUILDING A TRADING TEMPLATE
AIQ: BUILDING A TRADING TEMPLATE
STRATASEARCH: BUILDING A TRADING TEMPLATE
TRADECISION: BUILDING A TRADING TEMPLATE
TD AMERITRADE'S STRATEGYDESK: STOPS BARRIERS
BLOCKS SOFTWARE: INDUSTRY ANALYSIS TOOLS
NINJATRADER: STOPS BARRIER INDICATOR
VT TRADER: BUILDING A TRADING TEMPLATE
METASTOCK: BUILDING A TRADING TEMPLATE

or return to August 2007 Contents


TRADESTATION: BUILDING A TRADING TEMPLATE

Giorgos Siligardos' article in this issue, "Building A Trading Template," describes using an Excel spreadsheet for managing a portfolio of stocks. The trading rules are roughly based on the trading rules developed by a group of traders known as the Turtles. The rules allow for only long positions (no short sales). The following code simulates a trading history using Siligardos' rules. The simulation is done entirely within TradeStation.

The example EasyLanguage indicator runs in a chart that can contain up to 50 symbols (Figure 1). Some symbols can be hidden (not shown on the chart), if desired. The code automatically determines the number of symbols in the chart, including hidden symbols. Simulated trades occur at the end of each historical daily bar. As processing takes place, the total cost of positions is compared to closed equity. For historical calculations, the code simulates trading for each symbol in the order in which each symbol was inserted in the chart. With live data, the order of calculation will be determined by the order of data arrival. Each trade is recorded in the TradeStation Print Log. The total cost of positions is not allowed to exceed closed equity. Positions are noted on the chart by the plotting of target and stop exit lines for each symbol. The indicator's "ProfitOrCost" input controls whether the indicator plots the total cost of positions or the total cost of equity.

FIGURE 1: TRADESTATION, SYSTEM MANAGEMENT TEMPLATE (SMT). The SMT system is shown in the right pane. Up to 50 securities can be added to the chart. Results are shown as either total equity or cost of positions in the lowest subgraph, based on user input selection. In this graphic, cost of positions is shown. On the left are two charts that compare strategy and indicator trading patterns. All trading for any given date is simulated before the next day is considered. This can be seen in the Print Log pane at the bottom of the graphic, which lists trades for AAPL, GOOG, and TOL on 6/7/2007.
Code for the SMT ("system management template") indicator is provided below. To download the code, go to the Support Center at TradeStation.com. Search for the file "SMT.ELD."

TradeStation does not endorse or recommend any particular strategy.
 

Indicator: SMT Portfolio
inputs:
     ProfitOrCost( 1 ), { 1 = plot profit, any other value plots cost }
    InitialEquity( 50000 ),
    NominalRisk( 2 ), { % }
    VolatilityRisk( 10 ), { % }
    CommissionRatePerShare( 0.01 ), { $ }
    SlippagePercent( 0.2 ), { % }
    Length( 55 ),
    MovementFactor( 0.5 ),
     TargetN ( 8 ),
    MinDRR( 3 ) ;
 
variables:
    TotalClosedEquity( InitialEquity ),
    CostOfPositions( 0 ),
    DataStream( 0 ),
    NumData( 0 ) ;
arrays:
    CumProfit_Loss[50]( 0 ) ;
NumData = NumDataStreams ; { determine the number of
 datastreams }
{ simulate trades in each data stream }
for DataStream = 1 to NumData
    begin
    CumProfit_Loss[DataStream] = SMT_System(
        NominalRisk,
        VolatilityRisk,
        TotalClosedEquity,
        CostOfPositions,
        CommissionRatePerShare,
        SlippagePercent,
        Length,
        MovementFactor,
        TargetN,
        minDRR ) of Data( DataStream ) ;
    end ;
if ProfitOrCost = 1 then
    Plot1( TotalClosedEquity, "Equity" )
else
    Plot2( CostOfPositions, "Cost" ) ;
Function:  NumDataStreams
{ Returns the number of data streams that are currently
inserted into a chart.  Maximum number of data streams
that can be inserted into a chart is 50. }
variables:    NumStreams( 0 ), Counter( 0 ) ;
for Counter = 1 to 50
    begin
    if BarStatus( Counter ) > 0 then
        NumStreams = Counter  ;
    end ;
NumDataStreams =  MaxList( NumDataStreams[1],
 NumStreams ) ;
Function:  SMT_System
inputs:
    NominalRisk( numericsimple ),
    VolatilityRisk( numericsimple ),
    TotalClosedEquity( numericref ),
    CostOfPositions( numericref ),
    CommissionRatePerShare( numericsimple ),
    SlippagePercent( numericsimple ),
    Length( numericsimple ),
    MovementFactor( numericsimple ),
     TargetN ( numericsimple ),
    MinDRR( numericsimple ) ;
variables:
    EstEntry_Price( 0 ),
    MaxShrPct( 0 ),
    MaxShrVolty( 0 ),
    MaxShrUncommit( 0 ),
    StopValue( 0 ),
    BuyNextBarStop( false ),
    EntryStopPrice( 0 ),
    SellNextBarStop( false ),
    ExitStopPrice( 0 ),
    Entry_Price( 0 ),
    Exit_Price( 0 ),
    Current_Shares( 0 ),
    AvgEntry_Price( 0 ),
    Profit_Loss( 0 ),
    CumProfit_Loss( 0 ),
    MP( 0 ),
    N( 0 ),
     TargetValue( 0 ),
     MinStop( 0 ),
    EstEntryPrice( 0 ),
     NumShares( 0 ),
    NumEntries( 0 ),
    TL_ID1( 0 ),
    TL_ID2( 0 ) ;
{ calculate NumShares }
EstEntry_Price = MaxList( Open, EntryStopPrice ) ;
if EstEntry_Price <> StopValue then
    MaxShrPct = TotalClosedEquity * NominalRisk * 0.01 /
     ( EstEntry_Price - StopValue ) ; { max shares based
     on percent of capital ('fund' value, stable equity, etc.) }
if EstEntry_Price <> 0 then
    begin
    MaxShrVolty = TotalClosedEquity * VolatilityRisk * 0.01 / EstEntry_Price ;
    { max shares based on volatility (risk to 'fund' value, stable equity, etc.) }
    MaxShrUncommit = ( TotalClosedEquity - CostOfPositions ) / EstEntry_Price ;
    { max shares based on uncommitted funds }
     end ;
if EstEntry_Price > 0
    and StopValue > 0
    and EstEntry_Price - StopValue > 0
then
    NumShares = MinList( MaxShrPct, MaxShrVolty,
     MaxShrUncommit ) ;
    NumShares = 10 * IntPortion( 0.1 * NumShares ) ;
     { truncate to nearest 10 lot }
{ complete buy orders from prior bar }
if BuyNextBarStop and EntryStopPrice < High then
    begin
    BuyNextBarStop = false ;
    if Current_Shares = 0 then
        begin
        MP = 1 ;
        Entry_Price = EstEntry_Price ;
        AvgEntry_Price = Entry_Price ;
        Current_Shares = NumShares ;
        CostOfPositions = CostOfPositions + NumShares *
         Entry_Price ;
        NumEntries = 1 ;
        if Entry_Price <> StopValue and Entry_Price > 0
         then
            Print( "Buy: ", Symbol, " ", ELDateToString(
             Date ), " ", Entry_Price, " ",
             Current_Shares, " ", TotalClosedEquity,
             " ", CostOfPositions, " ", NominalRisk,
             " ", Entry_Price , " ", StopValue, " ",
             TotalClosedEquity * NominalRisk * 0.01 /
             ( Entry_Price - StopValue ), " ",
             TotalClosedEquity * VolatilityRisk * 0.01 /
             Entry_Price, " ", ( TotalClosedEquity -
             CostOfPositions ) / Entry_Price, " ", NumEntries ) ;
        end
    else
        begin
        if Current_Shares + NumShares <> 0 then
            AvgEntry_Price = ( AvgEntry_Price *
             Current_Shares + Entry_Price *
             NumShares ) / ( Current_Shares + NumShares ) ;
        Current_Shares = Current_Shares + NumShares ;
        CostOfPositions = CostOfPositions + NumShares *
         Entry_Price ;
        NumEntries = NumEntries + 1 ;
         if Entry_Price <> StopValue and Entry_Price <> 0
         then
            Print( "Buy: ", Symbol, " ", ELDateToString(
             Date ), " ", Entry_Price, " ",
             Current_Shares, " ", TotalClosedEquity,
             " ", CostOfPositions, " ", NominalRisk,
             " ", Entry_Price, " ", StopValue, " ",
             TotalClosedEquity * NominalRisk * 0.01 /
             ( Entry_Price - StopValue ), " ",
             TotalClosedEquity * VolatilityRisk * 0.01 /
             Entry_Price, " ", ( TotalClosedEquity -
             CostOfPositions ) / Entry_Price, " ", NumEntries ) ;
        end ;
    end ;
{ complete sell orders from prior bar and deduct commissions }
if SellNextBarStop = true and ExitStopPrice > Low then
    begin
    SellNextBarStop = false ;
    MP = 0 ;
    Exit_Price = MinList( Open, ExitStopPrice ) ;
    Profit_Loss = ( Exit_Price - AvgEntry_Price ) *
     Current_Shares - CommissionRatePerShare *
     Current_Shares * 2 - SlippagePercent * 0.01 *
     Entry_Price * Current_Shares - SlippagePercent *
     0.01 * Exit_Price * Current_Shares ;
    CostOfPositions = CostOfPositions - Current_Shares *
     AvgEntry_Price ;
    Current_Shares = 0 ;
    NumEntries = 0 ;
    TotalClosedEquity = TotalClosedEquity + Profit_Loss ;
    Print( "Sell: ", Symbol, " ", ELDateToString(
     Date ), " ", Exit_Price, " ", TotalClosedEquity,
     " ", CostOfPositions, " ", Profit_Loss ) ;
    end ;
{ recalculate N }
if CurrentBar = 1 then
    N = AvgTrueRange( 20 )
else
    N = ( 19 * N[1] + TrueRange ) * 0.05 ;
{ set up next bar's orders }
if MP = 0 then
    begin
    BuyNextBarStop = true ;
    EntryStopPrice =  Highest( High, Length ) ;
    end
else if NumEntries = 1 then
    begin
    BuyNextBarStop = true ;
    EntryStopPrice =  N * MovementFactor + Entry_Price ;
    end
else if NumEntries = 2 then
    begin
    BuyNextBarStop = true ;
    EntryStopPrice =  N * 2 * MovementFactor +
     Entry_Price ;
    end
else if NumEntries = 3 then
    begin
    BuyNextBarStop = true ;
    EntryStopPrice =  N * 3 * MovementFactor + Entry_Price ;
    end  ;
if FracPortion( EntryStopPrice * 100 ) < 0.05 then
    EntryStopPrice = IntPortion( EntryStopPrice * 100 ) * 0.01
else
    EntryStopPrice = IntPortion( EntryStopPrice * 100 )
     * 0.01 + 0.01 ;
if MP[1] = 0 and MP = 1 then
    begin
    TargetValue = TargetN * N + Entry_Price ;
    if MinDRR <> 0 then
        StopValue = IntPortion( ( Close -
         ( TargetValue - Close ) / MinDRR ) * 100 ) * 0.01 ;
    end
else if MinDRR <> 0 then
    StopValue = IntPortion( MaxList( StopValue, Close -
     ( TargetValue - Close ) / MinDRR ) * 100 ) * 0.01 ;
if MP = 1 then
    begin
    SellNextBarStop = true ;
    ExitStopPrice = StopValue ;
    TL_ID1 = TL_New( Date[1], Time[1], StopValue, Date,
     Time, StopValue ) ;
    TL_ID2 = TL_New( Date[1],Time[1], TargetValue, Date,
     Time, TargetValue ) ;
    end ;
SMT_System = 1 ;
--Mark Mills
TradeStation Securities, Inc.
www.TradeStation.com
GO BACK

eSIGNAL: ENTROPIC ANALYSIS OF EQUITY PRICES

For this month's Traders' Tips, we've provided the formula "Entropy.efs," based on Ron McEwan's article from the November 2006 issue, "Entropic Analysis Of Equity Prices."

The formula parameters may be configured through the Edit Studies option in the Advanced Chart to change the number of periods as well as the color and thickness of the indicator line. The study is a nonprice study by default. To overlay the study on the price window, hold down the Shift key and then drag and drop the indicator pane onto the price window. Figure 2 shows a sample chart.

To discuss this study or download the completed copies of the formulas, please visit the Efs Library Discussion Board forum under the Forums link at www.esignalcentral.com, or visit our Efs KnowledgeBase at www.esignalcentral.com/support/kb/efs/. The eSignal formula scripts (Efs) are also available for copying and pasting from the STOCKS & COMMODITIES website at Traders.com.

FIGURE 2: eSIGNAL, ENTROPIC ANALYSIS OF EQUITY PRICES. Here is a demonstration of Ron McEwan's method of entropic analysis in eSignal.
--Jason Keck
eSignal, a division of Interactive Data Corp.
800 815-8256, www.esignalcentral.com
GO BACK

WEALTH-LAB: BUILDING A TRADING TEMPLATE

In "Building A Trading Template" in this issue, Giorgos Siligardos presents a framework for trade monitoring and evaluation that would be useful for "forward trading."

At Wealth-Lab, we provide similar tools for backtesting. For example, it is relatively easy to keep trading rules (entry and exit criteria) separate from money management (position sizing). "ChartScripts" contains the strategy code to trigger trading alerts for entry and exit orders, while "SimuScripts" can be used to make a determination about the opportunity for each trade and eventually size or reject the position.

This approach allows the Wealth-Lab $imulator tool to carry out realistic historical simulations at the portfolio level; that is, simulating trading many securities at once with each providing information about its own entries and exits, while using a SimuScript to coordinate the trades by filtering out some and finally sizing each position. (See Figure 3.)

FIGURE 3: WEALTH-LAB, SYSTEM TEMPLATE. The standard "Trades" view of a portfolio-level simulation is performed entirely by trading strategy code. Note that most of the fields in the open and closed trades spreadsheets from the SMT Excel workbook are readily included.
That's perfectly fine for simple and many not-so-simple cases, but when total equity, CSA, or other portfolio-level value is required to influence trading decisions (such as adjusting each single security's stop-loss based on current global assets), things are not so easy: trading and money management rules cannot be kept separate anymore. In those cases, a ChartScript that performs a full-fledged simulation on each WatchList security in parallel is required.

More details and a sample script can be found in the Wealth-Lab.com Knowledge Base article, "Interacting dynamically with portfolio level equity."

-- Giorgio Beltrame
www.wealth-lab.com
GO BACK

AMIBROKER: BULIDING A TRADING TEMPLATE

The AmiBroker code for this month's article by Giorgos E. Siligardos, "Building A Trading Template," shows how to calculate the stops barrier indicator. To use it, open the Formula Editor, copy the code, and press the "Apply Indicator" button. Then define the entry date, price target, and MDRR parameter.

The remaining functionality (order tracking, open position reporting, closed trades reporting, portfolio tracking) is provided by AmiBroker's built-in account manager; thus, it does not require any coding. Trailing stops and profit target stops are also built into AmiBroker's automatic analysis system and require no code.
 

EntryDateNum = ParamDate( "EntryDate", "2005-06-23" );
DateAfterEntry = IIf( DateNum() >= EntryDateNum, 1, Null );
target = Param("Price Target", 68, 1, 1E3, 0 );
MinDRR = Param("Minimum Dynamic Reward Risk", 3, 0.01, 100, 0 );
shift = ParamToggle("Mode", "Realistic|Review", 0 );
SB = C - ( Target - C ) / MinDRR;
SBV = DateAfterEntry  * IIf( shift == 0, SB, Ref( SB, -1 ) );
Plot( C, Date() + ", Price", colorBlack, styleCandle );
Plot( target, "PriceTarget", colorBlue );
Plot( SBV, "Stops Barrier"+_PARAM_VALUES(), colorRed, styleThick );
PlotShapes( DateNum() == EntryDateNum * shapeUpArrow, colorBlue, 0, Low, -30 );


A sample chart is shown in Figure 4.

FIGURE 4: AMIBROKER, STOPS BARRIER. Here is a daily chart of AIG with a price target at $68 (blue) and minDDR = 3. The red line represents the stops barrier.


--Tomasz Janeczko, AmiBroker.com
www.amibroker.com

GO BACK


NEUROSHELL TRADER: BULIDING A TRADING TEMPLATE

The system management indicator described by Giorgos Siligardos can be easily implemented in NeuroShell Trader by combining a few of NeuroShell Trader's 800+ indicators.

To implement the primary system management indicators described in the article for an existing trading strategy, select "New Indicator …" from the Insert menu and use the Indicator Wizard to set up the following indicators:

Initial shares to purchase based on risk per trade and Max % stable equity:
Shares = Min2( Divide( Mult( Add2( Initial Equity, NetProfit(Trading Strategy) ),
         Divide(RiskPerTrade%,100) ), Sub( Close , ProtectiveStopPrice ) ),
         Divide( Mult( Add2( Initial Equity, NetProfit(Trading Strategy) ),
         Divide(Max%StableEquity,100) ), Close) )
Barrier for stops (SB) based on MinDRR:
Sub( Close, Divide( Sub ( TargetPrice, Close ), MinDRR ) )
Dynamically Risk / Reward (DRR)
Abs ( Divide ( Mult( Divide(StopPrice, Close), 100 ), Mult( Divide(ExitLimitPrice, Close), 100 ) ) )


A sample chart is in Figure 5. For more information on NeuroShell Trader, visit www.NeuroShell.com.

FIGURE 5: NEUROSHELL TRADER, SYSTEM MANAGEMENT CHART
--Marge Sherald, Ward Systems Group, Inc.
301 662-7950, sales@wardsystems.com
www.neuroshell.com
GO BACK

NEOTICKER: BUILDING A TRADING TEMPLATE

There are three major ideas in Giorgos E. Siligardos' article "Building A Trading Template" about managing target, stop-loss, and trade size based on account size, how successful the method is, and the risk/reward ratio.

Siligardos presents a template to mathematically calculate target, stop-loss, and trade size. Here, we will demonstrate how these three ideas can be implemented in NeoTicker trading system code.

Since we do not have access to the Turtle system entry signals mentioned in the article, we will replace them with moving average crossover signals. The Example Delphi Crossed System (Listing 1) has parameters for users to adjust risk/reward ratio, stop loss %, initial size and target price % (a percentage of entry price is replaced with a fix price for target to automated the process).

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

function ex_del_xcross : double;
Const HSize = 4;
      PrevYearCSA = 0;
      CurrYearCSA = 1;
      CurrPosSize = 2;
      CurrTarget  = 3;
var myx : variant;
    pos_size : integer;
    stop_loss, SB : double;
begin
  if heap.size = 0 then
  begin
    heap.allocate(0);
    heap.fill (0, HSize-1, 0);
    heap.value [CurrPosSize] := params.items ['init size'].int;
    heap.value [PrevYearCSA] := trade.currentcash;
  end;
  // position size is calculated base on comparison of just ended year
  // available cash and previous year available cash
  if ntlib.year(data1.date[0]) <> ntlib.year(data1.date[1]) then
  begin
    //if current year ending cash is better than last year increase size
    if (Heap.value [PrevYearCSA] > Heap.value [CurrYearCSA]) then
       Heap.value [CurrPosSize] := Heap.value [CurrPosSize] +
                                   params.items ['init size'].int
    //reduce position size if size is greater than initial size
    else if (ntlib.trunc(Heap.value [CurrPosSize]) >
            params.items['init size'].int) then
            Heap.value [CurrPosSize] := Heap.value [CurrPosSize] -
                                   params.items ['init size'].int;
    Heap.value [PrevYearCSA] := Heap.value [CurrYearCSA];
  end;
  pos_size := ntlib.trunc(Heap.value [CurrPosSize]);
  //trail stop traget price base on reward/risk ratio
  if trade.openpositionlong and (trade.openpositionPL > 0) then
  begin
    //cancel stop loss and replace it with trial stop
    trade.cancelordersbycomment ('exit long stop loss');
    SB := data1.close [0] - (Heap.value[CurrTarget]/
                             params.items ['Risk/Reward Ratio'].real);
    trade.longexitstop (SB, trade.openpositionsize,
                        otfFillorKill, 'exit long trail profit');
  end;
  if trade.openpositionshort and (trade.openpositionPL > 0) then
  begin
    //cancel stop loss and replace it with trial stop
    trade.cancelordersbycomment ('exit short stop loss');
    SB := data1.close [0] + (Heap.value[CurrTarget]/
                             params.items ['Risk/Reward Ratio'].real);
    trade.shortexitstop (SB, trade.openpositionsize,
                         otfFillorKill, 'exit short trail profit');
  end;
  //calculate stop loss base on account cash
  stop_loss := trade.currentcash * params.items ['stop loss %'].real/100;
  // Simple MA cross is used as signal to demonstrate how ideas about
  // trailing stop, risk/rewoard ratio and position size
  itself.makeindicator ('fma', 'average', ['1'], [param1.str]);
  itself.makeindicator ('sma', 'average', ['1'], [param2.str]);
  myx := itself.makeindicator('mx', 'xcross', ['fma', 'sma'], ['']);
  if trade.openpositionflat and (myx.value [0] > 0) then
  begin
    trade.longatmarket (pos_size, 'long entry');
    trade.longexitstop (data1.close [0]-stop_loss, pos_size,
                        otfGoodtilCancel, 'exit long stop loss');
    Heap.value [CurrTarget] := data1.close [0] *
                               params.items ['target price %'].real/100;
  end;
  if trade.openpositionflat and (myx.value [0] < 0) then
  begin
    trade.shortatmarket (pos_size, 'short entry');
    trade.shortexitstop (data1.close [0]+stop_loss, pos_size,
                         otfGoodtilCancel, 'exit short stop loss');
    Heap.value [CurrTarget] := data1.close [0] *
                               params.items ['target price %'].real/100;
  end;
  result := trade.currentequity;
  Heap.value [CurrYearCSA] := trade.currentcash;
end;
--Kenneth Yuen, TickQuest Inc.
www.tickquest.com
GO BACK

AIQ: BUILDING A TRADING TEMPLATE

The AIQ code for the dynamic reward/risk barrier trailing stop (SB) is given here. Since this is an exit, I needed a system with a conventional trailing stop as a benchmark for comparison. Since the author suggests that the SB is better for trend following and longer-term position trades, I used a 30-day channel breakout system on a portfolio of the iShare ETFs from Barclays.

System rules are detailed within the comments of the code below. I tested the SB stop against a mid-channel trailing stop (MCT). When adding the SB stop, I used the author's suggestion that the SB stop should not be used alone but only as the maximum value for the main trailing stop. In Figure 6, I show a comparison of the MCT (upper red line) to the SB with a minimum reward-to-risk ratio (minDrr) of 3.0 (lower blue line). I also tried other minDrr values. My tests indicate that adding the SB to this particular type of trend-following system did not improve the returns. In fact, the higher I set the value for the minDrr, the lower were my average returns and corresponding Sharpe values. Only when the minDrr value was set to less than 1.0 did the returns come close to the benchmark, MCT. The returns with various minDrr values are shown in the table at the bottom of Figure 6.

FIGURE 6: AIQ, STOPS BARRIER. Here is a comparison of the mid-channel trailing stop (MCT) to the dynamic reward/risk barrier trailing stop (SB) at varying minimum reward/risk levels. The results of this one test are by no means conclusive, and the SB stop may be superior to other trailing stop methods when used with the channel breakout system or a different system. Further testing with each type of system should be done.


I provide the code for the SB, which is to be used as a trailing stop for short positions, but I did not test the short side. The code can be downloaded from the AIQ website at www.aiqsystems.com and also from www.tradersedgesystems.com/traderstips.htm.
 

!! SYSTEM MANAGEMENT (CONSTRUCTING A TEMPLATE FOR)
!  Author: Giorgos E. Siligardos, TASC Aug 2007
!  Coded by: Richard Denning 5/10/07
! The article deals with a barrier trailing stop (SB) which
! will be coded and tested below.
!Formula for the trailing stop barrier (SB):
   ! SB = P - (( PT - P) / minDRR )
     ! P is the current price of the security as of today
     ! PT is the profit target
     ! minDRR is the minimum dynamic reward/risk set by the trader
        ! the author suggests setting the minDRR to 3.00
! TEST OF STOP USING CHANNEL BREAKOUT ON ETFs
! System rules:
  ! Enter a long on the first breakout from a 30 day channel
  ! Use a 60 day rate of change, descending, to select signals
  ! Set profit target to 8 ATRs, initial stop loss at 2.0 ATRs
  ! Set a trailing stop at the highest mid channel since
  !    the position was opened (MCT)
  ! Compare the MCT to the SB type trailing stop
  ! Reverse the rules for a short position
 
! ABBREVIATIONS:
   C    is [close].
   C1    is valresult(C,1).
   L    is [low].
   H    is [high].
   PEP     is {position entry price}.
   PD    is {position days}.
! AVERAGE TRUE RANGE
   TR     is max(H-L,max(abs(H-C1),abs(L-C1))).
   ATR     is simpleavg(TR,60).
! BARRIER TRAILING STOP
   ! Set minimum risk to reward
      minDRR is 2.0.
   ! Set initial stop loss and trailing amount in ATRs
      noATRs is 2.0.
   ! FOR LONG POSITIONS
     PT    is PEP + 8 * ATR.
     SB     is C - ((PT- C) / minDRR).
     SB1    is valresult(SB,1).
  ! FOR SHORT POSITIONS
     SPT    is PEP - noATRs * minDRR * ATR.
     SSB    is C + ((C - SPT) / minDRR).
     SSB1    is valresult(SSB,1).
! CHANNELS
   TopChan is highresult(H,30).
   TopChan1 is valresult(TopChan,1).
   BotChan is lowresult(L,30).
   BotChan1 is valresult(BotChan,1).
! Mid channel for long trailing stops
   MidChan is TopChan - (TopChan - Botchan) / 2.
   MidChan1 is valresult(MidChan,1).
! Mid channel for short trailing stops
   MidChanS is BotChan + (TopChan - Botchan) / 2.
   MidChanS1 is valresult(MidChan,1).
! ENTRY RULES
! Long entry rule
   LE    if C > TopChan1 and countof(C > TopChan1,29,1) = 0 .
! Short entry rule
   SE    if C < BotChan1 and countof(C < Botchan1,29,1) = 0 .
 
! EXIT RULES
! Initial stop loss for longs
   LLX    is PEP - noATRs * ATR.  ! For long positions
! Initial stop loss for shorts
   LSX    is PEP + noATRs * ATR. ! For short positions
! Mid-Channel trailing stop
! For longs
   MidChLX is highresult(MidChan,PD) .
! For shorts
   MidChSX is lowresult(MidChanS,PD) .
! Trailing stop using author's SB concept with
! MidChLX For longs
   TrailLXmidSB    is max(SB1,MidChLX).
! MidChSX for shorts
   TrailSXmidSB    is min(SSB1,MidChSX).
! Combo exit to use as benchmark using MidChLX/SX
! For longs
   LXmid    if C >= PT or  C <= LLX or C <= MidChLX.
! For shorts
   SXmid    if C <= SPT or C >= LSX or C >= MidChSX.
! Combo exit that includes SB trailing stop
! with mid channel for longs
   LXmidSB if C >= PT or  C <= LLX or C <= TrailLXmidSB.
! with mid channel for shorts
   SXbotSB if C <= SPT or C >= LSX or C >= TrailSXmidSB.
! Signal selection - 60 day rate of change percent
   RC60    is (C / valresult(C,60) - 1) * 100.
--Richard Denning
AIQ Systems
richard.denning@earthlink.net
GO BACK

STRATASEARCH: BUILDING A TRADING TEMPLATE

Both money management (MM) and trade management (TM) are integral aspects of a complete trading system, and Giorgos Siligardos has done a very nice job of explaining their importance in his article in this issue, "Building A Trading Template." Indeed, as he states, improper implementation of these aspects can ruin your account in the long run.

Being a portfolio-based system, StrataSearch contains a large number of the discussed MM and TM features already. These features allow users to not only backtest using MM and TM, but also to search for trading systems automatically with these requirements in mind. For example, Siligardos says "having more than 15 to 20 open positions in various unrelated stock generally adds little with respect to diversification." In StrataSearch, therefore, you might select a portfolio size of 20 while viewing the variable trade equity report. When a trade is entered during backtesting, each position's size will then be determined by the current equity divided by that portfolio size of 20. As equity increases over time, so does the position size. Likewise, the position size will decrease automatically as equity decreases. StrataSearch contains a large number of other system management features as well. See Figure 7.

FIGURE 7: STRATASEARCH, EXPORTING POSITIONS FOR THE SYSTEM MANAGEMENT TEMPLATE. The StrataSearch Portfolio Manager provides more than 20 charts and reports for tracking live trades. It also allows exporting of data for use in spreadsheets like Giorgos Siligardos' system management template (SMT).
The stops barrier (SB) is also an effective method for adding additional capability to a trailing stop. Additional information on the stops barrier, as well as information on integrating the StrataSearch data into a spreadsheet such as Giorgos Siligardos' SMT technique, can be found in the Shared area of our user forum at www.StrataSearch.com.
 
//****************************************************************
// Stops Barrier
//****************************************************************
close < C-(($entryprice * @targetPCT)-C)/@minDRR
@targetPC:
    From: 1.05
    To: 1.03
    By: 0.01
@minDRR:
    From: 3
    To: 5
    By: 0.25
--Pete Rast
Avarin Systems, Inc.
www.StrataSearch.com
GO BACK

TRADECISION: BUILDING A TRADING TEMPLATE

In his article "Building A Trading Template," Giorgos Siligardos demonstrates a technique on how to create a system management template (SMT) and apply it to your trading systems.

Tradecision's Indicator Builder enables you to recreate Siligardos' stops barrier (SB) indicator, which is based on the concept of the dynamic reward/risk ratio. Here is the code:
 

input
day1:"Entry Date",24,1,32;
month1:"Entry Month",6,1,12;
year1:"Entry Year",2007,1990,2040;
target:"Price Target",50,0,1000000;
minDRR:"Minimum Dynamic Reward/Risk",3,0.01,100;
end_input
var
date1:=DayOfMonth() = day1 and Month() = month1 and Year() = year1;
{Stops Barrier}SB:=C - (target - C) / minDRR;
end_var
return NthValueWhen(1, date1, 1) *  SB;


(See Figure 8.) To use the stops barrier indicator in Tradecision, visit the area "Traders' Tips from TASC magazine" at https://tradecision.com/support/tasc_tips/tasc_traders_tips.htm or copy the code from the STOCKS & COMMODITIES website at www.Traders.com.

FIGURE 8: TRADECISION, STOPS BARRIER INDICATOR. Here, you see an example of the stops barrier indicator applied to an AIG daily chart with a minDRR of 3 and a target at $71.
--Alex Grechanowski, Alyuda Research, Inc.
sales@tradecision.com, 510 931-7808
www.tradecision.com
GO BACK

TD AMERITRADE'S STRATEGYDESK: STOPS BARRIERS

In "Building A Trading Template" in this issue, Giorgos Siligardos discusses setting trailing stops by calculating a stops barrier. The formula for determining a stops barrier in TD Ameritrade's StrategyDesk is presented here.

StrategyDesk's language allows users to modify existing formulas and to set up custom formulas for backtesting, program trading, and for charting custom indicators. The formula for a stops barrier is straightforward. As a custom indicator, it is:
 

Bar[Close,D,1]  - (((Target Price) - Bar[Close,D,1]) / minDRR)
For a backtest or program trade:
Bar[Close,D] <= Bar[Close,D,1]  - (((Target Price) - Bar[Close,D,1]) / minDRR)


Here, the StrategyDesk "Bar[Close,D,1]" function measures the last price of the tradable on the previous trading day (one day ago) based on daily (D) intervals. The "Bar[Close,D]" function measures the last price of the current trading day. If you prefer a different interval, StrategyDesk offers simple overrides for changing intervals.

The "target price" in the formula can be calculated in one of two ways: 1. Simply use your target price in the formula; 2. Base your target price on the entry price of your trade. This way utilizes the StrategyDesk "EntryPrice" function. For example, if your target is a 10% gain, the formula given above would be modified like this:
 

For a backtest or program trade:
Bar[Close,D] <= Bar[Close,D,1]  - (((EntryPrice * 1.1) - Bar[Close,D,1]) / minDRR)


Dollar gains can also be incorporated (EntryPrice + 5, for example). As referenced in Siligardos' article, the minDRR is a reward/risk multiplier that each investor will choose for themselves. If your reward/risk ratio is 3, for example, simply enter a "3" for minDRR in the above formula. As stated, this formula can be used as a formula in a backtesting window or as part of an automated program trade. Similarly, custom studies can be built with this same logic to plot a dynamic stop barrier on a chart (see Figure 9).

FIGURE 9: STRATEGYDESK, DYNAMIC STOP BARRIER. This chart details a buy at $90.40 on 4/18/2007. The red line represents the stop barrier, based on a target of $125 and a minDRR of 3. As the price goes up, the barrier approaches the bars, eventually meeting the price on a down day. The sell occurred at 118.40 on 6/1/2007.
Figure 9 details a buy at $90.40 on 4/18/2007. The red line represents the stop barrier, based on a target of $125 and a minDRR of 3. Note as the price goes up, the barrier approaches the bars, eventually meeting the price on a down day. The sell occurred at 118.40 on 6/1/2007.

If you have questions about this formula or functionality, please call TD Ameritrade's StrategyDesk help line at 800 228-8056, or access the Help Center from within the StrategyDesk application. StrategyDesk is a downloadable application free for TD Ameritrade clients. Regular commission rates apply.

TD Ameritrade and StrategyDesk do not endorse or recommend any particular trading strategy.

--Jeff Anderson
TD AMERITRADE Holding Corp.
www.TDAmeritrade.com
GO BACK

BLOCKS SOFTWARE: INDUSTRY ANALYSIS TOOLS

This tip is about the various industry analysis tools that are available in Blocks software. To use the studies described here, you will need the free Blocks software and the Strategy Trader data pack. To download the software or for more information on the data packs available, visit www.blocks.com.

Using the studies in Blocks, it's easy to analyze a stock based on its performance within its industry and the performance of that industry against the market as a whole. Figure 12 shows a one-day bar chart of Verisign (VRSN) showing approximately two years of price history in the top pane. VRSN has been in a steady climb since August 2006.

The second pane in the chart is the "Industry Count % of New Lows." This plots the percentage of stocks within an industry that are making new lows for the selected period. In our example, the period is set to 250 on a one-day bar chart to find the percentage of stocks in the industry making a new one-year low.

You can see that just prior to August 2006, the count of stocks in the Internet industry group making new lows spiked to over 15% (see point A; the chart is inverted to show negative values for new lows). This spike in stocks making new one-year lows may indicate a flush-out of sorts within that industry. You can see that VRSN was at or near a new one-year low at that point as well (point B).

In fact, if you look at the industry average in the third pane, you can see that the Internet industry average was also hitting a one-year low (point C).

At the same time, the Internet industry was one of the worst-performing industries in the market as illustrated by the "Rank vs. All Other Industries" plot in the bottom pane of the chart. This study plots the price performance rank of the industry against all other industries over a specified time period. The bottom pane of Figure 10 plots the price performance over the previous 100 days. In August 2006, the Internet stocks had been languishing in the bottom 20% of all industries for six months (point D).

By January 2007, VRSN was up over 35% since the August 2006 lows and the Internet industry's ranking versus all other industries was over 90, meaning the Internet industry as a whole was now outperforming more than 90% of the market (point E).

Heading into 2007, the Internet industry average began to flatten out and its 100-day performance against all other industries begin to falter. It fell all the way back to less than 20 by April 2007. VRSN, however, has continued to do well. It is now up over 20% since January of this year and up 66% since hitting a one-year new low back in August 2006.

To load a copy of the chart shown in Figure 10, click the Start button on the Blocks toolbar, click the Worden folder, then click the S&C Traders Tips folder and you'll see the "Check a stocks industry before you buy" chart tool.

FIGURE 10: BLOCKS, INDUSTRY ANALYSIS. This one-day bar chart of Verisign (VRSN) shows its performance within its industry and the performance of that industry against the market as a whole.
The following additional industry studies are available in the Blocks software as well:
 
Industry Count % New Highs
Industry MACD Histogram
Industry Relative Strength Index (RSI)
Industry Stochastics
Industry Worden Stochastics
Symbol Relative Strength vs. Industry
Industry Time Segmented Volume + (TSV+)
Industry Volume Bars


These studies are prebuilt for you in Blocks, but the software is completely customizable so you can tweak existing studies or create your own from scratch.

To download the free Blocks software, go to www.blocks.com. To get the Blocks Data Packs, call 800 776-4940 and one of our customer service agents will assist you.

--Patrick Argo
Worden Brothers, Inc.
800 776-4940, www.worden.com
GO BACK

NINJATRADER: STOPS BARRIER INDICATOR

The stops barrier (SB) indicator discussed by Giorgos Siligardos in his article, "Building A Trading Template," is now available for download at www.ninjatrader.com/SC/StopsBarrier.zip. Once you have downloaded the indicator, from within the NinjaTrader Control Center window, select the menu File > Utilities > Import NinjaScript and select the downloaded file.

We enhanced the implementation of the indicator by adding the following features:

  • Selection for either a short or long position
  • The plot will terminate at the bar where the target price is reached.
  • A sample chart is shown in Figure 11. 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 the indicator "StopsBarrier." NinjaScript indicators are compiled DLLs that run native, not interpreted, which provides you with the highest performance possible.

    FIGURE 11: NINJATRADER, STOPS BARRIER INDICATOR. This sample NinjaTrader chart demonstrates the stop barrier indicator (blue line) on a MSFT daily chart.
    --Raymond Deux, NinjaTrader, LLC
    www.ninjatrader.com
    GO BACK

    VT TRADER: BUILDING A TRADING TEMPLATE

    Giorgos Siligardos' article in this issue, "Building A Trading Template," discusses using a customized SMT (system management template) to help monitor trades based on trade management and money management rules not necessarily related to mechanical trading methods. Siligardos goes on to discuss the main parts of a customized template created using Microsoft's Excel spreadsheet software as well as money management techniques such as calculating a dynamic risk/reward ratio. Siligardos also discusses an indicator referred to as the stops barrier (SB) indicator.

    We'll be offering the aforementioned Excel-based SMT as well as our version of Siligardos' stops barrier (SB) indicator for download in our user forums.

    FIGURE 12: VT TRADER, STOPS BARRIER INDICATOR. The stops barrier indicator is displayed in the price frame of a GBP/USD daily candlestick chart.
    The VT Trader code and instructions for recreating the SB indicator are as follows:
     
    Stops barrier indicator
    1. Navigator Window>Tools>Indicator Builder>[New] button
    2. In the Indicator Bookmark, type the following text for each field:
    Name: TASC - 08/2007 - Stop Barrier Indicator (SB)
    Short Name: vt_SB
    Label Mask: TASC - 08/2007 - Stop Barrier Indicator (Entry: %month1%/%day1%/%year1%,
          Min. DRR: %minDRR%, Mode: %shift:ls%)
    Placement: Price Frame
    Inspect Alias: Stop Barrier
    3. In the Input Bookmark, create the following variables:
    [New] button... Name: month1 , Display Name: Enter Month , Type: integer , Default: 8
    [New] button... Name: day1 , Display Name: Enter Day , Type: integer , Default: 1
    [New] button... Name: year1 , Display Name: Enter Year , Type: integer , Default: 2007
    [New] button... Name: target , Display Name: Price Target , Type: float , Default: 2
    [New] button... Name: minDRR , Display Name: Minimum Dynamic Risk/Reward , Type: float , Default: 3
    [New] button... Name: shift , Display Name: Calculation Mode , Type: Enumeration , [...] button ,
          [New] button... Realistic, [New] button... Review , [OK] Button , Default: Realistic
    4. In the Output Bookmark, create the following variables:
    [New] button...
    Var Name: DisplaySB
    Name: (Stop Barrier)
    Line Color: green
    Line Width: slightly thicker
    Line Type: solid line
    5. In the Formula Bookmark, copy and paste the following formula:
    {Provided By: VT Systems & CMS FX (c) Copyright 2007}
    {Description: Stop Barrier (SB) Indicator}
    {Notes: August 2007 Issue - "Prepare for the Battlefield,
    Constructing A Template For System Management" by Giorgos E. Siligardos}
    {vt_SB Version 1.0}
    date1:= DayOfMonth()=day1 AND Month()=month1 AND Year()=year1;
    SB:= C - (target-C) / minDRR;
    DisplaySB:= valuewhen(1,date1,1) * if(shift=0, SB, ref(SB,-1));
    6. Click the "Save" icon to finish building the SB indicator.
        To attach the SB indicator to a chart (see Figure 12), click the right mouse button
        within the chart window and select "Add Indicators" -> "TASC - 08/2007 - Stop Barrier
        Indicator (SB)" from the indicator list.
      To learn more about VT Trader, visit www.cmsfx.com.
    --Chris Skidmore
    Visual Trading Systems, LLC (courtesy of CMS Forex)
    (866) 51-CMSFX, trading@cmsfx.com
    www.cmsfx.com
    GO BACK

    METASTOCK: BUILDING A TRADING TEMPLATE

    Editor's note: For the MetaStock code given in Giorgos Siligardos' article, "Building A Trading Template," see this issue or log in to the Subscriber Area at https://technical.traders.com/sub/sublogin.asp.

    GO BACK

    Return to August 2007 Contents

    Originally published in the August 2007 issue of Technical Analysis of STOCKS & COMMODITIES magazine. All rights reserved. © Copyright 2007, Technical Analysis, Inc.