ATR Afl
ATR Afl
ATR Afl
1 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
TRADERS TIPS
June 2009
Here is this months 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 http://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.
9/27/2009 8:11 AM
2 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
InitialDay( 1 ),
InitialYear( 2009 ),
FirstTrade( 1 ) ; { enter 1 for long, any other
number for short }
variables:
Loss( 0 ),
HiLo( 0 ),
HRef( 0 ),
LRef( 0 ),
HiLoHRefMax( 0 ),
HiLoHRefMaxLRefMax( 0 ),
ATRMod( 0 ),
WaitingForEntry( true ),
Trail( 0 ),
LineNum( 0 ),
ReturnVal( 0 ) ;
if TrailType <> 1 then
Loss = ATR_Factor * AvgTrueRange( ATR_Period )
else
begin
HiLo = iff( High - Low < 1.5 * Average( High - Low,
ATR_Period ), High - Low, 1.5 * Average( High Low, ATR_Period ) ) ;
HRef = iff( Low <= High[1], High - Close[1],( High Close[1] ) - 0.5 * ( Low - High[1] ) ) ;
LRef = iff( High >= Low[1], Close[1] - Low,
( Close[1] - Low ) - 0.5 * ( Low[1] - High ) ) ;
HiLoHRefMax = Maxlist( HiLo, HRef ) ;
HiLoHRefMaxLRefMax = Maxlist( HiLoHRefMax, LRef ) ;
ATRMod = XAverage( HiLoHRefMaxLRefMax, 2 *
ATR_Period - 1 ) ;
Loss = ATR_Factor * ATRMod ;
end ;
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
Sell short Quantity shares this bar at Close ;
WaitingForEntry = false ;
Trail = Close + Loss ;
end ;
end
else if WaitingForEntry[1] = false then
begin
if Close > Trail[1] and Close[1] > Trail[2] then
{ continued long }
Trail = MaxList( Trail[1], Close - Loss )
else if Close < Trail[1] and Close[1] < Trail[2]
then
{ continued short }
Trail = MinList( Trail[1], Close + Loss )
else if Close > Trail[1] then
{ close is above trail }
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
Sell short 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
9/27/2009 8:11 AM
3 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
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
ATR_TrailingStop.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:
Average True Range Trailing Stops, by Sylvain Vervoort
Version:
1.0
04/09/2009
Formula Parameters:
ATR Period
ATR Multiplication
Long or Short
Show Line Trailing Stop
Show Labels
Show Arrows
Display Cursor Labels
Line Color
Default:
5
3.5
Long
True
True
True
True
Red
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("ATR Trailing Stops");
setCursorLabelName("ATR Trailing Stop", 0);
setShowTitleParameters(false);
setDefaultBarFgColor(Color.red, 0);
setPlotType(PLOTTYPE_LINE, 0);
setDefaultBarThickness(2, 0);
9/27/2009 8:11 AM
4 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
setDefaultBarThickness(2, 0);
askForInput();
var x=0;
fpArray[x] = new FunctionParameter("nATRPeriod", FunctionParameter.NUMBER);
with(fpArray[x++]){
setName("ATR Period");
setLowerLimit(1);
setUpperLimit(100);
setDefault(5);
}
fpArray[x] = new FunctionParameter("nATRMultip", FunctionParameter.NUMBER);
with(fpArray[x++]){
setName("ATR Multiplication");
setLowerLimit(1);
setUpperLimit(10);
setDefault(3.5);
}
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);
}
fpArray[x] = new FunctionParameter("sStrategy", FunctionParameter.STRING);
with(fpArray[x++]){
setName("Long or Short");
addOption("Long");
addOption("Short");
setDefault("Long");
}
fpArray[x] = new FunctionParameter("cColor", FunctionParameter.COLOR);
with(fpArray[x++]){
setName("Line Color");
setDefault(Color.red);
}
}
var
var
var
var
bInit = false;
bVersion = null;
xATRTrailingStop = null;
xClose = null;
9/27/2009 8:11 AM
5 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
nATRTS = xATRTrailingStop.getValue(0);
nATRTS1 = xATRTrailingStop.getValue(-1);
if (nATRTS1 == null) return;
if (nClose1 < nATRTS1 && nClose > nATRTS1) {
if (bShowArrows) drawShape( Shape.UPARROW, BelowBar1, Color.green);
if (sStrategy == "Long") {
if (bShowL) drawTextRelative(0, BelowBar2, " LONG", Color.white,
Color.green, Text.PRESET|Text.CENTER|Text.FRAME, "Arial Black", 10,
"b"+(getCurrentBarCount()), -5);
Strategy.doLong("Long", Strategy.MARKET, Strategy.NEXTBAR);
} else {
if (bShowL) drawTextRelative(0, BelowBar2, " EXIT", Color.white,
Color.green, Text.PRESET|Text.CENTER|Text.FRAME, "Arial Black", 10,
"b"+(getCurrentBarCount()), -5);
if (Strategy.isShort()) Strategy.doCover("Exit Short",
Strategy.MARKET, Strategy.NEXTBAR);
}
}
if (nClose1 > nATRTS1 && nClose < nATRTS1) {
if (bShowArrows) drawShape( Shape.DOWNARROW, AboveBar1, Color.red);
if (sStrategy == "Long") {
if (bShowL) drawTextRelative(0, AboveBar2, " EXIT", Color.white,
Color.red, Text.PRESET|Text.CENTER|Text.FRAME, "Arial Black", 10,
"b"+(getCurrentBarCount()), -5);
if (Strategy.isLong()) Strategy.doSell("Exit Long", Strategy.MARKET,
Strategy.NEXTBAR);
} else {
if (bShowL) drawTextRelative(0, AboveBar2, "SHORT", Color.white,
Color.red, Text.PRESET|Text.CENTER|Text.FRAME , "Arial Black", 10,
"b"+(getCurrentBarCount()), -5);
Strategy.doShort("Short", Strategy.MARKET, Strategy.NEXTBAR);
}
}
if (bShowTS == false) return;
return xATRTrailingStop.getValue(0);
}
var xATR = null;
var nRef = 0;
var bSecondInit = false;
function ATRTrailingStop(nATRPeriod, nATRMultip, xSClose){
var nClose = 0;
var nClose1 = 0;
var nLoss = 0;
var nRes = 0;
var nRef = ref(-1);
if (bSecondInit == false) {
xATR = atr(nATRPeriod);
bSecondInit = true;
}
nClose = xSClose.getValue(0);
nClose1 = xSClose.getValue(-1);
nLoss = nATRMultip * xATR.getValue(0);
if (nLoss == null || nClose1 == null) return;
if (nClose > nRef && nClose1 > nRef) {
nRes = Math.max(nRef, nClose - nLoss);
} else {
if (nClose < nRef && nClose1 < nRef) {
nRes = Math.min(nRef, nClose + nLoss);
} else {
if (nClose > nRef) {
nRes = nClose - nLoss;
} else {
nRes = nClose + nLoss;
}
}
}
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=
http://www.esignal.com/download/default.asp",
Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.
RELATIVETOLEFT|Text.BOLD|Text.LEFT,
null, 13, "upgrade");
9/27/2009 8:11 AM
6 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
null, 13, "upgrade");
return b;
} else {
b = true;
}
return b;
}
Modified_ATR_TrailingStop.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:
Modified Average True Range Trailing Stops, by Sylvain Vervoort
Version:
1.0
04/09/2009
Formula Parameters:
ATR Period
ATR Multiplication
Long or Short
Show Line Trailing Stop
Show Labels
Show Arrows
Display Cursor Labels
Line Color
Default:
5
3.5
Long
True
True
True
True
Red
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("Modified ATR Trailing Stops");
setCursorLabelName("Modified ATR TS", 0);
setShowTitleParameters(false);
setDefaultBarFgColor(Color.red, 0);
setPlotType(PLOTTYPE_LINE, 0);
setDefaultBarThickness(2, 0);
askForInput();
var x=0;
fpArray[x] = new FunctionParameter("nATRPeriod", FunctionParameter.NUMBER);
with(fpArray[x++]){
setName("ATR Period");
setLowerLimit(1);
setUpperLimit(100);
setDefault(5);
}
fpArray[x] = new FunctionParameter("nATRMultip", FunctionParameter.NUMBER);
with(fpArray[x++]){
setName("ATR Multiplication");
setLowerLimit(1);
setUpperLimit(10);
setDefault(3.5);
}
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");
9/27/2009 8:11 AM
http://www.traders.com/Documentation/FEEDbk_Docs/2...
addOption("true");
addOption("false");
setDefault("true");
}
fpArray[x] = new FunctionParameter("ViewValue", FunctionParameter.BOOLEAN);
with(fpArray[x++]){
setName("Display Cursor Labels");
setDefault(true);
}
fpArray[x] = new FunctionParameter("sStrategy", FunctionParameter.STRING);
with(fpArray[x++]){
setName("Long or Short");
addOption("Long");
addOption("Short");
setDefault("Long");
}
fpArray[x] = new FunctionParameter("cColor", FunctionParameter.COLOR);
with(fpArray[x++]){
setName("Line Color");
setDefault(Color.red);
}
}
var
var
var
var
bInit = false;
bVersion = null;
xATRTrailingStop = null;
xClose = null;
7 of 29
9/27/2009 8:11 AM
8 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
return xATRTrailingStop.getValue(0);
}
var
var
var
var
xHigh_Low = null;
xATR_Modif = null;
nRef = 0;
bSecondInit = false;
nClose = xTClose.getValue(0);
nClose1 = xTClose.getValue(0);
nHigh = xHigh.getValue(0);
nHigh1 = xHigh.getValue(0);
nLow = xLow.getValue(0);
nLow1 = xLow.getValue(0);
nHigh_Low = xHigh_Low.getValue(0);
nMA_High_Low = xMA_High_Low.getValue(0) * 1.5;
if (nHigh_Low == null || nMA_High_Low == null) return;
if (nHigh_Low < nMA_High_Low) {
nHiLo = nHigh_Low;
} else {
nHiLo = nMA_High_Low;
}
9/27/2009 8:11 AM
9 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
ref(-1)) / nATRPeriod;
Modified/ATR.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:
Modified Average True Range, by Sylvain Vervoort
Version:
1.0
04/09/2009
Formula Parameters:
ATR Period
Line Color
Default:
5
Red
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(false);
setStudyTitle("Modified ATR");
setCursorLabelName("Modified ATR", 0);
setShowTitleParameters(false);
setDefaultBarFgColor(Color.red, 0);
setPlotType(PLOTTYPE_LINE, 0);
setDefaultBarThickness(2, 0);
askForInput();
var x=0;
fpArray[x] = new FunctionParameter("nATRPeriod", FunctionParameter.NUMBER);
with(fpArray[x++]){
setName("ATR Period");
setLowerLimit(1);
setUpperLimit(100);
setDefault(5);
}
fpArray[x] = new FunctionParameter("cColor", FunctionParameter.COLOR);
9/27/2009 8:11 AM
10 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
fpArray[x] = new FunctionParameter("cColor", FunctionParameter.COLOR);
with(fpArray[x++]){
setName("Line Color");
setDefault(Color.red);
}
}
var bInit = false;
var bVersion = null;
var xATR_Modif = null;
function main(nATRPeriod, cColor){
var nATR_Modif = 0;
if (bVersion == null) bVersion = verify();
if (bVersion == false) return;
if(bInit==false){
setDefaultBarFgColor(cColor, 0);
xATR_Modif = efsInternal("Calc_ATRMod", nATRPeriod);
bInit=true;
}
nATR_Modif = xATR_Modif.getValue(0);
if (nATR_Modif == null) return;
return nATR_Modif;
}
var
var
var
var
xHigh_Low = null;
xATR_ModifTmp = null;
nRef = 0;
bSecondInit = false;
bThirdInit = false;
xClose = null;
xHigh = null;
xLow = null;
nClose = xClose.getValue(0);
nClose1 = xClose.getValue(0);
nHigh = xHigh.getValue(0);
nHigh1 = xHigh.getValue(0);
nLow = xLow.getValue(0);
nLow1 = xLow.getValue(0);
nHigh_Low = xHigh_Low.getValue(0);
nMA_High_Low = xMA_High_Low.getValue(0) * 1.5;
if (nHigh_Low == null || nMA_High_Low == null) return;
9/27/2009 8:11 AM
11 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
ref(-1)) / nATRPeriod;
BACK TO LIST
9/27/2009 8:11 AM
http://www.traders.com/Documentation/FEEDbk_Docs/2...
WealthScript Code (C#):
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Text;
System.Drawing;
WealthLab;
WealthLab.Indicators;
namespace WealthLab.Strategies
{
/* Class that encapsulates the ATR Trailing Stop, closing basis */
public class ATRTrail
{
private WealthScript ws;
private Bars bars;
private double stopPrice;
private bool longPosition;
private DataSeries atrMod;
public ATRTrail(WealthScript wL, Bars b, bool positionLong, double
initialStop, int period, double factor )
{
ws = wL;
bars = b;
longPosition = positionLong;
stopPrice = initialStop;
atrMod = factor * TASCIndicators.ATRModified.Series(bars, period);
}
// Call this method to update and return the stop price on each bar
after entry
public double Price(int bar)
{
double prevPrice = stopPrice;
double newPrice;
if (longPosition)
{
newPrice = bars.Close[bar] - atrMod[bar];
stopPrice = newPrice > stopPrice ? newPrice : stopPrice;
}
else
{
newPrice = bars.Close[bar] + atrMod[bar];
stopPrice = newPrice < stopPrice ? newPrice : stopPrice;
}
ws.DrawLine(ws.PricePane, bar-1, prevPrice, bar, stopPrice, Color.Blue,
LineStyle.Solid, 1);
return stopPrice;
}
}
public class SAC_ATRTrailingStops : WealthScript
{
private StrategyParameter _isLong = null;
private StrategyParameter _initStop = null;
private StrategyParameter _period = null;
private StrategyParameter _atrMult = null;
private StrategyParameter _y = null;
private StrategyParameter _m = null;
private StrategyParameter _d = null;
public SAC_ATRTrailingStops()
{
_isLong = CreateParameter("Long = 1", 1, 0, 1, 1);
_initStop = CreateParameter("Initial Stop", 1.0, 0.25, 50.0, 0.25);
_period = CreateParameter("ATR Period", 5, 2, 100, 1);
_atrMult = CreateParameter("ATR Multiplier", 3.5, 1.0, 5.0, 0.1);
_m = CreateParameter("Month", 4, 1, 12, 1);
_d = CreateParameter("Day", 13, 1, 31, 1);
_y = CreateParameter("Year", 2009, 1990, 2012, 1);
}
/* Execute a strategy - trade on a specified date */
protected override void Execute()
{
DateTime dt;
try {
dt = new DateTime(_y.ValueInt, _m.ValueInt, _d.ValueInt);
}
catch {
DrawLabel(PricePane, "Invalid Date", Color.Red);
return;
}
int b = Bars.ConvertDateToBar(dt, false);
if (b < 1) {
12 of 29
9/27/2009 8:11 AM
13 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
_isLong.ValueInt == 1 )
BuyAtMarket(b, "Discretionary");
else
ShortAtMarket(b, "Discretionary");
Position p = LastPosition;
// After creating a position, initialize a stop object
ATRTrail atrStop = new ATRTrail(this, Bars, p.PositionType ==
PositionType.Long, _initStop.Value, _period.ValueInt, _atrMult.Value);
for(int bar = b + 1; bar < Bars.Count; bar++)
{
if (p.Active)
{
if (p.PositionType == PositionType.Long)
{
if( Close[bar] < atrStop.Price(bar) )
ExitAtMarket(bar + 1, p);
}
else if( Close[bar] > atrStop.Price(bar) )
ExitAtMarket(bar + 1, p);
}
}
}
}
}
Robert Sucher
www.wealth-lab.com
BACK TO LIST
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 = ParamList("Stop Mode", "Fixed|Chandelier|Modified ATR" );
StopLevel = Param("Fixed perc %", 14, 0.1, 50, 0.1)/100;
StopATRFactor = Param("ATR multiple", 4, 0.5, 10, 0.1 );
StopATRPeriod = Param("ATR period", 14, 3, 50 );
// calculate support and resistance levels
if( StopMode == "Fixed" ) // fixed percent trailing stop
{
sup = C * ( 1 - stoplevel );
9/27/2009 8:11 AM
14 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
sup = C * ( 1 - stoplevel );
res = C * ( 1 + stoplevel );
}
else // Chandelier ATR-based stop
if( StopMode == "Chandelier" )
{
sup = C - StopATRFactor * ATR( StopATRPeriod );
res = C + StopATRFactor * ATR( StopATRPeriod );
}
else
{
HL = H - L;
MAHL = 1.5 * MA( HL, StopATRPeriod );
HiLo = IIf( HL < MAHL, HL, MAHL );
H1 = Ref( H, -1 );
L1 = Ref( L, -1 );
C1 = Ref( C, -1 );
Href = IIf( L <= H1, H - C1, ( H - C1 ) - ( L - H1 ) / 2 );
Lref = IIf( H >= L1, C1 - L, ( C1 - L ) - ( L1 - H ) / 2 );
diff1 = Max( HiLo, HRef );
diff2 = Max( diff1, LRef );
ATRmod = Wilders( diff2, StopATRPeriod );
sup = C - StopATRFactor * ATRmod ;
res = C + StopATRFactor * ATRmod ;
}
// 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);
//SetBarFillColor( colorYellow );
Plot( trailARRAY,"trailing stop level", colorRed, styleLine );
Tomasz Janeczko, AmiBroker.com
www.amibroker.com
BACK TO LIST
9/27/2009 8:11 AM
http://www.traders.com/Documentation/FEEDbk_Docs/2...
HiLo
Min2(Subtract(High,Low), MovAvg(Subtract(High,Low),5))
Href
Subtract(Subtract(High, Lag(Close,1)), IfThenElse( A<=B(Low, Lag(High,1)),
0, Divide(Subtract(Low, Lag(High,1)), 2)))
Lref
Subtract(Subtract(Lag(Close,1), Low), IfThenElse ( A>=B(High, Lag(Low,1)),
0, Divide(Subtract(Lag(Low,1), High), 2)))
Modified Average True Range
ExpAvg( Max3( HiLo, Href, Lref ), 9)
To recreate the modified average true range trailing stop reversal system, enter the following formula in the appropriate locations
of the Trading Strategy Wizard:
Long protective stop:
Subtract( MaxValueSinceEntryFilled(TradingStrategy #2, High, 1),
Multiply2( 3.5, ModifiedAverageTrueRange))
Short protective stop:
Add2( MinValueSinceEntryFilled(TradingStrategy #2, Low, 1),
Multiply2( 3.5, ModifiedAverageTrueRange))
If you wish to create a modified average true range trailing stop system using your own trading systems entry rules, simply
combine the modified average true range trailing stops listed above with your own entry/exit conditions.
If you have NeuroShell Trader Professional, you can also choose whether the 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.
For more information on NeuroShell Trader, visit www.NeuroShell.com.
Marge Sherald, Ward Systems Group, Inc.
301 662-7950, sales@wardsystems.com
www.neuroshell.com
BACK TO LIST
10.
2.
2008.
1.
5.
3.5.
! ABBREVIATIONS:
C is [close].
C1 is valresult(C,1).
H is [high].
L is [low].
! AVERAGE TRUE RANGE
TR is Max(H - L,max(abs(C1 - L),abs(C1- H))).
ATR is expAvg(TR,atrLen).
15 of 29
9/27/2009 8:11 AM
16 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
10.
2.
2008.
1.
5.
3.5.
! ABBREVIATIONS:
C is [close].
C1 is valresult(C,1).
H is [high].
H1 is valresult(H,1).
L is [low].
L1 is lowresult(L,1).
! MODIFIED AVERAGE TRUE RANGE
AvgRng is simpleAvg(H - L, atrLen) .
HiLo is iff(H - L < 1.5 * AvgRng, H - L, 1.5*AvgRng).
HLmax is (H - C1) - (L - H1) / 2.
Href is iff(L <= H1,H - C1,HLmax).
LHmax is (C1 - L) - (L1 - H) / 2.
Lref is iff(H >= L1, C1 - L, LHmax).
Diff1 is Max(HiLo,Href).
Diff2 is Max(Diff1,Lref).
ATRM is expAvg(Diff2,atrLen*2-1,0).
! ATR TRAILING STOP FROM DATE
startDate is makeDate(mo,da,yr).
daysSinceStart is scanany(ruledate() = startDate, 5040)
then offSetToDate(month(),day(),year()).
loss is ATRM * atrMult.
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.
The code can be downloaded from the AIQ website at www.aiqsystems.com and also from
www.TradersEdgeSystems.com/traderstips.htm. It can also copied and pasted from the STOCKS & COMMODITIES website at
Traders.com.
Richard Denning
for AIQ Systems
richard.denning@earthlink.net
BACK TO LIST
9/27/2009 8:11 AM
17 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
month in my May 2009 Traders Tip, since the stop can adapt to the changing volatility of both the overall market as well as to
each individual stocks volatility and changes in volatility.
In my May 2009 Traders Tip, I modified Vervoorts fixed-percentage trailing stop system by adding market timing and also by
trading both the long and short sides. This system, if traded both long and short, would be always in, but since I added a markettiming filter based on a general-market trend-following filter, it will only trade long when the market trend is up or short when
the market trend is down.
The coded version of Vervoorts ATR trailing stop system that I am supplying here has the options of trading either long only,
short only, or both long and short. It also has the option to apply a market-trend filter using the S&P 500 index (SPX) to
determine whether to trade long or short. I decided to stick with the authors list of stocks for the tests.
One advantage in testing stocks with TradersStudio over other programs is that both the 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 they are
based on the number of shares traded. (Other programs compute commissions on a cents-per-share basis, and 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.) In addition, with TradersStudio, 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 dont know whether a
stock is low-priced due to a split or was really trading at a low price in real time. TradersStudio also has the ability to compute
the dividends that you would have been received or paid (if short).
FIGURE 6: TITLE.blurb
In Figure 6, I show a comparison of the equity curves: the left one represents trading both long and short using a trend filter on
the SPX with optimized parameters using the fixed-percentage trailing stop system from the May 2009 issue, while the one on the
right shows this issues modified ATR trailing stop (ATRM) system with optimized parameters. Just by looking at the two equity
curves, its hard to tell which is preferable, although the ATRM (right curve) appears smoother with smaller drawdowns.
Looking at the table in Figure 7, which shows some key metrics for the two trailing-stop methods, we see that the ATRM stops
are preferable, since we obtain slightly more net profit with lower drawdown, better profit factor, and better profit-to-maximum
drawdown ratios with fewer trades. I also found that there is a slight improvement (not shown) by using the ATRM system
versus the ATR system.
FIGURE 7: TITLE.blurb
To measure the robustness of the parameter sets from the ATRM system optimization, in Figure 8 I show two three-dimensional
models. 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 ATR-length parameter is less sensitive to changes than the ATR multiple. The range
of good parameters is five to 10 days for the ATR length, and 4.5 to 5.5 for the ATR multiple. All tests used 300 days for the
moving average length on the SPX trend filter. I used a TradersStudio add-in to produce the three-dimensional models.
FIGURE 8: TITLE.blurb
The code can be downloaded from the TradersStudio website at www.TradersStudio.com ->Traders Resources->FreeCode as
well as from www.TradersEdgeSystems.com/traderstips.htm. It can also be copied and pasted from the STOCKS &
COMMODITIES website at www.Traders.com.
'
'
'
'
Sub ATR_TSSR(tsStartDate,WilderLenATR,multATR,longOnly,useMktTm,spxLen,useModATR)
'tsStartDate = date that trading is to start after bars back has been satisfied
'
use TradeStation date format of YYYMMDD example 1/20/2003 = 1030120
'WilderLenATR = 5, multATR = 3.5, unitSiz = 1, longOnly = 2 (both long and short)
9/27/2009 8:11 AM
18 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
'WilderLenATR = 5, multATR = 3.5, 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
' spxLen = 250
' useModATR = 1 uses modified ATR; any other value uses standard ATR
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)
If useModATR = 1 Then
trail = ATRM_TRAIL_STOP(WilderLenATR, multATR)
Else
trail = ATR_TRAIL_STOP(WilderLenATR, multATR)
End If
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
'_____________________________________________
Function ATR_Wilder(WilderLen)
' computes average true range using Wells Wilder averaging method
ATR_Wilder = XAverage(TrueRange,WilderLen*2-1,0)
End Function
'_____________________________________________
Function ATR_TRAIL_STOP(WilderLen,multATR)
' suggested default parameters: WilderLen = 5, multATR = 3.5
Dim loss
Dim longStop
Dim shortStop
Dim maxVal
Dim minVal
Dim ATRval As BarArray
Dim trail As BarArray
loss = ATR_Wilder(WilderLen)*multATR
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
9/27/2009 8:11 AM
19 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
End If
End If
ATR_TRAIL_STOP = trail
End Function
'_____________________________________________
Function ATRM_Wilder(WilderLen)
' computes average true range as modified using Wells Wilder averaging method
Dim AvgRng As BarArray
Dim HiLo As BarArray
Dim Href As BarArray
Dim Lref As BarArray
Dim HLmax As BarArray
Dim LHmax As BarArray
Dim Diff1 As BarArray
Dim Diff2 As BarArray
AvgRng = Average(H - L, WilderLen)
HiLo = IIF(H - L < 1.5 * AvgRng, H - L, 1.5*AvgRng)
HLmax = (H - C[1]) - (L - H[1]) / 2
Href = IIF(L <= H[1],H - C[1],HLmax)
LHmax = (C[1] - L) - (L[1] - H) / 2
Lref = IIF(H >= L[1], C[1] - L, LHmax)
Diff1 = Max(HiLo,Href)
Diff2 = Max(Diff1,Lref)
ATRM_Wilder = XAverage(Diff2,WilderLen*2-1,0)
End Function
'_____________________________________________
Function ATRM_TRAIL_STOP(WilderLen,multATR)
' coputes the modified ATR trailing stop
' suggested default parameters: WilderLen = 5, multATR = 3.5
Dim loss
Dim longStop
Dim shortStop
Dim maxVal
Dim minVal
Dim ATRval As BarArray
Dim trail As BarArray
loss = ATRM_Wilder(WilderLen)*multATR
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
ATRM_TRAIL_STOP = trail
End Function
'_____________________________________________
'ATR Trailing Stop Indicator
sub ATR_TRAIL_STOP_IND(WilderLen,multATR)
plot1(ATR_TRAIL_STOP(WilderLen,multATR))
End Sub
'_____________________________________________
'ATR Modified Trailing Stop Indicator
Sub ATRM_TRAIL_STOP_IND(WilderLen,multATR)
plot1(ATRM_TRAIL_STOP(WilderLen,multATR))
End Sub
'_____________________________________________
Richard Denning
for TradersStudio
richard.denning@earthlink.net
BACK TO LIST
9/27/2009 8:11 AM
20 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
In the current series of articles by Sylvain Vervoort on stop methods, including the one in this issue, Average True Range
Trailing Stops, Vervoort has provided some helpful methods for implementing trailing stops. Based on our tests, the strategy
presented in this months article provides some performance increases over the methods discussed in his article last month
(Using Initial And Trailing Stops).
In our tests, both the fixed-percentage trailing stop method and the modified ATR trailing stop method were run against the
NASDAQ 100 components from 2004 to 2007 using a spread of 0.04 and commissions of $10.00 on either side. A range of
variables was also added to test the percentage, period, and factor values. Surprisingly, every parameter set for both of the
trailing stop approaches created profitable results. However, the modified ATR trailing stop clearly had the better performance,
with higher returns and shorter holding periods.
One issue, noted last month in this column as well, is that the percentage profitability never rose above 50% for either approach.
Likewise, both approaches performed poorly when tested exclusively in 2008. Thus, these trailing stops may benefit greatly from
the use of supporting indicators. The automated search in StrataSearch can help users find supporting indicators that improve
either of these trailing-stop approaches.
As with all other StrataSearch Traders Tips, additional information, including plugins, can be found in the Shared Area of the
StrataSearch user forum.
//****************************************************
// ATR Modified
//****************************************************
period = parameter("Period");
HiLo=If(H-L<1.5*Mov(H-L,period,S),H-L,
1.5*Mov(H-L,period,S));
Href=If(L<=Ref(H,-1),H-Ref(C,-1),
(H-Ref(C,-1))-(L-Ref(H,-1))/2);
Lref=If(H>=Ref(L,-1),Ref(C,-1)-L,
(Ref(C,-1)-L)-(Ref(L,-1)-H)/2);
diff1=higher(HiLo,Href);
diff2=lower(diff1,Lref);
ATRMOD = wsm(diff2,period);
Pete Rast
Avarin Systems Inc.
www.StrataSearch.com
BACK TO LIST
9/27/2009 8:11 AM
21 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
Craig Shipman
Worden Brothers, Inc
www.Worden.com, www.StockFinder.com
BACK TO LIST
LISTING 1
$period := choose(param1 < 1, 1, param1 > 100, 100, param1);
$atrfact := choose(param2 < 1, 1, param2 > 10, 10, param2);
MidPrice := H-L;
$HiLo := if(MidPrice < 1.5*average(MidPrice, $period),
MidPrice, 1.5*average(MidPrice, $period));
$Href := if (L <= H(1), H-C(1), ((H-C(1))-(L(1)-H))/2);
$Lref := if (H >= L(1), C(1)-L, ((C(1)-L)-(L(1)-H))/2);
diff1 := maxlist($HiLo, $Href);
diff2 := maxlist(diff1, $Lref);
$atrmod := 1/$period*diff2 + ($period-1)/$period*qc_xaverage(1,diff2,$period);
$loss := $atrfact*$atrmod;
plot1 := $atrmod;
plot2 := choose(C>plot2(1) and C(1)>plot2(1), maxlist(plot2(1),C-$loss),
Cplot2(1), C-$loss, C+$loss);
success2 := date(0) > param3;
A downloadable version of the indicator will be available at the NeoTicker blog site (http://blog.neoticker.com).
Kenneth Yuen, TickQuest Inc.
www.tickquest.com
BACK TO LIST
9/27/2009 8:11 AM
22 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
Href:=0;
Lref:=0;
diff1:=0;
diff2:=0;
atrmod:=0;
loss:=0;
result:=0;
end_var
HiLo:=iff(H - L < 1.5 * Mov(H - L, period, S), H - L, 1.5 * Mov(H - L,
period, S));
Href:=iff(L <= Ref(H, -1), H - Ref(C, -1), (h - ref(C, -1)) - (L Ref(H, -1)) / 2);
Lref:=iff(H >= Ref(L, -1), Ref(C, -1) - L, (Ref(C, -1) - L) - (Ref(L, -1)
- H) / 2);
diff1:=Max(HiLo, Href);
diff2:=Max(diff1, Lref);
atrmod:=EMA(diff2,period);
loss:=atrfact*atrmod;
if HISTORYSIZE <= period then result := C;
else
begin
if C > this\1\ AND C\1\ > this\1\ then result := Max(this\1\,C-loss);
else
begin
if C < this\1\ then result := Min(this\1\,C+loss);
else
begin
if C > this\1\ then result := C-loss;
else result := C+loss;
end;
end;
end;
return result;
Then you specify the strategy rules in Tradecision's Strategy Builder:
Entry Long:
if Date() = 080102 then return true;
return false;
Exit Long:
return CrossBelow(Stop_Trail_ATR_Mod(5,3.5),C);
Entry Short:
if Date() = 081201 then return true;
return false;
Exit Short:
return CrossAbove(Stop_Trail_ATR_Mod(5,3.5),C);
As mentioned in Vervoorts article, youll need to enter the starting date manually. To define Date(), use a numeric value in the
Yymmdd format. Date returns 080102 if the day is January 2, 2008. See Figure 12.
To import the strategy into Tradecision, visit the area Traders Tips from TASC magazine at http://tradecision.com/support
/tasc_tips/tasc_traders_tips.htm or copy the code from the STOCKS & COMMODITIES website at www.Traders.com.
Yana Timofeeva
Alyuda Research, Inc.
510 931-7808, sales@tradecision.com
www.tradecision.com
BACK TO LIST
9/27/2009 8:11 AM
23 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
NinjaScript and select the downloaded file. This indicator is for NinjaTrader version 6.5 or greater.
You can review the indicators source code by selecting the menu Tools > Edit NinjaScript > Indicator from within the
NinjaTrader Control Center window and selecting ATRTrailingStop. A sample chart is shown in Figure 13.
NinjaScript indicators are compiled DLLs that run native, not interpreted, which provides you with the highest possible
performance.
BACK TO LIST
We are offering four scripts that implement Vervoorts approach in Wave59. As always, users of Wave59 can download these
scripts directly using the QScript Library, found at http://www.wave59.com/library.
Indicator 1: ATR reversal system
#This script plots Sylvain Vervoort's ATR Stop Value
#as described in the June 2009 issue of Stocks&Commodities
#Period: period to get ATR value, using wilder's average function
#Multiplier: factor to multiply the ATR value by to calculate stop amount
#Act_as_System: if true, use as trading system, otherwise just lines
input:period(5),multiplier(3.5),act_as_system(false),color(red),thickness(1);
#initialize variables
if (barnum==barsback) {
stopval=close;
buysell=1;
}
#calculate atr values
atr=wilder_average(truerange(),period);
bigatr=atr*multiplier;
#calculate long stops
if (buysell>0) {
9/27/2009 8:11 AM
24 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
if (buysell>0) {
stopval=close-bigatr;
stopval=max(stopval,stopval[1]);
if (close<stopval) {
buysell=-1;
stopval=close+bigatr;
if (act_as_system==true) exitlong(0,close,"market","onebar");
}
}
#calculate stort stops
else if (buysell<0) {
stopval=close+bigatr;
stopval=min(stopval,stopval[1]);
if (close>stopval) {
buysell=1;
stopval=close-bigatr;
if (act_as_system==true) buy(1,close,"market","onebar");
}
}
#plot the lines
plot1=stopval;
color1=color;
thickness1=thickness;
9/27/2009 8:11 AM
25 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
text_setstring(txref,to_string(stopval));
}
Indicator 3: This script uses Vervoort's Modified ATR calculation
#This script plots Sylvain Vervoort's Modified ATR Stop Value
#as described in the June 2009 issue of Stocks&Commodities
#Period: period to get modified ATR value
#Multiplier: factor to multiply the ATR value by to calculate stop amount
#Act_as_System: if true, use as trading system, otherwise just lines
input:period(5),multiplier(3.5),act_as_system(false),color(red),thickness(1);
#initialize variables
if (barnum==barsback) {
stopval=close;
buysell=1;
}
#calculate Vervoort's modified atr values
simplehilo=average(high-low,period);
if (high-low<1.5*simplehilo)
hilo=high-low;
else
hilo=simplehilo;
href=abs(high-close[1]);
if (low>high[1]) href-=(low-close[1])/2;
lref=abs(low-close[1]);
if (high<low[1]) lref-=(close[1]-high)/2;
modatr=max(lref,href,hilo);
bigatr=wilder_average(modatr,period);
bigatr*=multiplier;
#calculate long stops
if (buysell>0) {
stopval=close-bigatr;
stopval=max(stopval,stopval[1]);
if (close<stopval) {
buysell=-1;
stopval=close+bigatr;
if (act_as_system==true) exitlong(0,close,"market","onebar");
}
}
#calculate stort stops
else if (buysell<0) {
stopval=close+bigatr;
stopval=min(stopval,stopval[1]);
if (close>stopval) {
buysell=1;
stopval=close-bigatr;
if (act_as_system==true) buy(1,close,"market","onebar");
}
}
#plot the lines
plot1=stopval;
color1=color;
thickness1=thickness;
Indicator 4: This script uses Vervoort's Modified ATR calculation to
manage a specific trade
#This script plots Sylvain Vervoort's ATR Stop Value
#as described in the June 2009 issue of Stocks&Commodities.
#Use this version to manage an actual trade based on a specific date.
#Period: period to get ATR value, using wilder's average function
#Multiplier: factor to multiply the ATR value by to calculate stop amount
#Startyear, Startmonth, Startday: Day to Begin plotting on
input:startyear(2009),startmonth(1),startday(1),longposition(true),
period(5),multiplier(3.5),color(red),thickness(1);
#initialize variables
if (barnum==barsback) {
startbar=date_to_bar(startyear,startmonth,startday,time);
stopval=close;
buysell=1;
if (longposition==false) buysell=-1;
txref=text(barnumber, close, "", color, tx_left, 8);
}
#calculate Vervoort's modified atr values
simplehilo=average(high-low,period);
if (high-low<1.5*simplehilo)
hilo=high-low;
else
hilo=simplehilo;
href=abs(high-close[1]);
9/27/2009 8:11 AM
http://www.traders.com/Documentation/FEEDbk_Docs/2...
href=abs(high-close[1]);
if (low>high[1]) href-=(low-close[1])/2;
lref=abs(low-close[1]);
if (high<low[1]) lref-=(close[1]-high)/2;
modatr=max(lref,href,hilo);
bigatr=wilder_average(modatr,period);
bigatr*=multiplier;
if (barnum<startbar)
{
if (buysell>0) stopval=close-bigatr;
else stopval=close+bigatr;
}
else
{
#calculate long stops
if (buysell>0) {
stopval=close-bigatr;
stopval=max(stopval,stopval[1]);
if (close<stopval) {
buysell=-1;
stopval=close+bigatr;
}
}
#calculate stort stops
else if (buysell<0) {
stopval=close+bigatr;
stopval=min(stopval,stopval[1]);
if (close>stopval) {
buysell=1;
stopval=close-bigatr;
}
}
#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));
}
-------------------------------------------Earik Beann
Wave59 Technologies Intl, Inc.
www.wave59.com
BACK TO LIST
26 of 29
9/27/2009 8:11 AM
27 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
Systems, LLC}
{Copyright: 2009}
{Description: TASC, June 2009 - "Average True Range Trailing Stops"
by Sylvian Vervoort}
{File: tasc_TSRLATR.vtsrc - Version 1.0}
Loss:= ATR(atrperiods)*atrmult;
TSL:= if(BarCount()>=atrperiods,
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 ATR trailing stoploss reversal level indicator.
To attach the indicator to a chart (Figure 15), click the right mouse button within the chart window and then select Add
Indicator -> TASC - 06/2009 - Trailing Stoploss Reversal Level (ATR) from the indicator list.
To learn more about VT Trader, visit www.cmsfx.com.
Forex trading involves a substantial risk of loss and may not be suitable for all investors.
Chris Skidmore
Visual Trading Systems, LLC (courtesy of CMS Forex)
(866) 51-CMSFX, trading@cmsfx.com
www.cmsfx.com
BACK TO LIST
THE WIGGLE
At Trade-Ideas we use a custom, dynamic stop that takes into account a stocks 15-minute average volatility multiplied by the
relative volume (an indexed ratio of what the current volume is over its 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. NFLXs 15-minute average volatility is $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 will be correct about the trade but get stopped out, only to watch the stock do exactly what you thought it
would, which we all know is painful. The wiggle creates a customized stop that takes into account the characteristics of each
stock.
The wiggle is used in the strategy, Modified ATR Volatility Stop 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: Modified ATR Volatility Stop
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.
9/27/2009 8:11 AM
28 of 29
http://www.traders.com/Documentation/FEEDbk_Docs/2...
Type or copy/paste this 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):
http://bit.ly/1WrpZ (case sensitive)
This strategy also appears on the Trade-Ideas blog, http://marketmovers.blogspot.com/, or you can build the strategy from
Figure 16, which shows the configuration of this strategy, where one alert and nine filters are used with the following settings:
Running Up Now (in 1 minute or less), $0.75
Min Price Filter = 5 ($)
Max Price Filter = 50 ($)
The definitions of these indicators appear here: http://www.trade-ideas.com/Help.html.
Thats the strategy, but what about the trading rules? How should the opportunities that the strategy finds be traded? For the
stop-loss, we used one of the more advanced options available in the OddsMaker. Instead of using a traditional stop-loss, we
selected Another alert as the exit condition called Trailing stop, volatility down. This alert is triggered when a stock moves
down an amount equal to the average 15-minute volatility multiplied by the number of 15-minute bars we decide on in this
case, 2. For example, if the average 15-minute volatility is 10 cents, this alert would not trigger until a stock moves down at least
20 cents.
Here is what The OddsMaker tested for the past three weeks ended 4/9/2009 given the following trade rules:
On each alert, sell short the symbol (price moves down to be a successful trade)
Schedule an exit for the stocks 30 minutes after entry
Start trading from the open and stop trading 30 minutes later
Set a stop using the alert, trailing stop, volatility down, with a setting of two bars
The OddsMaker summary provides evidence of how well this strategy and our trading rules did. The settings are shown in
Figure 17.
The results (last backtested for the three-week period ended 4/9/2009) are shown in Figure 18. The summary reads as follows:
This strategy generated 498 trades of which 339 were profitable for a win rate of 68.07%. The average winning trade generated
$0.38 in profit and the average loser lost $0.18. The net winnings of using this strategy for 15 trading days generated $105.06
points. If you normally trade in 100-share lots, this strategy would have generated $10,506. The z-score or confidence factor that
the next set of results will fall within this strategys average winner and loser is 100%.
You can find an explanation of The OddsMaker backtest results in more detail from the online user manual at
http://www.trade-ideas.com/OddsMaker/Help.html.
9/27/2009 8:11 AM
http://www.traders.com/Documentation/FEEDbk_Docs/2...
http://www.trade-ideas.com/OddsMaker/Help.html.
Dan Mirkin & David Aferiat
Trade Ideas, LLC
david@trade-ideas.com, www.trade-ideas.com
BACK TO LIST
29 of 29
9/27/2009 8:11 AM