Download as pdf or txt
Download as pdf or txt
You are on page 1of 555

Code Snippets

&

How To’s

David Jennings
The Performance Factory

1
2
AIQ CODE..............................................................................................................................................9
CANDLESTICKS ....................................................................................................................................9
CANDLESTICK COLOUR STUDY ............................................................................................................9
RATE OF CHANGE .................................................................................................................................9
MONEY MANAGEMENT EXITS ............................................................................................................10
MACDI EXIT RULES ...........................................................................................................................10
CONDITIONAL RULES-SELLING PRESSURE ...................................................................................11
MOMENTUM .......................................................................................................................................12
VIDYA - TUSHAR CHANDE ...............................................................................................................13
SECTOR MOVEMENT...........................................................................................................................13
PRICE/VOLUME CRITERIA?.................................................................................................................17
HIGH JUMP CANDIDATE SELECTION ...................................................................................................17
VOLUME SPIKE ...................................................................................................................................18
VARIABLE PROFIT PROTECT STOP, LOSS STOP AND TIME STOP .........................................................19
BUY FOR STOCKS IN A SECTOR ...........................................................................................................20
BOLLINGER BANDS ............................................................................................................................20
LINEAR REGRESSION CALCULATION USING THE LEAST MEANS SQUARED METHOD ...........................21
LINEAR REGRESSION METHOD BASED INDICATORS ............................................................................21
SECTOR DIVERGENCE .........................................................................................................................22
COUNTOF............................................................................................................................................23
ATR AND WILDER’S RSI ...................................................................................................................23
RELATIVE STRENGTH .........................................................................................................................24
RECURSION.........................................................................................................................................25
METASTOCK CODE..........................................................................................................................28
PRIMARY BUY SIGNAL .......................................................................................................................28
PRIMARY SELL SIGNAL ......................................................................................................................28
MARKETSPACE STOCK SYSTEM .........................................................................................................28
Primary Buy Signal.......................................................................................................................28
Primary Sell Signal .......................................................................................................................29
SMOOTH STOCKS ................................................................................................................................29
Bressert Cycle Indicators..............................................................................................................30
EXPLANATION OF THE MCCLELLAN OSCILLATOR ..............................................................................31
THRUST OSCILATOR: ..........................................................................................................................31
MIDAS VOLUME WEIGHTED AVE PRICE-SUPPORT/RESIST ...............................................................32
STOCHASTIC CROSS TRADING SYSTEM .................................................................................33
TSI AND ERGODICS INDICATORS..............................................................................................33
Trading Ergodics with the Trend – Rules .....................................................................................34
RELATIVE STRENGTH OF STOCK TO INDEX ..........................................................................34
FIND RSI ABOVE 80 .......................................................................................................................36
KASE DEV STOP .................................................................................................................................36
WOLF WAVE PATTERNS..............................................................................................................36
THE MARKET FACILITATION INDEX ...................................................................................................37
TRUE STRENGTH INDEX..............................................................................................................38
GANN SWING HILOW ACTIVATOR......................................................................................................41
RUGGERIO'S TREND ............................................................................................................................42
AUTOMATIC METASTOCK TRENDLINE FORMULA ...............................................................................42
THE RECURSIVE MOVING TREND AVERAGE.......................................................................................44
THREE INSIDE DAYS ....................................................................................................................49
NR4 FORMULA...................................................................................................................................50
MOVAVG ASYMMETRIC VOLATILITY PRICE BANDS ..........................................................................58
REGRESSION ASYMMETRIC VOLATILE PRICE BAND ...........................................................................58
WRO AND WSO INDICATORS ..........................................................................................................152
BODY MOMENTUM.....................................................................................................................158
ST OSCILLATOR...........................................................................................................................159
LOOKBACK ......................................................................................................................................160
JACK LANDIS' WEIGHTED STOCHASTIC (SHORTENED TO LANDIS).....................................................163

3
CHANDE & KROLL'S R2 INDICATOR .................................................................................................165
PRICE ACTION INDICATOR (PAIN) ...................................................................................................165
WEEKLY PIVOT POINT ......................................................................................................................167
HIGHEST HIGH SINCE BUY SIGNAL........................................................................................168
FORECAST OSCILLATOR SYSTEM ALTERNATIVE..............................................................168
FORECAST OSCILLATOR SYSTEM ..........................................................................................168
Chaos Blue BL ............................................................................................................................171
Chaos Red BL .............................................................................................................................171
Chaos Green BL..........................................................................................................................171
Chaos Gator................................................................................................................................171
CHAOS AO .......................................................................................................................................172
Chaos AO Signal Line.................................................................................................................172
Chaos AC ....................................................................................................................................172
Chaos Fractal .............................................................................................................................172
TRADING THE TREND 2 .............................................................................................................184
TRADING THE TREND 1 .............................................................................................................186
BOLLINGER BAND WIDTH ........................................................................................................187
BOLLINGER BAND HISTOGRAM KARNISH ...........................................................................187
BB HISTOGRAM ...............................................................................................................................191
CHANDELIER EXIT, VERSION 2 METASTOCK CODE ..............................................................196
MOVING AVERAGE CROSSOVERS ..........................................................................................197
VIDYA WITH P VARIABLE VERSION 2 ...................................................................................200
VIDYA EXPLANATION ...............................................................................................................201
IMPROVED CHANDELIER EXIT ................................................................................................217
BOOMERS TRADING SIGNALS ............................................................................................................224
Boomers buysig...........................................................................................................................224
ADX AND TRENDLINES .............................................................................................................227
ADX RISING EXPOLORATION...................................................................................................243
SWING TRADING EXPERT .........................................................................................................243
DMI EXPLORATION VERSION 3.........................................................................................................245
VOLATILITY BREAKOUT ...................................................................................................................249
VOLATILITY EXPLORATION ..............................................................................................................253
RELATIVE VOLATILITY INDEX ..........................................................................................................254
SMOOTHED ADAPATIVE STOCHASTIC OSCILLATOR ..........................................................................254
SIDEWAYS CHANNELS EXPLORATION ..............................................................................................260
STOCHASTIC AND RSI SYSTEM ...............................................................................................261
DAHL OSCILLATOR...........................................................................................................................263
2 DAY HAMMER EXPLORATION .......................................................................................................264
WRO AND WSO INDICATORS ..........................................................................................................265
WRO INDICATOR: ............................................................................................................................267
GAP1 SYSTEM ..................................................................................................................................268
GAP2 SYSTEM ..................................................................................................................................268
RSI DIVERGENCE EXPLORATION............................................................................................269
STIX INDICATOR .........................................................................................................................270
DENVELOPE (RSI) ............................................................................................................................270
CYLICAL SYSTEM .......................................................................................................................271
JKCYCL .............................................................................................................................................272
ST OSCILLATOR...........................................................................................................................273
CCI SPIKE TRADING SYSTEM ...........................................................................................................273
LOOKBACK ......................................................................................................................................274
MCCLELLAN OSCILLATOR ...............................................................................................................276
MCCLELLAN SUMMATION INDEX .....................................................................................................276
BARNES' ACCELERATION .................................................................................................................278
BARNES' ADAPTIVE FORECAST ........................................................................................................278
BARNES' MOVING AVERAGE ............................................................................................................278
NATENBERG'S VOLATILITY ..............................................................................................................279
TEMA STOCHRSI FORMULA .............................................................................................................280
DEVSTOP .......................................................................................................................................280
WEEKLY PIVOT POINT ......................................................................................................................281
STO RSI ..........................................................................................................................................282

4
ATR MODIFIED.............................................................................................................................283
HIGHEST HIGH SINCE BUY SIGNAL........................................................................................283
MINER’S STORSI..............................................................................................................................284
FORECAST OSCILLATOR SYSTEM ALTERNATIVE..............................................................287
MURREY MATH ................................................................................................................................287
ZIGZAG CODE ..............................................................................................................................289
TRADE EQUITY AND TRADE STOP FORMULA UPDATE .......................................................................292
SO MUCH FOR QUICK FIXES. MY THANKS TO DAVID HOBBS FOR
LETTING ME KNOW THAT MY 'ND' VARIABLE FIX WAS ALSO FLAWED.
I'LL TRY AGAIN. IF YOU HAVE VERSION 3.X TRADE EQUITY OR TRADE
STOP FORMULAS WITH AN 'ND' THAT LOOKS LIKE EITHER OF THE LINES
BELOW, ND:=LASTVALUE(INT(FRAC(CP/100)*10)); OR
ND:=LASTVALUE(INT(FRAC(CP/99)*10)); THEN IT SHOULD BE CHANGED
TO ND:=LASTVALUE(INT(0.1+FRAC(CP/100)*10)); HOPEFULLY THIS WILL
FIX THE PROBLEM ONCE-AND-FOR-ALL. ...................................................................297
LATCHES ..........................................................................................................................................297
TRADESTATION CODE..................................................................................................................302
SLOWKCLASSIC ...............................................................................................................................302
MACD HISTOGRAM .........................................................................................................................302
HIGH OF TODAY ................................................................................................................................303
MACD CROSSOVER CHART .............................................................................................................304
COLES’S RANGE ...............................................................................................................................304
INDICATOR COLE'S RANGE DAILY ....................................................................................................305
8 PERIOD DONCHIAN CHANNEL MID-POINT LINE .............................................................................305
INDICATOR SUPP-RESIS DAILY ........................................................................................................305
ANDREW’S PITCHFORK.....................................................................................................................307
E-MINI WITH MONTE CARLO ...........................................................................................................311
HURST EXPONENT ............................................................................................................................313
ERGOTIC CSI....................................................................................................................................314
ERGOTIC MACD ..............................................................................................................................315
ENTRY & EXIT .................................................................................................................................316
STOPS IN EDS ................................................................................................................................317
TRIGGERS BASED ON ENTRY PRICES..................................................................................................318
COUNT OF ........................................................................................................................................318
COMPARE TWO INDICES ...................................................................................................................318
COLOUR STUDIES .............................................................................................................................319
RECURSION.......................................................................................................................................320
DIFFERENT RESULTS IN TRADESTATION ..........................................................................................325
SIGNAL REVIEW – UPSIDE ................................................................................................................326
3 BAND RESEARCH SYSTEM .............................................................................................................326
MARKET PROFILE .............................................................................................................................327
T BOND SYSTEM ..............................................................................................................................334
HIGHER HIGHS...................................................................................................................................334
INDICATOR MARKS ..........................................................................................................................335
YESTERDAY’S HIGH LOW ON AN INTRADAY CHART ........................................................................336
TO COUNT THE NUMBER OF NEW HIGHS IN THE LAST N BARS ............................................................336
COMMENTARY FUNCTION ................................................................................................................337
NO PLOT() STATEMENT ....................................................................................................................338
NUMERICAL ACCURACY...................................................................................................................340
TRADESTATION: RELATIVE VIGOR INDEX ..........................................................................340
STOPS ...............................................................................................................................................341
ADAPTIVE STOP ................................................................................................................................341
LINE THICKNESS WON’T RESPOND ..................................................................................................342
TEXT STUDIES ..................................................................................................................................342
@Text Current C <= ..................................................................................................................344

5
@TextCurrentCText....................................................................................................................344
@TextCurrentIndic .....................................................................................................................345
TRADESTATION INSTABILITY ...........................................................................................................346
OTHER HOW TO’S ..........................................................................................................................347
TS4 INSTALLATION ON WIN 2K ........................................................................................................349
ATR DISCUSSION .............................................................................................................................355
CODING VELOCITY AND ACCELERATION ...........................................................................................356

WEALTHSCRIPT CODE.................................................................................................................357
DEAD CAT CATCHER ........................................................................................................................357
INTRADAY ........................................................................................................................................358
WEALTHSCRIPT CODE ......................................................................................................................358
WEALTHSCRIPT CODE.................................................................................................................360
TURTLE SOUP WITH FILTER ..............................................................................................................360
WEALTHSCRIPT CODE ......................................................................................................................361
MULTI COLOUR MA ETC..................................................................................................................363
DIVERGENCE BETWEEN PRICE AND RSI OR MACD HISTO...? ...........................................................364
CHECK PEAK & CHECK VALLEY ......................................................................................................368
MOVING AVERAGES .........................................................................................................................371
FIBONACCI FORMULAS .....................................................................................................................373
JOE DINAPOLI - DINAPOLI TREND FORMULA ...................................................................................376
FORECAST OSCILLATOR ...................................................................................................................390
CHANDE'S DYNAMIC MOMENTUM INDEX .........................................................................................392
ADAPTIVE SYSTEMS .........................................................................................................................394
ON BALANCE VOLUME .....................................................................................................................399
BOOK LIST........................................................................................................................................401
GANN ...............................................................................................................................................401
LIST OF BOOKS AND COURSES:..........................................................................................................401
RWI .................................................................................................................................................405
KNEWPEAKINDICATOR ...............................................................................................................406

KPEAK OSCILLATOR ....................................................................................................................406

OKS & PEAKOSCILLATOR...........................................................................................................407

KCD INDICATOR.............................................................................................................................407

KPERM FN.........................................................................................................................................408

1ST CLASS SHORTS ........................................................................................................................408

1ST CLASS LONGS ............................................................................................................................409

KCDL PIERCING .............................................................................................................................410


{BULLISH PIERCING} .......................................................................................................................410
{BEARISH PIERCING} .......................................................................................................................411
KSDANGERLONG & SHORT ........................................................................................................411

KS2 LONGS & WARNING ..............................................................................................................411

KS2 SHORTS & WARNING ............................................................................................................412

PERMISSION STOCHASTIC..........................................................................................................414

XPERMD ............................................................................................................................................414

6
XPERM K ...........................................................................................................................................414

XPERM LONG...................................................................................................................................414

XPERM SHORT ................................................................................................................................415

XD ........................................................................................................................................................415

XKCD ..................................................................................................................................................416

KPERMISSIONFN ............................................................................................................................416

KDEVSTOPS......................................................................................................................................416

XDEV...................................................................................................................................................417

XREV...................................................................................................................................................417

LARRY WILLIAMS EXPERT ........................................................................................................418

DEMARK EXPERT...........................................................................................................................420
ZIG ZAG TREND INDICATOR .............................................................................................................423
Expressing Exponential averages in days...................................................................................428
FIBONACCI FORMULAS .....................................................................................................................442
JOE DINAPOLI - DINAPOLI TREND FORMULA ...................................................................................444
FORECAST OSCILLATOR ...................................................................................................................457
CHANDE'S DYNAMIC MOMENTUM INDEX .........................................................................................460
ADAPTIVE SYSTEMS .........................................................................................................................461
ON BALANCE VOLUME .....................................................................................................................466
MARKET COMMENTARY ...................................................................................................................467
ACTIVE TRADER MAGAZINE CODE ..................................................................................................468
ROSS CONGESTION PAINTBAR. .........................................................................................................489
NARROW RANGE 4 (NR4) DAYS ......................................................................................................490
NARROW RANGE 7 (NR7) DAYS ......................................................................................................491
HISTORICAL VOLATILITY .................................................................................................................492
BOLLINGER BANDS ..........................................................................................................................493
OUTSIDE DAY, NR4 AND MOVING AVERAGE ..................................................................................494
NR7, INSIDE DAY AND BOLLINGER BAND .......................................................................................495
STOWELL’S THREE-BAR NET LINE .....................................................................................................499
NONLINEAR EHLERS FILTER .............................................................................................................505
NEW MARKET PARADIGM SYSTEM ....................................................................................................508
BETTER BOLLINGER BANDS BY DENNIS MCNICHOLL ......................................................................510
KLINGER VOLUME OSCILLATOR ......................................................................................................512
TPF_REVERSAL2002 .......................................................................................................................514
{MARKET DIRECTION}.....................................................................................................................517
REAL TIME PIVOT 2000....................................................................................................................518
VOLATILITY STOP INDICATOR ..........................................................................................................519
CLUSTER 20000................................................................................................................................521
REVERSAL INDICATOR ......................................................................................................................522
HI LO PIVOTS ...................................................................................................................................523
INTRADAY HI LO .............................................................................................................................524
PB LONG ..........................................................................................................................................525
PB SHORT ........................................................................................................................................527
RUBBER BAND2................................................................................................................................529
SFD..................................................................................................................................................530
SFK..................................................................................................................................................531
SSD..................................................................................................................................................531
CLUSTER VOLATILITY STOP – USES CLUSTER 2000 AS A FUNCTION .................................................532
CLUSTER 2000.................................................................................................................................534

7
REVERSAL INDICATOR ......................................................................................................................535
CLUSTER INDICATOR CODE ...............................................................................................................535
CANDLESTICK PATTERN RECOGNITION ............................................................................................536
TFS TREND FOLLOWING SYSTEM ....................................................................................................544
TETHERLINE .....................................................................................................................................545
VOLUME OSCILLATOR ......................................................................................................................546
DOUBLE STOCHASTIC .......................................................................................................................546
RINA DATA COLLECTION PORTFOLIO OUTPUT ...............................................................................547
WILL SPREAD ...................................................................................................................................551
MAMA FAMA................................................................................................................................551
ACTIVE INVESTING ...........................................................................................................................553

8
AIQ Code

CANDLESTICKS

See Separate file

CANDLESTICK COLOUR STUDY

!Colour Study

GreenCandle if ([Open]<=[Close]).
RedCandle if ([Open]>[Close]).

GreenBar if ([close]>=val([close],1)).
RedBar if ([close]<val([close],1)).
Island reversal

!==================================================
lowbody is min([open],[close]).
highbody is max([open],[close]).
gapup if valresult(lowbody,1) > valresult(highbody,2).
gapdn if valresult(lowbody,1) < highbody.
islandReversal if gapup and gapdn.
!===================================================

I have not tested this. I hope it is correct.

Almost correct... just reverse the UDFs:


gapdn if highbody < valresult(lowbody,1).

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

RATE OF CHANGE

! prdsys@pewd.com august 2000 www.pewd.com


! ROC indicator (rate of change)
! source: TA from A-Z, S. Achelis www.equis.com/free/taaz/
! change value of nbrdays to change number of days in indicator originally coded for
12 period ROC

define nbrdays 12.


closexago is val([close],nbrdays).

9
roc is (([close]-closexago)/closexago)*100.

rocaverage is simpleavg(roc,21).

check my code for accuracy before trading off of them

MONEY MANAGEMENT EXITS

!! Exits Start Here !!

losslimit is 1.25. !! This controls the stop loss limit.


stesa is expavg([close],5).
stoploss if val([high],1) >={position entry price} * losslimit.
profitarget if val([low],1) <= valresult(stesa,1).

!! Insert the UDF and rule(below) into the backtester.


exitprice is iff(stoploss, {position entry price} * losslimit,
iff(profitarget,valresult(stesa,1), val([close],1))).
closeposition if [high] >= {position entry price} * losslimit or [low] <=stesa or
{position days} =4 or mfi1 < 0.1.

!!! Exit the position when one of the following 4 events occurs first:
!!! 1) a -25% max stoploss is reached,
!!! 2) or profit target is triggered when price hits the 5-day ESA,
!!! 3) or the 1-day MF RSI turns 0,
!!! 4) or at the close of day 4.

!!! If money management does not allow you to use a -25% stop loss, then use a
smaller limit. It will decrease overall
performance, but it will make you FEEL safer.

=============================================================

MACDI EXIT RULES

! Based upon strategies from "Street Smarts", copyright M. Gordon Publishing.

!Linda Bradford Raschke MACDI exit rules

MACDXEXIT if
val([macd],2)< val([macd],1)
and val([macd],1)> val([macd],0)
and val([macd],1)>0

10
and val([macd],2)>0
and [macd]>0
and HiVal([Macd],20)=val([macd],1).

CONDITIONAL RULES-SELLING PRESSURE

I did more work on this and now it works for all the stocks in my
database with look
back of 22 days-all of my stocks showed at least 4 up days in a 22
day look back
period from today:

!=============================
!Selling Pressure 4 day average in 22 day lookback:

ORg is [open]-[low].
UpC if [close]>val([close],1).

A1 is Sum(ORgUpC,4)/4.
A2 is Sum(ORgUpC,5)/4.
A3 is Sum(ORgUpC,6)/4.
A4 is Sum(ORgUpC,7)/4.
A5 is Sum(ORgUpC,8)/4.
A6 is Sum(ORgUpC,9)/4.
A7 is Sum(ORgUpC,10)/4.
A8 is Sum(ORgUpC,11)/4.
A9 is Sum(ORgUpC,12)/4.
A10 is Sum(ORgUpC,13)/4.
A11 is Sum(ORgUpC,14)/4.
A12 is Sum(ORgUpC,15)/4.
A13 is Sum(ORgUpC,16)/4.
A14 is Sum(ORgUpC,17)/4.
A15 is Sum(ORgUpC,18)/4.
A16 is Sum(ORgUpC,19)/4.
A17 is Sum(ORgUpC,20)/4.
A18 is Sum(ORgUpC,21)/4.
A19 is Sum(ORgUpC,22)/4.

Cup1 if countof(UpC,4)=4.
Cup2 if countof(UpC,5)=4.
Cup3 if countof(UpC,6)=4.
Cup4 if countof(UpC,7)=4.
Cup5 if countof(UpC,8)=4.
Cup6 if countof(UpC,9)=4.
Cup7 if countof(UpC,10)=4.
Cup8 if countof(UpC,11)=4.
Cup9 if countof(UpC,12)=4.
Cup10 if countof(UpC,13)=4.
Cup11 if countof(UpC,14)=4.
Cup12 if countof(UpC,15)=4.
Cup13 if countof(UpC,16)=4.
Cup14 if countof(UpC,17)=4.
Cup15 if countof(UpC,18)=4.
Cup16 if countof(UpC,19)=4.
Cup17 if countof(UpC,20)=4.
Cup18 if countof(UpC,21)=4.

11
CountUp is countof(UpC,22).

Avg4day is
iff(Cup1,A1,iff(Cup2,A2,iff(Cup3,A3,iff(Cup4,A4,iff(Cup5,A5,iff(Cup6,
A6,
iff(Cup7,A7,iff(Cup8,A8,iff(Cup9,A9,iff(Cup10,A10,iff(Cup11,A11,

iff(Cup12,A12,iff(Cup13,A13,iff(Cup14,A14,iff(Cup15,A15,iff(Cup16,A16
,
iff(Cup17,A17,iff(Cup18,A18,A19)))))))))))))))))).

!The following is to display data to test calculation of average:


ORgUpC is IFF(UpC,ORg,0).
ORgUpC1 is valresult(IFF(UpC,ORg,0),1).
ORgUpC2 is valresult(IFF(UpC,ORg,0),2).
ORgUpC3 is valresult(IFF(UpC,ORg,0),3).
ORgUpC4 is valresult(IFF(UpC,ORg,0),4).
ORgUpC5 is valresult(IFF(UpC,ORg,0),5).

GoodData if HasDataFor(255)>=252 and expavg([volume],50)>3000


and [close]>=5 and mover and not ScanAny(GapDown,20) and
resetdate() and
CountUp>=4.
GapDown if Val([low],1) - [high]>2.

Look if [ADX]>30 and [DirMov]>0 and Avg4day<1.00 and GoodData.

HG if Look and [low]<=expavg([close],20).

!Mover scan created by Bill S. (from Bear Essentials):


bigs if [Close] > 10.
diffrat is (([high] - [low]) / [low]) * 100.
avgrat is simpleavg(diffrat,30).
mover if avgrat > 4.
BigMover if avgrat>8.

List if 1=1.

MOMENTUM
! prdsys@pewd.com august 2000 www.pewd.com
! momentum indicator
! sources: TA from A-Z, S. Achelis www.equis.com/free/taaz/
! MarketTrack-MX user manual, page 10-16 (Track Data Corp)

define nbrdays 12.


momentum is ([close]/val([close],nbrdays))*100.

check my code for accuracy before trading off of them

12
VIDYA - TUSHAR CHANDE

Here's Vidya based on a 9-period CMO, or as close as we can get given > TEP's
limitations for recursive calculations. Change VidLen to vary > the > (nominal) length
of the moving average. As an indicator it is very > slow > to calculate, but is not bad
in a scan.

> > HHP

! (based on 9-period CMO).


!==================================

Define CMOLen 9. ! Conventional value is 9.

Define VidLen 12. ! Smoothing. Vary to suit.

Define Itr 100. ! Iterations allowed (maximum 240).

!=============================

MO is [Close] - Val([Close], 1).


AbsMO is Abs(MO).
AbsCMO is 0.01 + Abs(Sum(MO, CMOLen)) / (Sum(AbsMO, CMOLen) + 0.01).

Alpha is (2 / ((1 + VidLen)) * AbsCMO).


Beta is 1 - Alpha.

DaysInto is ReportDate() - RuleDate().


Stop if DaysInto > Itr.
StopCalc is iff(Stop, [Close], Vidya).

Vidya is Alpha * [Close] + Beta * ValResult(StopCalc, 1).

!===================================

SECTOR MOVEMENT

Steve, Quite correct to point out this market has no intrinsic worth of 5000 and the
trip back to that level may take years, I meant that because it is a long trip, I'm not in a
hurry to jump on the first train that leaves. There will be plenty of opportunity to
catch a tech wave or two. The sector rotation formula is very simple, but it has
backtested better than TS for the way I am using it. It mostly fires at the beginning of
a shift in leadership, and is best with 20 day holds or so. The gifs will show you what
it looks like, and it doesn't look very good because it fires for a few days and then
drops. It is only used to fire a good sector signal, the stock sell is based on stock
action, not a drop in the sector signal.
!==========================================================

13
!GROUP & SECTOR STUFF ! Rich set up form
Description is Description().
GroupSymbol is TickerUDF(RSTicker(),Symbol()).
GroupName is TickerUDF(RSTicker(),Description).
SectorSymbol is TickerUDF(RSTicker(),GroupSymbol).
SectorName is TickerUDF(SectorSymbol,Description).
SectorTCIDIR is TickerUDF(SectorSymbol,TCIDIR).
GroupTCIDIR is TickerUDF(GroupSymbol,TCIDIR).

TCIDIR is (( [TCI]-val([TCI],1))*10 )+ [dirmov]-60. !combines the TCI and the


DIRMOV to find quik trend

Tech if SectorSymbol="MGTECHNO". !I set up my sectors based on the 10


Market Guide sectors,but any will work
NOTECHNOSECTOR if not tech.
notech if NOTECHNOSECTOR and SectorTCIDIR>=0. ! used to keep techs out
of the game if the NASDAQ is on a decline
! but any other sector that shows life will be active for a few days.

!ALL weather for month long 20 stocks


!will switch to non-tech sectors if they are hot when combosig=-1
!..code for stock picking--last few criteria
and [TCI]<65
and not FoundGaps
and ((combosig=-1 and notech) or combosig=1). ! this lets ANY stock get picked
when the NASDAQ is on a buy
! but if on a sell, only nontech sectors IF they are hot will fire

14
Weighted Action List Report

attached are the action and weighted action reports, in eds, which is real
close to the system supplied reports (report module). change the constants
to match what you usually run on reports, and don't forget to change to
whatever list you want to run for (file/properties).

2 report tabs, 1 for wa report, another for the action report, both upside
versions. i didn't code the downside reports. and i should note, AIQ
wrote the original EDS - i just fixed it and modified it slightly, the
original work is AIQ's, not mine.

note that there are a few oddities in the wa report, not reflected in the
code - this version of the code matches the report as close as i can get it,
at least till the next time someone prompts me to look at it ;)

first oddity - wa report looks back x days, action report looks back x+1
days, for looking for an up er.

next item, in the report (and attached eds) the system does not look for a
phase reversal upside followed a day or 2 later by a reversal downside,
followed by another reversal up. it does make sure phase is currently going
up, but doesn't check for whipsaws (up/down/up). if i recall correctly, you
will occasionally see stocks on the weighted action report which have had a
upside phase reversal a few days ago, followed by a downside reversal a day
or 2 later, then another up. personally, i don't trade such stocks. your

15
mileage may vary, disclaimer, do what you will with it , i'm not liable (too
many lawyers in my family i guess :) )

the other thing i'm not checking for in the code is an up er followed a few
days later by a down er. an example would be yhoo - up er on 1/3, down er
on 1/11, yet its on the report. same comment as above. i disagree with the
report specs in this case - i don't want to see it if an up er has been
followed by a down one, regardless of current phase direction. others
however would view the down er as unconfirmed, and thus a non signal, due to
lack of down phase action, so they remain on the report. other versions of
this EDS that i've passed around in the past do check for an intervening
down er, and exclude such stocks - this version doesn't as i tried to match
the report. same disclaimer, check your charts before pulling the trigger.

! -----------------------------------------------------------------------------------------------
! eds to match weighted action report
! modified by pewd from original version supplied by AIQ
! check what settings you have on wt act rpt if youre trying to match this eds to the
report,
! eg., make sure youre running for the same list, price, and volume filters as on the wt.
act. report
!
! ER to upside 95 or greater last 10 days confirmed by change in direction of the Price
Phase indicator in the last 3 days.
!
! modifications to original (aiq) version:
! pewd 7/99 added price filter, $10 and up
! pewd 7/99 added volume filter, 100,000 shares and up
! pewd 7/99 changed up er lookback from 10 to 6
! pewd 7/99 corrected logic error in PhaseChangeUp test, eliminate stocks that turned
phase down on report date
! pewd 7/99 added 4th day to PhaseCHANGEUPup rule to match reports module
! pewd 7/99 added er, price, and a few other columns to report
! pewd 1/01 added action report tab, cleaned up my sloppy code from 99
! ------------------------------------------------------------------------------------------------------
-------------------------

! define report constants


define minprice 10. ! minimum price
define minvolume 1000. ! minimum volume, in lots (x 100)
define nbrdays 11. ! nbr days to look for an up er
define miner 90. ! minimum er value to trigger
define nbrphasedays 4. ! number of days to look back for phase reversal

! check for minimum price


pricefilter if [close]>=minprice.

16
! check for minimum volume
volumefilter if [Volume ESA] > minvolume.

phasereverse if val([phase],1)<[phase] and val([phase],2)>val([phase],1).


goodphase if ^[phase]>^val([phase],1).
phasechangeup if scanany(phasereverse,nbrphasedays) and goodphase.

! look for ER buy signal


WA_Report_Up if HiVal([ER UP],nbrdays) >=MinER and PhaseChangeUp and
PriceFilter and VolumeFilter.
Action_Report_Up if HiVal([ER UP],nbrdays-1) >=MinER and PhaseChangeUp and
PriceFilter and VolumeFilter.

! report columns
!pewd july 99
UpER is hival([ER UP],nbrdays).
Exch is MarketCode().
Change is [close]-val([close],1).
Security_name is Description().
Trend is [TS].
DeltaTrend is [DTS].
GroupSymbol is TickerUDF(RSTicker(),Symbol()).
GroupName is TickerUDF(RSTicker(),Security_name).
GroupTS is TickerUDF(RSTicker(),Trend).
GroupDTS is TickerUDF(RSTicker(),DeltaTrend).
SectorSymbol is TickerUDF(RSTicker(),GroupSymbol).
SectorName is TickerUDF(SectorSymbol,Security_name).
SectorTS is TickerUDF(SectorSymbol,Trend).
SectorDTS is TickerUDF(SectorSymbol,DeltaTrend).

PRICE/VOLUME CRITERIA?

Gap is IFF([low]>Val([High],1) and ([low]/Val([High],1))>=1.15 and


([close]/Val([High],1))>=1.15,1,0).
Keep if [volume esa]>500 and Sum(Gap,100)=0 and Countof([volume]>0,100)>=98.

HIGH JUMP CANDIDATE SELECTION

I wrote the HighestHighJump scan and I use it just as you do to develop a list of
trading candidates.

The inventor of the HJ indicator is Ian Woodward. He uses it as a gauge of how


extended a stock is off its base. When the numbers get over certain cutoffs (on a
current basis), he says there is a high danger of a major correction in the stock.

17
After I programmed the indicator in AIQ, I noticed that some stocks got to much
higher HJ numbers than others. I also noticed that most of the High Growth stocks
that Ian (and William O'Neil) define by other means (eg EPS rank, RS and Group RS
etc) could be defined by a high peak readings in their maximum HJ levels. So I wrote
the scan that looks back and picks out the highest reading over a lookback period of
five years or less if less trading history. The ones with the highest readings were
always the high growth and/or momentum stocks. What this indicator does is measure
the ability of a stock to rise rapidly. The higher the reading the faster the stock
has been able to climb.

I am working on additional ways to develop trading lists and I will post more on this
when I have time. I asked other traders to propose how they would go about
developing
a short list of stocks. I received several good suggestions and I want to thank those
who contributed.

Here is the code for the HJ (but not the Highest High Jump) for those of you who are
wondering what it is:

!HIGH JUMP INDICATOR - from Ian Woodward


!For Ian Woodward's standard HighJump set ST MA to 17, IT MA to 50, LT MA to
200.
STMA is simpleavg([close],17).
ITMA is simpleavg([close],50).
LTMA is simpleavg([close],200).
STdmaPct is ([close]-STMA)/STMA*100.
ITdmaPct is ([close]-ITMA)/ITMA*100.
LTdmaPct is ([close]-LTMA)/LTMA*100.
Highjump is STdmaPct + ITdmaPct + LTdmaPct.

VOLUME SPIKE

*******************
!ER is 95 or above within last 5 days
!Strength of Group is based on trend score , or high positive value for DTS
! P-Vol is higher than yesterday and todays P-Vol is higher than its ESA.
! Spike if volume is 50% above the ESA of volume
!Buy the stock when all rules are passed.
TS is [TS].
DTS is [DTS].
Description is Description().
GroupDTS is TickerUDF(RSTicker(),DTS).
GroupTS is TickerUDF(RSTicker(),TS).
Group is TickerUDF(RSTicker(),Description).

18
GroupTSHigh if GroupTS>90.
GroupDTSHigh if GroupDTS>20.
ERUP if HiVal([er up],5) >= 95.
PVolUP if VAL([P-Vol],1) < [P-Vol] and [P-Vol] > [P-Vol ESA] .
VolSpike if [volume] >= [volume esa] * 1.5.
BuyMid2 if HiVal([er up],5) >= 95 and PVolUP and VolSpike and (GroupTSHigh or
GroupDTSHigh)
***********************************

VARIABLE PROFIT PROTECT STOP, LOSS STOP AND TIME STOP

!Variable Profit Protect Stop, Loss Stop and Time Stop


! Coded by Rich Denning
! Date: 3/10/2001
! This file was written for the AIQ Yahoo Groups Message Board and is for
demonstration
! and educational purposes only. Distribution outside of this message board or use
! in commercial applications is prohibited.
! If any of this file is copied, in part or in whole, this header must be included with it.
!The following requires AIQ version 6.0 and can only be used as an exit rule in a
bactest of a simulation
P is {Position Days}.
MaxProfitR is {Position High Price}/{Position Entry Price}.
Profit is [close]-{Position Entry Price}.
MaxProfit is HighResult(Profit,P).
Stop1 is {Position Entry Price}+MaxProfit*0.70.
Stop2 is {Position Entry Price}+MaxProfit*0.80.
Stop3 is {Position Entry Price}+MaxProfit*0.90.
Stop4 is {Position Entry Price}+MaxProfit*0.95.
Stop5 is {Position Entry Price}+MaxProfit*0.98.
Stop6 is {Position Entry Price}+MaxProfit.
! Protect 70% of profit above 50%
! Protect 80% of profit above 60%
! Protect 90% of profit above 70%
! Protect 95% of profit above 80%
! Protect 98% of profit above 90%
! Protect 100% of profit above 100%
ProfitProtect if [close]<iff(MaxProfitR>1.5 and MaxProfitR<1.6,Stop1,
iff(MaxProfitR>1.6 and MaxProfitR<1.7,Stop2,
iff(MaxProfitR>1.7 and MaxProfitR<1.8,Stop3,
iff(MaxProfitR>1.8 and MaxProfitR<1.9,Stop4,
iff(MaxProfitR>1.9 and MaxProfitR<2.0,Stop5,
iff(MaxProfitR>2.0,Stop6,0)))))).
LossStop if [close]<{Position Entry Price}*0.75.
!TimeStop if {Position Days}>=20.
MasterExit if ProfitProtect or LossStop

19
BUY FOR STOCKS IN A SECTOR
!Scan for DTUniversity
Price if [close]<51 AND [close]>19.
AvgVol is [Volume ESA].
Vol if ExpAvg(AvgVol,14)>1200 AND [Volume]>1200.
!To-days range
Range is [high]-[low].
HighRange If ExpAvg(Range,14)>4 AND Range>4 .
CCIUp IF Slope([CCI],5)>0 AND [CCI]>0.
Avgvcrossover IF [ST ESA]>[IT ESA] AND ( Val([ST ESA],1)<Val([IT ESA],1)).

Security_nameis Description().
GroupSymbol is TickerUDF(RSTicker(),Symbol()).
GroupName is TickerUDF(RSTicker(),Security_name).

Semiconductor if GroupSymbol="ETSEMMFG".
ComputerSoftware if GroupSymbol="CSSFTETR".
Internet if GroupSymbol="INECOMM".
ComputerHardware if GroupSymbol="CPMFGS".
Biotech if GroupSymbol="MDBIOGEN".

Buy IF Price AND Vol AND HighRange AND CCIup AND (semiconductor OR
ComputerSoftware OR Internet OR ComputerHardware OR Biotech).

BOLLINGER BANDS

> =====================================
> varudf is [close].
> variance is Variance(varudf,21).
> stddev is Sqrt(Variance).
> ma is SimpleAvg(varudf,21).
>
> UpperBB is 2 * StdDev + ma.
> LowerBB is ma - 2 * StdDev.
> =======================================

Slope etc

While I am at it...here is something that is VERY valuable to your bag of EDS tricks.
It is the calculation used to calculate the internal function "slope". The math may be
way over some peoples heads,but the most important thing about having this is the
ability to calculate the INTERCEPT point!

Alan Nathan asked about doing Standard Deviation lines based on the linear
regression line. In order to do this you must have the intercept point. So I coded the
internal Slope function in EDS so you can now have this. I put together an EDS file

20
that does the math, and creates "bands" based on 2 standard deviations above/below
the intercept point of the linear regression line. I hope this is close to what Alan has
asked for. You can put UpperSD and LowerSD and Intercept as Custom Indicators
and plot the bands.

! Author: Dale Paul (AIQ)


! Date: 4/7/2001
! How to calculate a slope and intercept using linear regression

! how many days are we running this for?


define constdays 4.
days is HasDataFor(constdays).

! value (in this case the close)


varudf is [close].

LINEAR REGRESSION CALCULATION USING THE LEAST MEANS SQUARED METHOD

day is offsettodate(month(),day(),year())+1.
dayX2 is day * day.

sx is Sum(day,days).
sx2 is Sum(dayX2,days).
sy is Sum(varudf,days).
sxy is Sum( day * varudf ,days).
d is ( days * sx2) - (sx * sx).

slope is ((days * sxy) - ( sx * sy)) / -d. ! same result as internal Slope function
b is ((sx2 * sy) - (sx * sxy)) / d.

Intercept is slope + b.

! get the standard deviation of the close


variance is Variance(varudf,days).
stddev is Sqrt(Variance).

! Compute our Deviation Bands


UpperSD is 2 * StdDev + Intercept.
LowerSD is Intercept - 2 * StdDev.

all if 1.

LINEAR REGRESSION METHOD BASED INDICATORS

There was an error in my linear regression code--the intercept was claculated


incorrectly. Thanks to John R for pointing this out.
The correct eds code is

21
define TimeFrame 30.
b is slope([close],TimeFrame).
intercept is sum([close],TimeFrame)/TimeFrame - (b * (TimeFrame+1)/2).
expectedLast is intercept + (TimeFrame*b).

SECTOR DIVERGENCE

!!! Sector Divergence


!!! EDS Author. Ron Stockstill
!!! Date. 4/9/2001.

!!! Define constants

define slopelen 20. ! determine length of lookback for slope function to see if a
divergence in price
define divpct 15. ! set divergence percentage

Sym is symbol().
Desc is description().
GroupSym is TickerUDF( RSTicker(),symbol()).
SectorSym is TickerUDF( RSTicker(),groupsym).

stock if stock(). ! Only want stock symbols.


MedSector if SectorSym = "medical". ! Check for medical sector

TechSector if SectorSym = "electric".

Biotech if GroupSym = "medic1". ! AIQALL list uses medic1 for


biotech
Semi if GroupSym = "Elect10".

Slope is Slope([close], slopelen). ! Calculate slope of linear


regression line
GroupSlope is TickerUDF(groupsym,slope). ! Calculate slope of linear
regression line for group symbol

groupstock if Semi or Biotech. ! Only want symbols from


semiconductors or biotechs

Pctgain is 100*([close] - Val([close],slopelen))/Val([close],slopelen). !


Calculate percent gain using slope length as lookback period.
groupPctGain is TickerUDF(groupsym,Pctgain).

Totalgain is Pctgain + ABS(groupPctGain). ! Use Absolute value as a negative


slope will normally but not always have a negative return.

!! Code Positive Divergence using Slope

22
Diverge if stock and
groupstock and
Slope > 0 and
GroupSlope < 0 and
Totalgain > divpct.

COUNTOF

Rule if [close] > simpleavg([close],20).


CountRule if Countof(Rule,1)=1 and Countof(Rule,2) =1. ! False on day
n+2; True on day n+1

================================================

Tom,

Rule is true if close is greater than the 20 day sma.


Now suppose you have two days in a row of closes above 20 day sma.
Rule will be true for today and also Rule will be true for yesterday.
Thus Countof(Rule,2) will = 2 (1 + 1). Thus, Countof(Rule,2)=1 will be
FALSE.

Now CountRule is only true when


yesterday is FALSE and today is TRUE. If today is below the
moving average, the Countof(Rule,1) will be zero and CountRule will
be false. This leaves the only combination that CountRule can be
true; yesterday below the SMA and today above the SMA.

You could have used Valresult(rule)<> 1 and rule=1 for CountRule.

ATR AND WILDER’S RSI

!==========================
!!! Average True Range.

TR is Max([High], Val([Close], 1)) - Min([Low], Val([Close], 1)).


ATR27 is ExpAvg(TR, 27). !! Equivalent to ATR14 using Wilder's
smoothing.

!========================
PlusDM1 is [High] - Val([High], 1).
PlusDM2 is Max(PlusDM1, 0).
PlusDM is PlusDM2 * (PlusDM2 > MinusDM2).
AvgPlusDM is ExpAvg(PlusDM, 27).

23
PlusDMI is AvgPlusDM * 100 / ATR27. !! Plot wuth MinusDMI as 2-line
indicator.

MinusDM1 is Val([Low], 1) - [Low].


MinusDM2 is Max(MinusDM1, 0).
MinusDM is MinusDM2 * (MinusDM2 > PlusDM2).
AvgMinusDM is ExpAvg(MinusDM, 27).

MinusDMI is AvgMinusDM * 100 / Atr27. !! Plot with PlusDMI as 2-line


indicator.

DlDiff is PlusDMI - MinusDMI. !! Plot as histogram. Same as AIQ's


DirMov.
DlSum is PlusDMI + MinusDMI.
DX is Abs(DlDiff) * 100 / DlSum.
ADX is ExpAvg(Dx, 27). !! PLOT ADX as single line indicator with
support at 24, same as AIQ's ADX.

!==========================

RELATIVE STRENGTH

!RELATIVE STRENGTH STUDY by Rich Denning 10/23/99


!Run against your group or sector structure by clicking on file, properties, then put in
group list eg AIQALL and check groups only

!Indicatior for ranking RS of stocks, groups or sectors (you can set these up a custom
indicators on the charts)
RS4 is SLOPE([RS Indx],4)*100.
RS9 is SLOPE([RS Indx],9)*100.
RS17 is SLOPE([RS Indx],17)*100.
RS50 is SLOPE([RS Indx],50)*100.
RS200 is SLOPE([RS Indx],200)*100.
RScomposit is RS17 + RS50 + RS200.

!Is trend up or down in various time frames? my settings are st=17, it=50, lt=200
STtrend is SLOPE([st ma],5).
ITtrend is SLOPE([it ma],5).
LTtrend is SLOPE([lt ma],5).

!List of all tickers


List if 1=1.

Description is description().
Group is TickerUDF(RSTicker(),Description).
Sector is TickerUDF(RSTicker(),Group).

24
!List of positive relative strength tickers (short term)
Define Length1 17. ! Or 4,9
RS1 is 100*SLOPE([RS Indx], length1).
STposRS if RS1 > 0.

!List of positive relative strength tickers (long term)


Length2 is 200. !Or 50, 100
RS2 is SLOPE([RS Indx],length2)*100.
LTposRS if RS2 > 0.

!List of negative relative strength tickers (short term)


STnegRS if RS1 < 0.

!List of positive relative strength tickers (long term)


LTnegRS if RS2 < 0.

!List all positive tickers


AllPos if STposRS and LTposRS and RScomposit > 0 and [DTS]>=0 and [TS]>0
and [VA pct]>0.

!List HGS groups only


HGSgroup1 if 1=1. !Don't know how to do this yet
!HGSgroup if Symbol() is "COMP1" HGS group includes all Computer,
Electrical, Telecom, Medical plus selected others

RECURSION

!! Adaptive Moving Average (Perry Kaufman).


! (with allowances for AIQ recursion).
! EDS code by HHP.

!*******************************************

MA Long Term:
Mov(C,30,E);
Mov(C,35,E);
Mov(C,40,E);
Mov(C,45,E);
Mov(C,50,E);
Mov(C,55,E);

MA Short Term:
Mov(C,5,E);
Mov(C,8,E);
Mov(C,11,E);
Mov(C,14,E);
Mov(C,17,E);

25
Adaptive Moving Average:
period:=Input("Period",1,250,13);
DifP:=Abs(C-Ref(C,-1));
SC:=Power((Abs(C-Ref(C,-period)) / Sum(DifP,period)) * 0.60215{2/3-2/31} +
0.06452{2/31},2);
AMA:=PREV+(SC*(C-PREV));
AMA

!***********************************************

Define ERPds 10. ! Efficiency Ratio Periods.


Define FPds 2.
Define SPds 30.

Dir is [Close] - Val([Close], ERPds).

dPr is [Close] - Val([Close], 1).


Vlty is Sum(Abs(dPr), ERPds).

ER is Dir / Vlty.

Fastest is 2 / (FPds + 1).


Slowest is 2 / (SPds + 1).

Smooth is ER * (Fastest - Slowest) + Slowest.

C is Smooth * Smooth.

!=====================
! EDS Recursion. Original coding by Dale Paul.

Define RWin 100. ! Recursion window.


DaysInto is ReportDate() - RuleDate().
Stop if DaysInto > RWin.
StopADPT is IFF(Stop, [Close], ADPTMA).

ADPTMA is C * [Close] + (1 - C) * ValResult(StopADPT, 1).

!========================
!! AMA Filter.

Define FltWin 20. ! Filter Window periods).


Define FltPct 15.
dAMA is ADPTMA - ValResult(ADPTMA, 1).
AMAFlt is (FltPct / 100) * Sqrt(Variance(dAMA, FltWin)).

26
!=========================

27
MetaStock Code

PRIMARY BUY SIGNAL

((MACD()>Mov(MACD(),9,E) AND C>Mov(C,5,E) AND C>Mov(C,15,E))=TRUE)


AND
(Ref(MACD()>Mov(MACD(),9,E) AND C>Mov(C,5,E) AND
C>Mov(C,15,E),-1)=FALSE)
AND
BarsSince(Ref( ((MACD()>Mov(MACD(),9,E) AND C>Mov(C,5,E) AND
C>Mov(C,15,E))=TRUE) AND (Ref(MACD()>Mov(MACD(),9,E) AND
C>Mov(C,5,E)
AND C>Mov(C,15,E),-1)=FALSE),-1))
>=
BarsSince(Ref(Cross(0.955*Ref(C,-2),C),-1))

PRIMARY SELL SIGNAL

Cross(0.955*Ref(C,-2),C) AND
BarsSince(((MACD()>Mov(MACD(),9,E) AND C>Mov(C,5,E) AND
C>Mov(C,15,E))=TRUE) AND (Ref(MACD()>Mov(MACD(),9,E) AND
C>Mov(C,5,E)
AND C>Mov(C,15,E),-1)=FALSE))
<=
BarsSince(Ref(Cross(0.955*Ref(C,-2),C),-1))

and the MarketSpace Stock System which works with daily data.

MARKETSPACE STOCK SYSTEM

Primary Buy Signal

((MACD()>Mov(MACD(),45,E) AND C>Mov(C,25,E))=TRUE) AND


(Ref(MACD()>Mov(MACD(),45,E) AND C>Mov(C,25,E),-1)=FALSE) AND
BarsSince(Ref(((MACD()>Mov(MACD(),45,E) AND C>Mov(C,25,E))=TRUE)
AND

28
(Ref(MACD()>Mov(MACD(),45,E) AND C>Mov(C,25,E),-1)=FALSE),-1)) >=
BarsSince(Ref(Cross(0.9*Ref(C,-7),C),-1))

Primary Sell Signal

(Cross(0.9*Ref(C,-7),C) AND BarsSince(((MACD()>Mov(MACD(),45,E) AND


C>Mov(C,25,E))=TRUE) AND (Ref(MACD()>Mov(MACD(),45,E) AND
C>Mov(C,25,E),-1)=FALSE))<= BarsSince(Ref(Cross(0.9*Ref(C,-7),C),-1)))

SMOOTH STOCKS

David,
Following are two explorations which will find stocks with a high percentage of relatively
"smooth" stocks that have been trending up over the last a) three months and b) twelve
months.
In the Exploration Editor, put the following in one of the "columns":
(C - Ref(C,-252)) / Ref(C,-252) *100
This will give you the percentage gain over the last twelve months.
Some of the other columns could have the current closing price, average volume or whatever
has meaning to you.
In the Filter, put one of the following, depending on whether you want a three month trend or
a twelve month trend (or modify for some other period)
For three months:
(C / (1 + ((C - Ref(C,-64)) / Ref(C,-64))))
<=
(C / (1 + ((C - Ref(C,-21)) / Ref(C,-21))))
AND

(C / (1 + ((C - Ref(C,-21)) / Ref(C,-21))))


<=
(C / (1 + ((C - Ref(C,-5)) / Ref(C,-5))))
AND
(C / (1 + ((C - Ref(C,-5)) / Ref(C,-5))))
<=
C
AND
colB >= 20 {I use Column B for my twelve month percentage and don't want to see any stocks
with less than a 20% trailing twelve month gain.}
For twelve months:
(C / (1 + ((C - Ref(C,-252)) / Ref(C,-252))))
<=
(C / (1 + ((C - Ref(C,-126)) / Ref(C,-126))
AND
(C / (1 + ((C - Ref(C,-126)) / Ref(C,-126))))
<=

29
(C / (1 + ((C - Ref(C,-64)) / Ref(C,-64))))
AND
(C / (1 + ((C - Ref(C,-64)) / Ref(C,-64))))
<=
(C / (1 + ((C - Ref(C,-21)) / Ref(C,-21))))
AND

(C / (1 + ((C - Ref(C,-21)) / Ref(C,-21))))


<=
(C / (1 + ((C - Ref(C,-5)) / Ref(C,-5)))
AND
(C / (1 + ((C - Ref(C,-5)) / Ref(C,-5))))
<=
C
AND
colB >= 20
After running the exploration, I sort on the twelve month column (Column B) to get the biggest
12 month gainers on top of the list. Many of the stocks in this list (not all) will be "smooth"
gainers and momentum stocks. Then comes the question, how to make money from these
stocks?
Jim Dawson
-----Original Message-----
From: owner-metastock@metastock.com [mailto:owner-
metastock@metastock.com]On Behalf Of David DeFina
Sent: Friday, June 08, 2001 12:07 PM
To: METASTOCK@metastock.com; Metastockusers@yahoogroups.com
Subject: Finding "smooth" stocks?

I’m interested in identifying stocks that have “smooth” transitions up and down,
meaning when a stock is increasing day to day that the lows of the previous day
aren’t violated, and vice versa. Also, stocks that have a tendency to increase or
decrease multiple days rather than reversing all the time.

I know stocks don’t behave consistently all the time, but I’m looking to rank stocks
from a specific universe that have the propensity to trade smoothly. Any input would
be appreciated.

Thanks,

David DeFina

Bressert Cycle Indicators

I saw that some were interested in the Bressert cycle indicators for use in Metastock.
Here is my implementation of the cycle 10 indicator; I have been using it for more
than one year as part of explorations. If you want the cycle 5, just substitute 5 for the
10 in the formulas.
Good luck I find these cycle indicators helpful.
The below should be installed as a custom indicator. It can then be used on charts and
called for in explorations.

30
{double smoothed stochastic 10 period}
{demominators defined to eliminate divide by zero errors}
denom1:= If(HHV(H,10)-LLV(L,10)>0, HHV(H,10)-LLV(L,10), 1);
P1:= Mov(((C-LLV(L,10))/ denom1)*100,3,E);
denom2 := If(HHV(P1,10)-LLV(P1,10)>0, HHV(P1,10)-LLV(P1,10), 1);
Mov(((P1-LLV(P1,10))/denom2)*100,3,E)

EXPLANATION OF THE MCCLELLAN OSCILLATOR

(DAILY ADVANCING ISSUES -(minus) DAILY DECLINING ISSUES)= B


McClellan OSC= MOV(B,19,E)- MOV(B,39,E)
WHERE: -100 OR LESS IS OVERSOLD (BULLISH)
WHERE: +100 OR GREATER IS OVERBOUGHT (BEARISH)
Note that B is just a constant for illustration purposes only.
Advance Decline Line
{To display the Advance Decline Line, create a composite security in The
DownLoader of Advancing Issues minus Declining Issues. Open a chart of
the composite and plot this formula}
Cum(CLOSE)
McClellan Oscillator
{To display the McClellan Oscillator, create a composite security in The
DownLoader of Advancing Issues minus Declining Issues. Open a chart of
the composite and plot this custom indicator.}
Mov(CLOSE,19,EXPONENTIAL) - Mov(CLOSE,39,EXPONENTIAL)
mike arnoldi
CMO FILTER
CMO Filtered:
momu:=If(C>Ref(C,-1),C-Ref(C,-1),0);
momd:=If(C<Ref(C,-1),Ref(C,-1)-C,0);
A1:=Stdev(momu,100);
A2:=Stdev(momd,100);
Mup:=If(C-Ref(C,-1)>A1,C-Ref(C,-1),0);
Mdn:=If(Ref(C,-1)-C>A2,Ref(C,-1)-C,0);
Periods:=Input("Length",5,100,13);
CMOF:=100*((Sum(Mup,Periods)-Sum(Mdn,Periods))
/(Sum(Mup,Periods)+Sum(Mdn,Periods)));
Sig:=Mov(CMOF,10,S);
Hist:=CMOF-Sig;
Hist;
Sig;
CMOF;

THRUST OSCILATOR:
AI:= Security("D:\Stocks\Market
Indicators\X.NASD-A",C);
AV:= Security("D:\Stocks\Market

31
Indicators\X.NASD-A",V);
DecI:= Security("D:\Stocks\Market
Indicators\X.NASD-D",C);
DecV:= Security("D:\Stocks\Market
Indicators\X.NASD-D",V);
TO:=(((AI*AV)-(DecI*DecV))/((AI*AV)+(DecI*DecV)))*100;
Periods1:=Input("length1",3,100,21);
Periods2:=Input("length2",3,100,5);
IND:=Mov(TO,Periods1,S);
sig:=Mov(IND,Periods2,S);
sig;
IND;
You will have to create securities of advancing issues,declining issues,advancing
volume, declining volume first then type in the directory where they are located
Henry kaczmarczyk
THRUST OSCILLATOR

the thrust osc, the metastock formula


AI:= Security("D:\Stocks\Market Indicators\X.NASD-A",C);
AV:= Security("D:\Stocks\Market Indicators\X.NASD-A",V);
DecI:= Security("D:\Stocks\Market Indicators\X.NASD-D",C);
DecV:= Security("D:\Stocks\Market Indicators\X.NASD-D",V);
TO:=(((AI*AV)-(DecI*DecV))/((AI*AV)+(DecI*DecV)))*100;
Periods1:=Input("length1",3,100,21);
Periods2:=Input("length2",3,100,5);
IND:=Mov(TO,Periods1,S);
sig:=Mov(IND,Periods2,S);
sig;
IND;
You will have to have created securities of advancing issues,declining
issues,advancing volume, declining volume
henry1224@hotmail.com

MIDAS VOLUME WEIGHTED AVE PRICE-SUPPORT/RESIST

From P.67, TASC, May 2001


MIDAS Volume Weighted Ave Price-Support/resist.}

sm:=Input("Starting Month",1,12,1);
sd:=Input("Starting day of month",1,31,1);
sy:=Input("Starting year",1980,2100,2000);
start:= sd = DayOfMonth() AND sm = Month() AND sy = Year();
pv:= MP()*V;

denom:=If(Cum(V)-ValueWhen(1,start,Cum(V))=0,1,Cum(V)-
ValueWhen(1,start,Cum(V)));

If(BarsSince(start),(Cum(pv)-ValueWhen(1,start,Cum(pv)))/denom,MP())

32
STOCHASTIC CROSS TRADING SYSTEM

QUESTION
How would I write a MetaStock System Tester for:
Buy: stoch(12,3) has fallen below 36 and then crosses above its 6 day WMA.
Sell: stoch(12,3) rises above 52 and then falls below its 3 day WMA OR 3 day WMA
of stoch crosses above 55.
ANSWER
stoch(12,3)<36 and cross(stoch(12,3),mov(stoch(12,3),6,w))
stoch(12,3)>52 and cross(mov(stoch(12,3),3,w),stoch(12,3)) or
mov(stoch(12,3),3,w)>55

TSI AND ERGODICS INDICATORS

Contributed by Christian Baude BAUDECB@ix.netcom.com


True Strength Index (TSI) - "Momentum, Direction and Divergence", William Blau,
Pub: John Wiley& Sons (see also TASC Jan '93, "Stochastic Momentum" gives the
formula for the true strength index. This article refers to an older article by Blau in the
Jan '91 TASC "Double Smoothed Stochastics")
TSI(close,r,s) = 100*EMA(EMA(mtm,r),s / EMA(EMA(ImtmI,r),s)
>> Your formula expanded
>>
100*(Mov(Mov(ROC(C,1,$),25,E),13,E)/Mov(Mov(Abs(ROC(C,1,$)),25,E),13,E))
Numerator:
mtm = one-day momentum of close
r-day EMA of mtm {25 day}
s-day EMA {13 day double smoothing}
Denominator:
ImtmI = absolute value of mtm
r-day EMA of ImtmI
s-day EMA {double smoothing}
TSI(close,25,13)
Signal Line = EMA(TSI,7)
thresholds at +25, 0, -25

5 day EMA of 20 day EMA of 1 day momentum

{little lag Vs smoothing of price}


Ergodic Oscillator = Ergodic + Signal line {TSI version of Slow Stochastic}
Ergodic(close,r) = TSI(close,r,5) {double smoothing is fixed at 5}
Signal Line(close,r) = EMA(TSI(close,r,5),5)
r = 20days
thresholds are +20, -20

33
Interesting comparison chart between 20 Slow Stochastic and 20 Erodic
{more head room in oversold-bought areas}
another chart showing Ergodic Osc = TSI(close,32,5) with 5-day EMA signal line

Trading Ergodics with the Trend – Rules

1. Enter or hold position only when slope of Ergodic Signal line has the same
direction as the trend
2. Stand aside when slope of Ergodic Signal Line is in the opposite direction of trend
3. Enter or exit position when Ergodic and its Signal Line cross
Slow TSI Trend = TSI(close,64,64) {? weekly looking chart - very little lag}
Thresholds set at +15 & -15
Trading Ergodics with Slow TSI Trend
1st window - Slow TSI Trend = TSI(close,64,64)
2nd window - Ergodic Osc = TSI(close,64,5)

RELATIVE STRENGTH OF STOCK TO INDEX


Here is what I have been using as Relative strength (RSC)Compared to the XAO
Column A: CLOSE
Column B: If( (Ref(Div(CLOSE,P),-4) > Ref(Mov(Div(C,P),30,E),-4)),1,0)
Column C: If( (Ref(Div(CLOSE,P),-3) > Ref(Mov(Div(C,P),30,E),-3)),1,0)
Column D: If( (Ref(Div(CLOSE,P),-2) > Ref(Mov(Div(C,P),30,E),-2)),1,0)
Column E: If( (Ref(Div(CLOSE,P),-1) > Ref(Mov(Div(C,P),30,E),-1)),1,0)
Column F: (( C/P - Mov(C/P,30,E)) / Mov(C/P,30,E)) * 100
Filter: Div(C,P)> Mov(Div(C,P),30,E) AND colB=1 AND colC =1 AND colD = 1
AND colE =1
I name columns B - E period 1, 2, 3, etc.
Open The chart of the index you wish to get the relative strength of the securities on
make periodicity "Week".
In the options area of the exploration editor change to Week.
This formula will select securities that have outperform the index over the last 5
weeks. The formula in column F provides a way to rank the securities in terms of their
recent performance relative to the index.
Frederick W McKenzie
:fmckenz@primus.com.au
FLEXIBLE PARAMETER BOLLINGER BAND
SYSTEM
N:=Input("Lookback Period", 9, 220, 90);
M:=N; {Period used for Momentum Index}
SD:=1.5; {Number of Stdev's around FlexPivot}
MI:= CMO(C ,M ) / 100; { Momentum Index }
MA:= Mov(C, N, S); { Moving Average }
FlxP := If( MI > 0,
{ THEN }
MA + (MI * (HHV(C, M) - MA)),
{ ELSE }

34
MA + (MI * (MA - LLV(C, M)))
); { ENDIF }
LBand := FlxP - SD * Stdev(INDICATOR, N);
UBand := FlxP + SD * Stdev(INDICATOR, N);
UBand;
FlxP;
LBand;
{from Andreas Grau}
DIVERGENCE TRADING SYSTEM
RSI(9) DIVERGENCE BUY:
If(RSI(9) >= HHV(RSI(9),19) AND CLOSE <HHV(CLOSE,19), 1,0) OR
If(CLOSE <= LLV(CLOSE,19) AND RSI(9) > LLV(RSI(9),19), 1,0)
RSI(9) DIVERGENCE SELL:
If(CLOSE >= HHV(CLOSE,19) AND RSI(9)<HHV(RSI(9),19),1,0) OR
If(RSI(9) <= LLV(RSI(9),19) AND CLOSE > LLV(CLOSE,19),1,0)
Substitute any formula for the "RSI(9)" in the above.
Mike Arnoldi
DYNAMIC ZONE WILLIAMS%R EXPLORATION
ColA:
Mov(WillR(19),70,S)-(1.3185 * Stdev(WillR(19),70))
ColB:
Mov(WillR(19),70,s)
Filter:
Cross(mov(WillR(19),70,s) , Mov(WillR(19),70,S)-(1.3185 * Stdev(WillR(19),70)))
{from suggestions by J. Seed and A. Grau}
DYNAMIC ZONE WILLIAMS%R INDICATOR
I have written a Dynamic Zone Williams % R indicator that you may find useful. I
have converted the Will%R to a +/- 50 oscillator. The formula is:
{DYNAMIC W%R}
PR:=Input("Enter Periods for W%R",1,100,14);
PB:=Input("Enter Periods for BUY",1,100,20);
PS:=Input("Enter Periods for SELL",1,100,20);
{CONVERT W%R TO +/-50 OSC}
DWR:=(Mov(WillR(PR),2,S))+50;
UpZone:=Mov(DWR,PS,S)+(1.3185 *Stdev(DWR,PS));
LwZone:=Mov(DWR,PB,S)-(1.3185 *Stdev(DWR,PB));
MidZone:=(UpZone + LwZone)/2;
MidZone;
UpZone;
LwZone;
DWR
This will plot 3 dynamic zones and a Dynamic Williams%R. To use in an exploration
you would need to use the Fml Var call function of the indicator.
from J. S
NEGATIVE CLOSES – DOWN DAYS
EXPLORE THE NUMBER OF NEGATIVE CLOSES AND THE PERCENT LOSS
CHANGING THE > WITH < WE HAVE THE POSITIVE DAYS .
COL A: BarsSince(C>Ref(C,-1)) {NUMBER OF NEG. DAYS )
COL B: ROC(C, LastValue(BarsSince(C>Ref(C,-1))),%) {PERCENT}

35
From "KAKARIDIS NIKOS"

FIND RSI ABOVE 80

Col A: RSI(14)
Filter colA>=80
Filter enabled Yes
Periodicity Daily
Records required 18

KASE DEV STOP

Hi Lino,
Here is what I found for her Kase DevStop:

{Cynthia Kase}
Per1:=Input("Max Length",2,100,30);

RWH:=(H-Ref(L,-Per1))/(ATR(Per1)*Sqrt(Per1));
RWL:=(Ref(H,-Per1)-L)/(ATR(Per1)*Sqrt(Per1));

Pk:=Mov((RWH-RWL),3,W);
AVTR:=Mov(HHV(H,2) - LLV(L,2),20, S);
SD:=Stdev(HHV(H,2) - LLV(L,2),20);
Val4:=If(Pk>0,HHV(H-AVTR-3*SD,20),LLV(L+AVTR+3*SD,20));
Val3:=If(Pk>0,HHV(H-AVTR-2*SD,20),LLV(L+AVTR+2*SD,20));
Val2:=If(Pk>0,HHV(H-AVTR-SD,20),LLV(L+AVTR+SD,20));
Val1:=If(Pk>0,HHV(H-AVTR,20),LLV(L+AVTR,20));

Val4;Val3;Val2;Val1;

WOLF WAVE PATTERNS

Here's a simple Metastock exploration for locating Wolf Wave patterns. It doesn't hit
all that often, but when it does, it's best to pay attention.
ColA: WW
Pa:=Trough(4,LOW,5);
Pb:=Peak(3,HIGH,5);
P1:=Trough(3,LOW,5);
P2:=Peak(2,HIGH,5);

36
P3:=Trough(2,LOW,5);
P4:=Peak(1,HIGH,5);
P5:=Trough(1,LOW,5);
tb:=TroughBars(1,LOW,5);
tb<=4 AND
p1 > pa AND
pb < p2 AND
p1 < p2 AND
p1 < p4 AND
p1 > p3 AND
p3 > p5 AND
p4 < p2 AND

ColB: Tangents

p1:=Trough(3,LOW,5);
p3:=Trough(2,LOW,5);
p5:=Trough(1,LOW,5);
o1:=p1-p3;
o2:=p1-p5;
a1:=TroughBars(3,LOW,5)-TroughBars(2,LOW,5);
a2:=TroughBars(3,LOW,5)-TroughBars(1,LOW,5);
tan1:=o1/a1;
tan2:=o2/a2;
Abs(tan1-tan2)

Filter:
colA AND colB <= .2

THE MARKET FACILITATION INDEX


In the August 1996 STOCKS & COMMODITIES, an article by Thom Hartle titled
"The Market Facilitation Index" showed how to color chart bars to identify chart
patterns based on changes in the market facilitation index and volume.
The first step is to create a new expert by choosing Expert Advisor from MetaStock's
Tool menu, and then choose New from the Expert Advisor. Name the expert "Market
Facilitation Index," enter any notes you like, and then click on the Highlights tab.
Enter the following Highlights by choosing New, choosing the color and then entering
the following formulas:
Green Bar (Green bar)
ROC((H-L)/V,1,$) > 0 AND
ROC(V,1,$) > 0
Fade Bar (Blue bar)
ROC((H-L)/V,1,$) < 0 AND
ROC(V,1,$) < 0
Fake Bar (Dk Gray bar)
ROC((H-L)/V,1,$) > 0 AND
ROC(V,1,$) < 0
Squat Bar (Red bar)
ROC((H-L)/V,1,$) < 0 AND

37
ROC(V,1,$) > 0
After you have entered the four Highlights, click OK to finish editing the expert's
properties. You can now right-click on the heading or background of any chart. Next,
select Expert Advisor and then Attach from the Chart shortcut menu. Attach the
market facilitation index expert, and it will highlight the four market facilitation
patterns that were discussed in Hartle's article. Note: You can save a chart as a
template with this expert attached, and then any time you apply the template to a
chart, the market facilitation index expert will automatically attach to the chart.
from Allan J. McNichol, EQUIS International
www.equis.com Sender: blackman@hawaii.rr.com

TRUE STRENGTH INDEX

Walter Lake wlake@sprint.ca


True Strength Index = TSI
TSI(close,r,s) = 100*EMA(EMA(mtm,r),s / EMA(EMA(ImtmI,r),s)
Numerator
mtm = one-day momentum of close
r-day EMA of mtm {25 day}
s-day EMA {13 day double smoothing}
Demoninator
ImtmI = absolute value of mtm
r-day EMA of ImtmI
s-day EMA {double smoothing}
TSI(close,25,13)
Signal Line = EMA(TSI,7)
thresholds at +25, 0, -25
-0-
5 day EMA of 20 day EMA of 1 day momentum {little lag Vs smoothing of price}
-0-
Ergodic Oscillator = Ergodic + Signal line {TSI version of Slow Stochastic}
Erodic(close,r) = TSI(close,r,5) {double smoothing is fixed at 5}
Signal Line(close,r) = EMA(TSI(close,r,5),5)
r = 20days
thresholds are +20, -20
interesting comparision chart between 20 Slow Stochastic and 20 Erodic {more head
room in oversold-bought areas}
another chart showing Ergodic Osc = TSI(close,32,5) with 5-day EMA signal line
0–

Trading Ergodics with the Trend - Rules


1. Enter or hold position only when slope of Erogodic Signal line has the
same direction as the trend
2. Stand aside when slope of Erogodic Signal Line is in the opposite
diretion of trend
3. Enter or exit position when Erogodic and its Signal Line cross
-0-
Slow TSI Trend = TSI(close,64,64) {? weekly looking chart - very little lag}

38
Thresholds set at +15 & -15
Trading Ergodics with Slow TSI Trend
1st window - Slow TSI Trend = TSI(close,64,64)
2nd window - Ergodic Osc = TSI(close,64,5)

{Fibonacci Trader-Dynamic Balance Point Step}

DPS:=(ValueWhen(1,FmlVar("FT-DBP","DBC"),
FmlVar("FT-DBP","DBC"))+
ValueWhen(5,FmlVar("FT-DBP","DBC"),
FmlVar("FT-DBP","DBC"))+
ValueWhen(10,FmlVar("FT-DBP","DBC"),
FmlVar("FT-DBP","DBC"))+
ValueWhen(15,FmlVar("FT-DBP","DBC"),
FmlVar("FT-DBP","DBC"))+
ValueWhen(20,FmlVar("FT-DBP","DBC"),
FmlVar("FT-DBP","DBC")))/5;
DPS;

{created by Adam Hefner 9-1-99}


EXAMPLE OF HOW TO CREATE A MACD Crossover SYSTEM TEST IN
MetaStock

Enter Long:
Mov(C,5,E) > Mov(C,13,E)
AND Mov(C,13,E) > Mov(C,40,E)

Close Long:
Cross(Mov(C,13,E),Mov(C,5,E))

Now you can play with these combinations on both the enter long and close long side.
For example,
keep the same Enter Long but change the Close Long to =

Cross(Mov(C,40,E) ,Mov(C,5,E) )

This will keep you in the trade longer. You may want to enter when the 5 crosses
above the 13 and not wait for the 40 OR, you may just want to use the 5 cross above
the 40 and forget about the 13.

(created by David Evans)

Trending Bandini
Mov(C,2,S)>
Mov(Mov(C,2,S),2,S) AND
Mov(Mov(C,2,S),2,S)>
Mov(Mov(Mov(C,2,S),2,S),2,S) AND
Mov(Mov(Mov(C,2,S),2,S),2,S)>

39
Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S) AND
Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S)>
Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S) AND
Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S)>
Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S) AND
Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S)>
Mov(Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S),2,S) AND
Mov(Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S),2,S)>
Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S),2,S),2,S)
AND
Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S),2,S),2,S)>
Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S),2,S),
2,S),2,S) AND
Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S),2,S),
2,S),2,S)>
Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(Mov(C,2,S),2,S),2,S),2,S),2,S),2,S),
2,S),2,S),2,S),2,S)

{created by Brookelise}

Elliot Oscillator

Mov((H+L)/2,5,S)-Mov((H+L)/2,34,S)
GRII
This is a long formula so I broke it up into four pieces. GRII is derived from formulas
1, 2, and 3.

This is a nifty momentum oscillator that I've used for about five years to help me
determine the direction of a given market when I have evidence that the market is
about to turn.

test
formula
1 GRIIF1 tsf(C,9)-ref(tsf(C,9),-1)

2 GRIIF2 (ref(tsf(C,9),-1)-(ref(tsf(C,9),-2)))

3 GRIIF3 (ref(tsf(C,9),-2)-(ref(tsf(C,9),-3)))

4 GRII (tsf(C,9)-ref(tsf(C,9),-1))+((ref(tsf(C,9),-1)-ref(tsf(C,9),-2)))+((ref(tsf (C,9),-


2)-(ref(tsf(C,9),-3))))

(written by Eddie Kwong)

SPECIAL TRIX

This is my own version of the well-known indicator, TRIX. I have had much better
results with this than the canned version that comes with every charting program.

40
trix(12)-ref((trix(12)),-1)

(created by Eddie Kwong)


{Fibonacci Trader - Fixed Balance Point}
{NOTE: under Color/Style options, change
plot to last "style" option}

{Fixed Balance Point Calculation}


FBC:=If(DayOfWeek()=1 AND Ref(DayOfWeek(),-1)
<5,
{then}(HighestSince(2,DayOfWeek()=1,H)+
LowestSince(1,DayOfWeek()=1,L)+
CLOSE)/3,
{else}If(DayOfWeek()=5,
{then}(HighestSince(1,DayOfWeek()=1,H)+
LowestSince(1,DayOfWeek()=1,L)+
CLOSE)/3,
{else}0));
{Fixed Balance Point Plot}
FBP:=ValueWhen(1,FBC>0,FBC);
FBP

{created by Adam Hefner}

GANN SWING HILOW ACTIVATOR

I was only able to implement Krausz's Gann Swing HiLow Activator in Metastock,
because it's simply the average of the last three bars High (stop for short position or
long entry) or Low (stop for long position or short entry) plotted one period forward:
Ref(Mov(L,3,S),-1) or Ref(Mov(H,3,S),-1)
(from Thorsten Buhmann in Germany)
Tema PV Binary Wave
Use of Tema PV Binary Wave and Tema QStick Formulas in MetaStock, from
"JimG"
There are really two different ways to use these formulas. Since the Binary Wave is a
smoothed addition of several technical indicators that each give +1 when bullish, 0
when neutral and -1 when negative, it makes sense that a positive number is bullish
and rising numbers are bullish. Similarly negative numbers and falling numbers are
bearish.
The QStick is really a candlestick type indicator, but can be read as bullish or bearish
in same way as the Binary Wave.
The two traditional ways to play them are to buy on a rise from a negative peak and
sell on a fall from a positive peak, or to buy on a zero cross over to the upside and sell
on a zero crossover to the downside. Of course you can optimize and find various buy
and sell levels as long as you understand what is bearish and what is bullish.

41
My own MetaStock system tests alerts on the BW crossing a moving average of itself
and buys or sells on a confirmation of Qstick turning positive or negative respectively.
Having said that, I don't make my buy an sell decisions from the indicators or the
system test. I do use the system test as an initial screen and use a buy signal as a flag
to move the stock to my watch list. I make all buying and selling decisions based on
the trend channels. Over the years, I've found that works best for me.

RUGGERIO'S TREND

Ruggiero's rules for trend mode quoting his table 4.9:

1. If ADX crosses above 25, then the market is trending.


2. If ADX crosses below 20, then the market is consolidating.
3. If ADX crosses below 45 from above, then the market is consolidating.
4. If ADX rises from below 10 on 3 out of 4 days, then the market will start
to trend.
5. If a trend is based on rule 4, it remains in effect until the 5 day
difference in ADX is less than 0.

Ruggiero employs a 14 day ADX but that is based on T-Bonds data. He suggests
employing the above rules as a filter. I make the indicator take the value +1 if
trending, a -1 if consolidating according to the above criteria but I guess the zero is
for the grey area
in between. Anyway according to definition: If a market is not trending it must be
consolidating. However the zero may contain additional useful information. Ruggiero
suggests tweaking the threshold values.

periods:=Input("Periods?",1,63,14);
If((ADX(periods)>25 AND (BarsSince(Cross(45,ADX(periods))) >
BarsSince(Cross(ADX(periods),25)))) OR (ADX(periods) > 10 AND
Ref(ADX(periods),-4)<10 AND (ADX(periods)-Ref(ADX(periods),-5)>0)), 1,
If(ADX(periods)<20 OR ((BarsSince(Cross(45,ADX(periods))) <
BarsSince(Cross(ADX(periods),25))) AND ADX(periods) < 45),-1,0))

AUTOMATIC METASTOCK TRENDLINE FORMULA

Trough(1,L,10)+
((((Trough(1,L,10)-Trough(2,L,10))
/
(TroughBars(2,L,10)-TroughBars(1,L,10)))
*TroughBars(1,L,10)))
This formula will draw a trendline from the most recent bottom.
The L (low) can be changed to C (close) and the 10 can be changed
to a different percent value.
You will also need to change the line style to the last one in the
drop down list.
Mike Helmacy

42
www.techanalysis.com
Those who know me have found out I vacillate between the VERY complicated and
the very simple. I have been following a few stocks (medium volatility, but good %%
moves both up and down over a 2-5 week time frame) and tracking them with about
15 templates on which most of the formulas that I have acquired reside. I wanted to
track those that did best and those that were not as effective. I also tracked those
formulas that were late in showing turns in momentum vs those that caught the turn
close on. In this regard, I was looking for finding stocks at intermediate term lows and
highs, NOT for indicators that identified stocks that had begun their run in any
direction and were destined to continue. As a result, I came up with a very simple
indicator that showed a HIGH degree of accuracy in "turn-calling", but it did NOT
give me indication of the strength or duration of the new move, only that it probably
would occur. I believe that I have finally discovered that any signal of a change in
momentum will NEVER give you a sense of strength or duration BY ITS VERY
NATURE, and that only signals that identify stocks WITHIN a momentum trend
(ie..already established) are able to do that. My momentum trend change indicator is
derived from an intermediate trend indicator I've used for some time in MSWIN 6.0...
PDI(34) - MDI(34)
My new formula is...........
((PDI(8) - MDI(8)) - (PDI(21) - MDI(21))) + (PDI(13) - MDI(13))
Try it......I think you'll like it......and it's the same coding in WOW, I believe..........BW
Chan
I have posted an update to the RMTA and TOSC formula's,
>the first formulas had an "Absolute Value" that wasn't called for
>in the article ( I had mistaken the "[" "]" to mean "|" "|"). The new
>formulas seem to plot exactly as the old......but I wanted the code
>to match the math in the article.
>Thanks go out to William Golson for the help.
>
>{Recursive Moving Trend Average}
>Lb:=Input("Look-Back Period?",3,100,21);
>Alpha:=2/(LB+1);
>Bot:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+C;
>RMTA:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+
> (Alpha*(C+Bot-Ref(Bot,-1)));
>RMTA;
>
>{TOSC}
>Lb:=Input("Look-Back Period?",3,100,21);
>Alpha:=2/(LB+1);
>Bot:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+C;
>RMTA:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+
> (Alpha*(C+Bot-Ref(Bot,-1)));
>TOSC:=RMTA-Mov(C,lb,E);
>TOSC;
> Best wishes,
> Adam Hefner.
e-mail: VonHef@itlnet.net

43
THE RECURSIVE MOVING TREND AVERAGE

Is the name of an article in the December issue of TASC, written by


>Dennis Meyers. In it he describes what he calls " The Recursive
>Moving Trend Average" . I wont go into all the article right now, but
>here is my translation of his math (for Metastock 6.5) :
>
> {Recursive Moving Trend Average}
>Lb:=Input("Look-Back Period?",3,100,21);
>Alpha:=2/(LB+1);
>Bot:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+C;
>RMTA:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+
> (Alpha*Abs(C+Bot-Ref(Bot,-1)));
>RMTA;
>
>He then explains how to make an oscillator by subtracting an
>Exponential MA form the Recursive MA...... again here is the code:
>
> {TOSC}
>Lb:=Input("Look-Back Period?",3,100,21);
>Alpha:=2/(LB+1);
>Bot:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+C;
>RMTA:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+
> (Alpha*Abs(C+Bot-Ref(Bot,-1)));
>TOSC:=RMTA-Mov(C,lb,E);
>TOSC;
>
>
>Here is the code for System Testing;
>
>Buy Long:
>
>Lb:=opt1;
>ent:=3;
>Alpha:=2/(LB+1);
>Bot:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+C;
>RMTA:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+
> (Alpha*Abs(C+Bot-Ref(Bot,-1)));
>TOSC:=RMTA-Mov(C,lb,E);
>Cross(tosc,(0-Abs(ent)))
>
>Sell short:
>
>Lb:=opt1;
>ent:=3;
>Alpha:=2/(LB+1);
>Bot:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+C;
>RMTA:=(1-Alpha)*(If(Cum(1)<Lb,C,PREV))+
> (Alpha*Abs(C+Bot-Ref(Bot,-1)));
>TOSC:=RMTA-Mov(C,lb,E);

44
>Cross((0+Abs(ent)),tosc1)
>
>Opt1 is the look- back periods, of 3 to 30, and
>Opt2 is the entry value of the oscillator, 0 to 5.
>
>Now, after all the hours spent on figuring out the
>code, I have discovered that the RMTA plots very
similar to the DEMA, oh well............
> Adam Hefner.
> e-mail: VonHef@itlnet.net

Market Pressure - Ultimate:

This is the basic calculation:


If toadies close is greater than yesterdays close and
toadies volume is greater than yesterdays volume, write down toadies volume * close,
otherwise,
If toadies close is less than yesterdays close and
toadies volume is less than yesterdays volume, write down todays volume as a
negative number * close, otherwise write down 0.

Then add up the past 7 days and * 4, add this to


the past 14 days total and * 2, add this to
the past 28 days total.
Plot this grand total in your chart for each new trading day.

Simple Interpretation:
Market Pressure - Ultimate can show divergences with the instrument it is plotted
against.
It may show signs of support and resistance when the indicator hits areas of
support/resistance on its own graph.
Comparing rates of change/moving averages of the indicator against that of the
instrument may reveal accumulation/distribution pressures.

Market Pressure - Ultimate:

Sum(If(C > Ref(C,-1)


AND V > Ref(V,-1),
V * C,
If(C < Ref(C,-1)
AND V < Ref(V,-1),
Neg(V) * C,0)),7) * 4 +

Sum(If(C > Ref(C,-1)


AND V > Ref(V,-1),
V * C,
If(C < Ref(C,-1)
AND V < Ref(V,-1),
Neg(V) * C,0)),14) * 2 +

45
Sum(If(C > Ref(C,-1)
AND V > Ref(V,-1),
V * C,
If(C < Ref(C,-1)
AND V < Ref(V,-1),
Neg(V) * C,0)),28)

Changing Ways Accumulation/Distribution:

This is the calculation for the first formula (Todays Change):


Todays close - yesterdays close

This is the main formula, incorporating the first calculation:


If todays change (1st formula) is greater than a 7 day exponential moving average of
todays change and todays close is greater than yesterdays close, write down todays
close + todays volume, otherwise,
If todays change is less than a 7 day exponential moving average of todays change
and todays close is less than yesterdays close, write down the negative value of todays
close + todays volume, otherwise write down 0.

Then add up all the days values and keep a cumulative running total for each new
trading day.

Simple Interpretation:
Changing Ways Accumulation/Distribution can show divergences against the
instrument.
When compared against volume activity, it can show what impact a day of high
turnover had on the share price for the coming periods. This is to say that if a day had
high volume and there was little movement in the indicator alongside this, then you
can suggest that all the volume for that day was absorbed into the price and there is
less likelihood of buying/selling pressure in that day taking hold in the market in
future trading days.

Metastock code for Changing Ways Accumulation/Distribution:

Cum(If(Fml( "Todays Change" ) > Mov(Fml( "Todays Change" ),7,E) AND C >
Ref(C,-1),
C + V,
If(Fml( "Todays Change" ) < Mov(Fml( "Todays Change" ),7,E) AND C < Ref(C,-1),
Neg(C + V) ,0)))

Where Fml( "Todays Change" ) = c - ref(c,-1)

Front Weighted 36 Day Moving Average:

This indicator requires 3 sub calculations and then the totalling of all 3 to get the final
indicator:

46
This is the basic calculation:
Take the closing prices of your instrument 34 days ago - 26 days ago (inclusive),
multiply each daily value by 0.01 and write each value down.
Then take the closing prices of your instrument 25 days ago - 18 days ago (inclusive),
multiply each daily value by 0.02 and write each value down.
Then take the closing prices of your instrument 25 days ago - 18 days ago (inclusive),
multiply each daily value by 0.02 and write each value down.
Then take the closing price of your instrument 17 days ago and multiply by 0.03 ad
write the value down.
Then take the closing price of your instrument 16 days ago - 8 days ago (inclusive),
multiply by 0.031 and write each value down.
Then take the closing price of your instrument 7 days ago - 6 days ago (inclusive),
multiply by 0.006 and write each value down.
Then take the closing price of your instrument 5 days ago - 1 day ago (inclusive),
multiply by 0.07 and write each value down.
Then take the closing price of your instrument today, multiply by 0.079 and write this
value down.

Finally, add up all the values that you wrote down and plot the value on the chart,
repeat this for every new trading day.

Simple Interpretation:
Front Weighted 36 Day Moving Average is similar to all other moving averages. The
interpretation is just as with all others, the trend is up when prices are above the
moving average and the trend is down when prices are below the moving averages.
This particular variation attempts to weight the data at the front more than that at the
back, with a sliding scale for each trading days value.

Metastock code for Front Weighted 36 Day Moving Average:

Fml( "1FrontWeighted36BarMA1" ) +
Fml( "2FrontWeighted36BarMA2" ) +
Fml( "3FrontWeighted36BarMA3" )

Where Fml( "1FrontWeighted36BarMA1" ) =


0.01 * Ref(P,-34) +
0.01 * Ref(P,-33) +
0.01 * Ref(P,-32) +
0.01 * Ref(P,-31) +
0.01 * Ref(P,-30) +
0.01 * Ref(P,-29) +
0.01 * Ref(P,-28) +
0.01 * Ref(P,-27) +
0.01 * Ref(P,-26) +
0.02 * Ref(P,-25) +
0.02 * Ref(P,-24) +
0.02 * Ref(P,-23) +
0.02 * Ref(P,-22) +

47
0.02 * Ref(P,-21) +

0.02 * Ref(P,-20) +
0.02 * Ref(P,-19) +
0.02 * Ref(P,-18)

Where Fml( "2FrontWeighted36BarMA2" ) =


0.03 * Ref(P,-17) +
0.031 * Ref(P,-16) +
0.031 * Ref(P,-15) +
0.031 * Ref(P,-14) +
0.031 * Ref(P,-13) +
0.031 * Ref(P,-12) +
0.031 * Ref(P,-11) +
0.031 * Ref(P,-10) +
0.031 * Ref(P,-9) +
0.031 * Ref(P,-8) +
0.006 * Ref(P,-7) +
0.006 * Ref(P,-6) +
0.07 * Ref(P,-5) +
0.07 * Ref(P,-4) +
0.07 * Ref(P,-3) +
0.07 * Ref(P,-2)

Where Fml( "3FrontWeighted36BarMA3" ) =


0.07 * Ref(P,-1) +
0.079 * P

Excel Confidence %

This is the calculation:

Take todays volume * 50 and find the square root of that number. Then divide 2.5 by
your result. Then take the result of dividing by 2.5 and * todays close. Write this
figure down.
Then plot a 10 day moving average of this figure. This is the fundamental calculation
which we shall call a.

Take the value for a and take it away from the lowest value of itself over the past 5
days. Add up these results for the past 3 days. This number is called b.

Now take the highest value for a over the past 5 days and subtract the lowest value for
a, also over the past 5 days. Call this number c.

Finally, divide b by c and multiply the answer by 100. (phew!)

Simple Interpretation:
Excel Confidence % should oscillate between 0 and 100, usually at the extreme ends
of the scale. A value of 0 indicates no confidence in the market going up, whilst 100

48
indicates perfect confidence in the market going up. Although this obviously isn't the
holy grail of indicators, it does offer some insight into what the market is thinking and
how one can measure investor sentiment.
You might like to add a slower version of this (just increase the 3 day and 5 day
calculations to something you believe to be appropriate - try 7 & 15) and trade the
crossovers, as with stochastics.
You can also just trade the values ie 90 or higher, buy, 10 or lower, sell.

Excel Confidence %:

(Sum( Mov(C * (2.5/ Sqrt(50 * V)),10,S)-


LLV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5), 3 ) /
Sum( HHV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5) -
LLV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5), 3) ) * 100

Lone Ranger

This is the calculation:

There are 2 calculations needed for this.


For the first, just take the highest value of the close in the past 3 days (including
todays close) and take this away from the lowest value of the cose in the past 3 days.
Call the result of this a.

Then divide a by volume. Subtract the result of this by the value of a divided by
volume 5 days ago.

Finally, multiply this number by -1.

Simple Interpretation:
This is a short term indicator which will show short term divergences against the
market instrument. You can also use it to compare its rate of change against that of
the market.
Extreme lows or highs in the indicator may be a signal of similar instances in the
market, however you would want to define a time period to make use of this function.

Metastock code for Lone Ranger:

(( Fml( "Z Range" ) / V) -


Ref((Fml( "Z Range" ) / V),-5)) * -1

Where Fml( "Z Range" ) = (HHV(c,3) - LLV(c,3))

THREE INSIDE DAYS


Inside days suggest a volatility compression and often preceede strong breakouts.
Search returns 1 for ok and 0 for not ok
Inside()
Inside()-1

49
Inside()-2

NR4 FORMULA

from page 100 Trading Tactics


Column A
Std(Log(C/Ref(C,-1)),5)/Std(Log(C/Ref(C,-1)),99)
Column B
HIGH-LOW<Ref(LLV(H-L,3),-1)
Column C
HIGH<(Ref(HIGH,-1)AND LOW>Ref(LOW,-1))
Column D
HIGH
Column E
LOW
Filter
colA<.5 AND (colB= 1 OR colC= 1)

PRICE AND VOLUME BREAKOUT


Shows stocks where the price increased 5% and the volume is 50% above a 50-day
moving average. Rank results by % change in price, then check the volume.
CLOSE
Ref(CLOSE,-1)
ROC(CLOSE,1,percent)
VOLUME
Mov(VOLUME,50,EXPONENTIAL)
((VOLUME - Mov(VOLUME,50,EXPONENTIAL))
/Mov(VOLUME,50,EXPONENTIAL)) * 100
**When(colC >= 5) AND When(colD >= colE*1.5)
BOTTOM REVERSAL
These are a collection of bottom signals. The search returns 1 for Ok and 0 for not ok.
CLOSE
EngulfingBull()
MorningDojiStar()
MorningStar()
WhiteSoldiers()
GAP DAYS
Shows stocks which have gapped up or down on the open compared to yesterdays
price. The search returns 1 for Ok and 0 for not ok.
GapUp()
HIGHER CLOSES
Shows stocks which have closed higher on successive days.
CLOSE
CLOSE -1
CLOSE -2
**When(colA,>,colB) AND When(colB,>,colC)
MOVING AVERAGE CROSSOVER - BULLISH

50
This is a10 and 30 day moving average crossover search. Results close to 0 pinpoint
the crossover.
CLOSE
Mov(CLOSE,30,EXPONENTIAL)
((CLOSE-Mov(CLOSE,30,EXPONENTIAL)) /Mov(CLOSE,30,EXPONENTIAL)) *
100
((CLOSE-Mov(CLOSE,10,EXPONENTIAL)) /Mov(CLOSE,10,EXPONENTIAL)) *
100
**When(colA > colB)
MACD CROSSOVER BUY SIGNAL
Shows those stocks where an MACD crossover has been signalled.The search returns
1 for Ok and 0 for not ok.
CLOSE
MACD()
Ref(MACD(),-1)
Mov(MACD(),9,EXPONENTIAL)
Ref(Mov(MACD(),9,EXPONENTIAL),-1)
((MACD() - Mov(MACD(),9,EXPONENTIAL))
/Mov(MACD(),9,EXPONENTIAL)) * 100
**Cross( MACD(), Mov(MACD(),9,EXPONENTIAL))
PERFORMANCE DAILY
Stocks sorted on % gains over 1, 2, 3, 4, and 5 days. Rank results for the selected day.
Good for finding breakout stocks.
CLOSE
ROC(CLOSE,1,percent)
ROC(CLOSE,2,percent)
ROC(CLOSE,3,percent)
ROC(CLOSE,4,percent)
ROC(CLOSE,5,percent)
RALLY GAP AND INSIDE DAY
Finds stocsk which have rallied, gapped upwards, and then had an inside day.
Usually leads to a resumption of the rally. The search returns 1 for Ok and 0 for not
ok.
RallyWithVol()
Inside()
GapUp()
RANGE HIGH
Looks for out of range move where the close equals the high. Suggests more buying
pressure.
The search returns 1 for Ok and 0 for not ok.
BigWhite()
CLOSE
HIGH VOLUME
Displays those where volume is above the 100 day moving average.
The search returns 1 for Ok and 0 for not ok.
VOLUME
Mov(VOLUME,100,EXPONENTIAL)
((VOLUME - Mov(VOLUME,100,EXPONENTIAL))
/Mov(VOLUME,100,EXPONENTIAL)) * 100
When(colA,>,colB)

51
THIS COLLECTION COMES FROM A SPANISH SOURCE.
They are contributed by Patrick who notes "my limited Spanish suggests that they are
simply a random collection made by the web owner, who points out that there is as
yet 'no
Holy Grail' in technical analysis! For the past few days I have been using them by
substituting the for
'number' given to each formula, the complete formula that particular number
represents. In this way, each becomes independent." We have included all 80 of them,
complete with
the orginal Spanish cover note.
A continuación se ofrecen una serie de fórmulas que puede utilizar con el programa
Metastock recogidas de la red y cuya utilidad Vd. debe valorar. Se ruega
encarecidamente a todos aquellos que tengan fórmulas que puedan resultar útiles las
envíen a jomaba@interbook.net para su publicación en esta página. Muchos dicen que
el Santo Grial no existe.¿Y si es mentira?

1 DAILY CLOSE VS HIGH AND LOW WAVE if((C-L)/(H-L),>,.66 ,1, if((C-L)/(H-


L),<,.38,-1,0))
2 PRICE OSCILLATOR WAVE if(ref(oscp(3,15,S,%),-1),<,0,1,0)
3 VOLUME OSCILLATOR WAVE if(oscv(1,50,S,%),>,50,1,0)
4 WEEKLY PRICE OSCILLATOR WAVE if(fml(#17),>,ref(fml(#17),-1),1,
if(fml(#17),<,ref(fml(#17),-1),-1,0))
5 VOLATILITY WAVE if(ref(fml(#27),-1),<,90,1,0)
6 LONG BINARY WAVE fml(#1) + fml(#2) + fml(#3) + fml(#9)
7 STOCHASTIC WAVE - LONG if(ref(stoch(14,3),-1),=,llv(stoch(14,3),3),2,
if(stoch(14,3),=,llv(stoch(14,3),3),1,0))
8 STOCHASTIC WAVE - SHORT if(ref(stoch(14,3),-1),=,hhv(stoch(14,3),3),2,
if(stoch(14,3),=,hhv(stoch(14,3),3),1,0))
9 VOLATILITY DIFFERENCE WAVE if(fml(#11),>=,1.00,1,0)
10 LONG BINARY II fml(#1) + fml(#3) + fml(#9) + fml(#24)
11 VOLATILITY DIFFERENCE mov(H-L,1,S)/mov(H-L,20,S)
12 HI LOW WAVE - DAILY if(H,>,ref(hhv(H,100),-1),1,if(L,<,ref(llv(L,100),-1),-
1,0))
13 WEEKLY HIGH LOW WAVE if(H,>,ref(hhv(H,40),-1),1, if(L,<,ref(llv(L,40),-1),
-1,0))
14 PERCENT ABOVE\BELOW MOVING AVG (oscp(1,30,E,%))
15 WEEKLY PRICE OSCILLATOR mov(oscp(10,20,S,%),10,S)
16 MACD WAVE MACD/trigger Binary Wave if(macd(), >, mov(macd(),9,E),
{bullish} +1, {bearish} -1)
17 WEEKLY OSC SEGMENT mov(oscp(43,86,S,%),43,S)
18 HISTORICAL VOLATILITY (std(log(C / ref(C,-1)),10)*sqr(365)) /(std(log(C /
ref(C,-1)),50)*sqr(365))
19 RELATIVE STRENGTH C/P
20 CLOSE REL TO HIGH LOW (C-L)/(H-L)
21 GAP IDENTIFICATION if(L,>,ref(H,-1),1, if(H,<,ref(L,-1),-1,0))
22 AVG VOLUME mov(V,50,S)
23 MOVE WAVE 20-unit m.a. Binary Wave if(C, >, mov(C,20,E), {then bullish} +1,
{else bearish} -1)
24 STOCHASTIC VALUE WAVE if(ref(stoch(14,3),-1),<,65,1,

52
if(stoch(14,3),<,65,1,0))
25 ROC WAVE 12-ROC price Binary Wave if(roc(C,12,%), >, 0, {then bullish} +1,
{else bearish} -1)
26 STOCH WAVE 5- Stochastic Binary Wave if(stoch(5,3), >, 50, {then bullish} +1,
{else bearish} -1)
27 ATR RATIO atr(10)/atr(50)/100
28 BINARY WAVE Composite Wave of above fml("MACD Wave") + fml("MOVE
Wave") + fml("ROC Wave")+ fml("STOCH Wave")
29 WEEKLY OPEN CLOSE WAVE if(C,>,O,1,if(C,<,O,-1,0))
30 SHORT BINARY WAVE fml(#31) + fml(#32) + fml(#33)
31 SHORT OPEN CLOSE WAVE if((C-L)/(H-L),<,.38,1,0)
32 SHORT PRICE OSCILLATOR WAVE if(ref(oscp(3,15,S,%),-1),>,0,1,0)
33 SHORT VOLUME WAVE if(oscv(1,50,S,%),>,0, if(V,>,ref(V,-1),1,0),0)
34 O.B.V. Good example of if() func cum( if( C, >, ref(C,-1), +V, if( C, <, ref(C,-1), -
V, 0) ))
35 SINE WAVE 5-unit standing sine wave sin( cum(5) )
36 STOCHASTIC Example of hhv() function ( sum( C - llv(L,5), 3 ) / sum( hhv(H,5)
- llv(L,5), 3) ) * 100
37 Median price (hhv(H,10)-C)-(C-llv(L,10))/(hhv(H,10)-llv(L,10))
38 Future MACD---Dr. Trieber (C-(( 11.607*(mov(C,26,E)))-
(10.607*(mov(C,12,E))) -(12.536*(mov(macd(),9,E)))))
39 Fraction (32nd's) int(C)+((frac(C)/0.03125)/100)
40 Summation Noise Indicator (Adam White) (sum(abs(C-ref(C,-1)),14)-
sum(abs(mov(C,10,S)-ref(mov(C,10,S),-1)),14))/
sum(abs(C-ref(C,-1)),14)
41 Chaikin Money Flow sum(((((C-L)-(H-C))/(H-L))*V),21)/sum(V,21)
42 Linear Regression ((15*(sum(cum(1)*C,10))-(sum(cum(1),10)*(sum(C,10))))
/((10*sum(pwr(cum(1),2 ),10))-pwr(sum(cum(1),2),10))
-pwr(sum(cum(1),10),2))
43 Smoothed Tick Momemtum Line-TASC mov(roc(cum(if(C,>,ref(mov(C,10,E),-
1),+1,
if(C,<,ref(mov(C,10,E),-1),-1,0))),5,$),5,E)
44 Bull Power (for Elderray) H-mov(C,13,E)
45 Bear Power (for Elderray) L-mov(C,13,E)
46 13-Period Moving Average (for Elderray) mov(C,13,E)
47 RSI Binary Wave (using 30/70 xover) if(rsi(10),>,30,if(ref(rsi(10),-
1),<,30,+1,if(rsi(10),<,70,if(ref(rsi(10),- 1),>,70,-1,0),0)),0)
48 Trendscore...Tushar Chande (TASC) if(C,>=,ref(C,-11),1,-1)+if(C,>=,ref(C,-
12),1,-1)+if(C,>=,ref(C,-13),1,-1)+
if(C,>=,ref(C,-14),1,-1)+if(C,>=,ref(C,-15),1,-1)+if(C,>=,ref(C,-16),1,-1)+
if(C,>=,ref(C,-17),1,-1)+if(C,>=,ref(C,-18),1,-1)+if(C,>=,ref(C,-19),1,-1)+
if(C,>=,ref(C,-20),1,-1)
49 KST-Martin Pring (One formula)
(mov(roc(C,10,%),10,S))+(2*(mov(roc(C,15,%),10,S)))+
(3*(mov(roc(C,20,%),10,S)))+(4*(mov(roc(C,30,%),15,S)))/10
50 Dual Oscillator B-Wave +1 buy, -1 sell if(fml("dual osc 1"),>,fml("dual osc
2"),if(ref(fml("dual osc 1"),-1),<,
ref(fml("dual osc 2"),-1),+1,if((fml("dual osc 1")),<,fml("dual osc 2"),
if(ref(fml("dual osc 1"),-1),>,ref(fml("dual osc 2"),-1),-1,0),0)),0)
51 Dual Osc 1 mov(C,2,S)-mov(C,10,S)

53
52 Dual Osc 2 mov((H+L+C)/3,5,S)-mov((H+L+C)/3,20,S)
53 R Squared pwr(corr(cum(1),C,5,0),2)
54 Slope of Linear Regression Line ((5*(sum(cum(1)*C,5)))-
(sum(cum(1),5)*(sum(C,5))))/
((5*sum(pwr(cum(1),2),5))-pwr(sum(cum(1),5),2))
55 RWI for today's high (H-ref(L,-16))/(mov((H-L),16,S)*sqr(16))
56 RWI for today's low (ref(H,-16)-L)/(mov((H-L),16,S)*sqr(16))
57 Momemtum roc(mov(C,10,E),10,%)
58 Volume Binary Wave if(V,>,ref(mov(V,20,E),1),1,if(V,<,ref(mov(V,10,E),1),-
1,0))
59 MACD w/SAR if(macd(),>,mov(macd(),9,E),{macd is above trigger}if(sar(.02,.2),
<,C,{buy long}+2,{stop shorts}+1),{macd < trigger}if(sar(.02,.2),>,
C,{sell short}-2, {stop longs}-1))
60 Oscillating OBV mov(obv(),20,E)-obv()
61 Overreaction Index if(ref(std(C,3),-3),>,4,+1,0)+if(C,<,(sar(.015,.15)),-1,+1)
62 Modified MACD tsf(C,12)-tsf(C,26)
63 RVI w/simple moving average (TASC) 100*mov(if(C,>,ref(C,-
1),std(C,10),0),14,S)/(mov(if(C,>,ref(C,-1),
std(C,10),0),14,S)+mov(if(C,<,ref(C,-1),std(C,10),0),14,S))
64 Upper Bollinger Band mov(C,20,S)+(2*(std(C,20)))
65 Lower Bollinger Band mov(C,20,S)-(2*(std(C,20)))
66 Middle Band mov(C,20,S)
67 %B (TASC) (C-(mov(C,20,S)-(2*(std(C,20)))))/(mov(C,20,S)+(2*(std(C,20)))-
mov(C,20,S)-(2*(std(C,20))))
68 Band Width (TASC) (mov(C,20,S)+(2*(std(C,20))))-(mov(C,20,S)-
(2*(std(C,20))))/mov(C,20,S)
69 Volume % above/below 10 day MA (V-mov(V,10,S))/mov(V,10,S)
70 # of STD's of volume (V-mov(V,20,S))/std(V,20)
71 Morris' RSI w/volume (TASC) 100-
(100/(1+(mov(if(roc(C,1,$),>,0,roc(C,1,$)*V,0),14,S)/
mov(if(roc(C,1,$), <,0,-roc(C,1,$)*V,0),14,S))))
72 Custom A/D Oscillator cum(if(C,>,ref(C,-2),1,if(C,<,ref(C,-2),-1,0)))
73 Empty Candlestick if(C,>,o{then empty},+1,0)
74 Filled Candlestick if(C,<,o{then filled},+1,0)
75 Doji if(C,=,o{then doji},+1,0)
76 Bearish engulfing lines if(fml(#28),=,+1,if(ref(fml(#27),-1),=,+1,if(C,<=,ref(O,-
1),if(O,>=,
ref(C,-1),-1,0),0),0),0)
77 Bullish engulfing lines if(fml(#27),=,+1,if(ref(fml(#28),-1),=,+1,if(C,>=,ref(O,-
1),if(O,<=,
ref(C,-1),+1,0),0),0),0)
78 Engulfing Line Binary wave fml(#30)+fml(#31)
79 Largest negative change in close llv(roc(C,1,$),40)
80 Choppiness Index (TASC) ((log(sum(atr(1),14)/(hhv(if(H,>=,ref(C,-1),H,ref(C,-
1)),14)-llv(if(L,<=,
ref(C,-1),L,ref(C,-1)),14)))/log(10))/(log(14)/log(10)))*100

Better Bollinger Bands

54
In the Oct issue of "Futures" there is an article written by
>Dennis McNicholl called "Better Bollinger Bands". In his
>article he describes how in a trending market the center
>band of the B.B. will shift away from the "mean" value of
>the price, and that the two outer bands will shift outward
>to such an extent that the envelope loses its utility as a
>volatility gauge (these are his words... not mine).
> As usual "Futures" only posted the TradeStation code,
>so this is my conversion from it. He called the Indicator
>"Denvelope", and it runs the bands much closer.....
>similar to "Standard Error Bands".
>
> {Denvelope}
> {Better Bollinger Bands}
>Lb:=Input("Look-Back Period ?",3,100,20);
>De:=Input("Band Deviation ?",.5,3,2);
>Alp:=2/(Lb+1);
>Mt:=Alp*CLOSE+(1-Alp)*PREV;
>Ut:=Alp*Mt+(1-Alp)*PREV;
>Dt:=((2-Alp)*Mt-Ut)/(1-Alp);
>mt2:=Alp*Abs(C-Dt)+(1-Alp)*PREV;
>ut2:=Alp*mt2+(1-alp)*PREV;
>dt2:=((2-Alp)*mt2-ut2)/(1-Alp);
>But:=Dt+de*dt2;
>Blt:=Dt-de*dt2;
>But;
>Dt;
>Blt;

> Best wishes,


> Adam Hefner.
> e-mail: VonHef@itlnet.net

Adaptive Moving Average by Perry Kauffman


This is a Metastock for Windows version 6.5 formula.
Periods := Input("Time Periods",1,1000, 10);
Direction := CLOSE - Ref(Close,-periods);
Volatility := Sum(Abs(ROC(CLOSE,1,$)),periods);
ER := Abs(Direction/Volatility);
FastSC := 2/(2 + 1);
SlowSC := 2/(30 + 1);
SSC := ER * (FastSC - SlowSC) + SlowSC;
Constant := Pwr(SSC,2);
AMA := If(Cum(1) = periods +1, ref(Close,-1) + constant * (CLOSE - ref(Close,-
1)),Prev + constant * (CLOSE - PREV));
AMA

"Average-Modified Method"
From The New Commodity Trading Systems and Methods, by Perry J. Kaufman

55
Chapter 4 - Moving Averages, pg. 60.
This formula is for version 6.5 of MetaStock for Windows 95 & NT only and cannot
be written in previous version.
This is a modified simple moving average.
The formula will prompt you for input for the number of time periods to use in the
moving average.
Day:=Cum(1)+1;
Z:=Input("Periods",2,1000,5);
MV:=(1/Z);
If(Day<(Z+2),C,If(day=(Z+2),Mov(C,LastValue(Z),S),PREV+(MV*(C-PREV))))

The Investor Preference Index


This indicator was discussed in the December 1997 Technical Analysis of Stocks &
Commodities magazine, page 19. The article was written by Cyril V. Smith Jr.
"This indicator, a long - term stock market investment tool, compares the performance
of the S&P 500 to the New York Stock Exchange index to measure sentiment. The
theory is that investors have a preference for certain types of investments, blue chips
versus mid-cap, during phases of a bull market."
To plot this in MetaStock for Windows, follow these instructions. When complete, if
you save this as a chart, you will simply need to load the chart and it will recalculate
using the newest data.
Open a chart of the S&P 500.
Open a chart of the New York Stock Exchange index.
Drag the S&P 500 price plot into the NYSE chart.
Drop the indicator listed below on the plot of the S&P 500. The plot will turn a
different color when you are pointing at it.
The resultant plot is the Investor Preference Index.
Formula: Investor Preference Index:
(Sum(Mov(ROC(Log(C),24,%)-ROC(Log(P),24,%),15,S)-Mov(ROC(Log(C),24,%)-
ROC(Log(P),24,%),38,S),54)+1)*100
System test:
Enter Long
C=HHV(C,26)
Close Long
Fml("Investor Preference Index")<97.6 AND ROC(Fml("Investor Preference
Index"),2,$)<=(-.04)

Slope of a Linear Regression Line


rev. 01/06/97
The following custom formula will return the slope of a Linear Regression Line.
tp:=Input("Time Periods",1,200,21);
((tp*(Sum(Cum(1)*C,tp)))-
(Sum(Cum(1),tp)*(Sum(C,tp))))/((tp*Sum(Pwr(Cum(1),2),tp))-
Pwr(Sum(Cum(1),tp),2))

WillSpread by Larry Williams

The Larry Wiliams' indicator named WillSpread is quite easy to plot in MetaStock for
Windows version 6.5.
Using version 6.5 of MetaStock for Windows, please follow these steps.

56
Plot the underlying commodity.
Drag the Spread Indicator from the indicator quick list to this commodity chart.
Select either Tbonds or Tbills as the security to use to spread. I recommend you plot
this in a new inner window.
Drag the Price Oscillator from the indicator quick list and drop it on the SPREAD
plot, not the price plot. The parameters Mr. Williams' uses are 7 and 11 time period
exponential moving averages. You also want to use "points" as the method. This plot
is the WillSpread indicator.
At this point, you may change the Spread Indicator plot's color to match the
background of the chart, or perhaps move the WillSpread indicator to a separate inner
window.
If you save this first effort as a template, perhaps named WillSpread, you are able to
apply this template to any commodity you wish and the indicator will be
automatically calculated against that commodity.
You may also use the "Next Security" function within MetaStock for Windows to
view each of your commodities by setting the options for next security to "Keep line
studies". If you apply this template to the first commodity in your futures folder, you
may then use the right arrow to move down the folder contents. Each new commodity
will have the WillSpread calculated as it is loaded.

1996 August TASC Trader's Tips - Connors and Raschke's Historical Volatility
System

Here is the Connors and Raschke's historical volatility system exploration in August
1996 TASC Trader's Tips translated for MetaStock.
COLUMN FORMULAS
---------------
Column A : Vol ratio
std(log(C/ref(C,-1)),5)/std(log(C/ref(C,-1)),99)
Column B : NR4 day
if(HIGH-LOW,<,ref(llv(H-L,3),-1),1,0)
Column C : Inside
if(HIGH,<,ref(HIGH,-1),if(LOW,>,ref(LOW,-1),1,0),0)
Column D : High
HIGH
Column E : Low
LOW
FILTER FORMULA
--------------
Formula:
when(colA,<,0.5) AND (when(colB,=,1) OR when(colC,=,1))

1997 October TASC Traders Tip - Volatility Bands As A Long Term Strategy
This article "Volatility Bands As A Long Term Strategy", by Ahmet Tezel, Ph.D., and
Suzan Koknar-Tezel, M.S., which appears in this issue introduces two different
volatility band trading systems. One system uses bands based on moving averages and
the other is based on bands which use regression. To plot the Moving Average
Asymmetric Volatility Price Bands in MetaStock for Windows, simply plot Bollinger
Bands using 11 periods and 1.7 standard deviations. Then click your right-mouse

57
button while the cursor is over the lower band and choose properties. Change the
standard deviations to 2. This plot will now appear exactly as the bands discussed in
the article.
To plot the Regression Asymmetric Volatility Price Bands in Metastock for Windows,
simply plot Standard Error Bands using 21 periods, 1 for standard errors, and 1 for the
smoothing periods. Then click your right-mouse button while the cursor is over the
lower band and choose properties. Change the standard errors to 1.5.
To recreate the systems in MetaStock for Windows, choose System Tester from the
Tools menu. Next choose New and enter the following trading rules and stop
conditions. After entering this information, choose Options and change the trade delay
to 1, then change the Trade Price to Open. If you have MetaStock 6.5 enter the first
set of formulas. MetaStock 6.5 allows variables which will allow you to change the
periods when testing much more easily.
Formulas for MetaStock 6.5

MOVAVG ASYMMETRIC VOLATILITY PRICE BANDS

SIGNAL FORMULAS
---------------
Enter Long:
Periods := 11;
UpperBand := BBandTop(CLOSE,Periods,S,1.7);
BuySignal1 := Sum(CLOSE > UpperBand,3) = 3;
BuySignal2 := CLOSE > UpperBand AND Ref(LOW,-1) > Ref(upperband,-1);
BuySignal3 := LOW > UpperBand AND Ref(CLOSE,-1) > Ref(upperband,-1);
BuySignal4 := CLOSE > UpperBand AND CLOSE > 1.4 * LLV(LOW,Periods + 1)
AND Mov(VOLUME,3,S) > 2000 {assuming volume in 100's otherwise use 200000}
AND Mov(HIGH,3,S) > UpperBand AND Mov(HIGH - LOW,3,S) > Mov(HIGH -
LOW,Periods,S);
BuySignal1 OR BuySignal2 OR BuySignal3 OR BuySignal4
Close Long:
Periods := 11;
LowerBand := BBandBot(CLOSE,Periods,S,2);
SellSignal1 := Sum(CLOSE < LowerBand,3) = 3;
SellSignal2 := CLOSE < (1-.18) * HHV(HIGH,Periods + 1) AND Sum(CLOSE <
LowerBand,2) = 2;
SellSignal3 := CLOSE < (1-.18) * HHV(HIGH,Periods + 1) AND HIGH <
LowerBand;
SellSignal1 OR SellSignal2 OR SellSignal3
STOPS
-----
Maximum Loss: LONG ONLY
10.00 Percent

REGRESSION ASYMMETRIC VOLATILE PRICE BAND

SIGNAL FORMULAS
---------------

58
Enter Long:
Periods := 21;
UpperBand := STEBandTop(CLOSE,Periods,1) ;
Sum(CLOSE > UpperBand,3) = 3 AND LinRegSlope(CLOSE,21) > 0 AND
ROC(Correl(CLOSE,Cum(1) ,21,0),2,$) >= .2
Close Long:
Periods := 21;
LowerBand := STEBandBot(CLOSE,Periods,1.5) ;
SellSignal1 := Sum(CLOSE < LowerBand,3) = 3;
SellSignal2 := CLOSE < (1-.18) * HHV(HIGH,Periods + 1) AND HIGH <
LowerBand;
SellSignal1 OR SellSignal2
STOPS
-----
Maximum Loss: LONG ONLY
10.00 Percent

1997 November TASC Traders Tip - Using Fibonacci Ratios and Momentum
In MetaStock for Windows, you can establish Fibonacci Retracement levels as
outlined in the November 1997 TASC article "Using Fibonacci Ratios and
Momentum" by Thom Hartle by first creating an Expert in the Expert Advisor. To do
this, choose Expert Advisor from the Tools menu and then choose New. Enter the
following Expert Highlights and Expert Symbols into your Expert.
Fibonacci Ratios and Momentum
Highlights
Name: RSI > 50
Condition: RSI(14) > 50
Color: Dk Green
Name: RSI < 50
Condition: RSI(14) < 50
Color: Red
Symbols
Name: Isolated Low
Condition: LOW < Ref(LOW,-1) AND
LOW < Ref(LOW,1)
Graphic: Buy Arrow
Color: Black
Label: Isolated Low
Name: Isolated High
Condition: HIGH > Ref(HIGH,-1) AND
HIGH > Ref(HIGH,1)
Graphic: Sell Arrow
Color: Black
Label: Isolated High
Note: If the Symbol labels make the chart too busy you may want to shorten the label
(e.g. change Isolated High to IH).
Next, close the Expert Advisor, open any chart, and then click the right-mouse button
on the chart’s heading. Choose Expert Advisor and then Attach from the Chart
Shortcut Menu. You can now choose Fibonacci Retracement from the Insert menu,
and then drag from one isolated extreme to another. In MetaStock 6.5 you should

59
right-click on the Fibonacci Retracement lines and choose properties. Check the Snap
to Price checkbox so the Retracement lines will automatically snap to the high and
low prices.
1997 December TASC Trader's Tip - Volatility % Indicator
You can easily create the Volatility% Indicator from William Brower’s article in
MetaStock for Windows. First choose Indicator Builder from the Tools menu in
MetaStock. Next choose New and enter one of the following formulas:
Formula for MetaStock 6.5
Volatility%
Lookback := Input("Time Periods",1,1000,50);
HighVolatility := Input("High Volatility %",.01,100,3);
100 * Sum(100 * ATR(1)/CLOSE > HighVolatility, Lookback)/Lookback
Formula for earlier versions of MetaStock for Windows
Volatility%
100 * Sum(100 * ATR(1)/CLOSE > 3, 50)/50
Now drag the Volatility% from the Indicator QuickList and drop it on the desired
chart.

1998 February TASC - Double Tops and Double Bottoms


In the February 1998 issue of Technical Analysis of Stocks & Commodities
magazine, Thomas Bulkowski discusses the use of Double Bottoms as a means of
finding profitable trades.
In MetaStock for Windows, you can find both Double Tops and Double Bottoms with
these formulas. There is a caveat however. In the article, Mr. Bulkowski utilizes the
High-Low range in finding Double Bottoms. These formulas use only the close value,
so a few of the lower priced issues will not produce signals in MetaStock. Overall,
however, these formulas produce most of the major signals he discusses.
Double Tops
PK:=Zig(C,10,%)<Ref(Zig(C,10,%),-1) AND Ref(Zig(C,10,%),-
1)>Ref(Zig(C,10,%),-2);
TR:=Zig(C,10,%)>Ref(Zig(C,10,%),-1) AND Ref(Zig(C,10,%),-
1)<Ref(Zig(C,10,%),-2);
PK1:=PeakBars(1,C,10);
PK2:=PeakBars(2,C,10);
(ValueWhen(1,PK,Ref(C,-1))/ValueWhen(2,PK,Ref(C,-1))>.96 AND
ValueWhen(1,PK,Ref(C,-1)) / ValueWhen(2,PK,Ref(C,-1))<1.04) AND PK2-
PK1>=10 AND Cross(ValueWhen(1,TR,Ref(C,-1)),C)
Double Bottoms
PK:=Zig(C,10,%)<Ref(Zig(C,10,%),-1) AND Ref(Zig(C,10,%),-
1)>Ref(Zig(C,10,%),-2);
TR:=Zig(C,10,%)>Ref(Zig(C,10,%),-1) AND Ref(Zig(C,10,%),-
1)<Ref(Zig(C,10,%),-2);
TR1:=TroughBars(1,C,10);
TR2:=TroughBars(2,C,10);
(ValueWhen(1,TR,Ref(C,-1))/ValueWhen(2,TR,Ref(C,-1))>.96 AND
ValueWhen(1,TR,Ref(C,-1)) / ValueWhen(2,TR,Ref(C,-1))<1.04) AND TR2-
TR1>=10 AND Cross(C,ValueWhen(1,PK,Ref(C,-1)))

1998 May TASC Trader's Tip - Automatic Support and Resistance

60
Copied from Technical Analysis of Stocks and Commodities Magazine. This is in
regards to an article on page 51 of the May 1998 issue.
In my article "Automatic support and resistance" in this issue, I present a
computerized approach to finding support and resistance levels on a chart. To recreate
the indicators and system described in my article using MetaStock for Windows, enter
the following formulas:
Indicators:
S1: IF(Ref(LOW,-4)=LLV(LOW,9),Ref(LOW,-4),PREVIOUS)
S2: IF(Fml("S1")=Ref(Fml("S1"),-1),PREVIOUS,Ref(Fml("S1"),-1))
S3: IF(Fml("S1")=Ref(Fml("S1"),-1),PREVIOUS,Ref(Fml("S2"),-1))
S4: IF(Fml("S1")=Ref(Fml("S1"),-1),PREVIOUS,Ref(Fml("S3"),-1))
S5: IF(Fml("S1")=Ref(Fml("S1"),-1),PREVIOUS,Ref(Fml("S4"),-1))
S6: IF(Fml("S1")=Ref(Fml("S1"),-1),PREVIOUS,Ref(Fml("S5"),-1))
WSO:
100*(1-(Int(Fml("S1")/CLOSE)+Int(Fml("S2")/CLOSE)+Int(Fml("S3")/CLOSE)+Int
(Fml("S4")/CLOSE) +Int(Fml("S5")/CLOSE)+Int(Fml("S6")/CLOSE))/6)
R1: IF(Ref(HIGH,-4)=HHV(HIGH,9),Ref(HIGH,-4),PREVIOUS)
R2: IF(Fml("R1")=Ref(Fml("R1"),-1),PREVIOUS,Ref(Fml("R1"),-1))
R3: IF(Fml("R1")=Ref(Fml("R1"),-1),PREVIOUS,Ref(Fml("R2"),-1))
R4: IF(Fml("R1")=Ref(Fml("R1"),-1),PREVIOUS,Ref(Fml("R3"),-1))
R5: IF(Fml("R1")=Ref(Fml("R1"),-1),PREVIOUS,Ref(Fml("R4"),-1))
R6: IF(Fml("R1")=Ref(Fml("R1"),-1),PREVIOUS,Ref(Fml("R5"),-1))
WRO: 100*(1-(Int(Fml("R1")/CLOSE)+Int(Fml("R2")/CLOSE)
+Int(Fml("R3")/CLOSE)+Int(Fml("R4")/CLOSE)
+Int(Fml("R5")/CLOSE)+Int(Fml("R6")/CLOSE))/6)
The indicators S1 through S6 and R1 through R6 should be plotted as points and not
as a continuous line.
Trading System Formulas and Parameters: Enter long positions on either building
support or sustained uptrend and exit position using stops. No short positions.
Enter Long: Fml("WSO") > Mov( Fml("WSO") , 4 , S ) OR Mov( Fml("WRO") , 30
, S ) > 95
Stop Out:
Breakeven stop: Floor level at 2%
Trailing stop: Profit risk of 10 Percent, ignoring 10 periods
Maximum loss stop: Maximum loss of 7%
Other Conditions:
Initial equity = 1000, Long positions only, Trade price = close, Trade delay = 0, Entry
commission = 0%, Exit commission = 0%, , Interest rate = 5%, Margin req. 100%
-- Mel Widner, Ph.D., 703 791-5910
E-mail techstrategies@msn.com.
1998 June TASC Traders' Tip - Mutated Variables, Volatility and a New Market
Paradigm
Mutated Variables, Volatility and a New Market Paradigm by Walter T. Downs,
Ph.D.
In MetaStock for Windows 6.0 or higher, use the Expert Advisor to create highlights,
which will show when contraction and expansion phases are present. First, choose
Expert Advisor from the tools menu in MetaStock. Create a new Expert with the
following highlights:
Expert name: New Market Paradigm
HIGHLIGHTS

61
Name: Contraction
Condition: BBandTop(CLOSE,28,SIMPLE,2)<
Ref(BBandTop(CLOSE,28,SIMPLE,2),-1) AND
BBandBot(CLOSE,28,SIMPLE,2)>Ref(BBandBot(CLOSE,28,SIMPLE,2),-1)
Color: Blue
Name: Expansion
Condition: BBandTop(CLOSE,28,SIMPLE,2)>
Ref(BBandTop(CLOSE,28,SIMPLE,2),-1) AND
BBandBot(CLOSE,28,SIMPLE,2)<Ref(BBandBot(CLOSE,28,SIMPLE,2),-1)
Color: Red
Click OK to save the changes to the Expert. Open a chart and then click your right-
mouse button while pointing at the chart heading. Choose Expert Advisor and then
choose Attach from the chart shortcut menu. Choose the New Market Paradigm
Expert and then click the OK button. The price bars in the chart will be highlighted
blue during a contraction phase and red in an expansion phase.

1998 July Trader's Tip - Channel Analysis


Channel Analysis, beginning on page 18 of the July 1998 Technical Analysis of
Stocks & Commodities Magazine It's quite easy to create the Trend Channels
discussed in Thom Hartle's Channel Analysis article in MetaStock for Windows.
After opening a chart, you may want to zoom in a little to make it easier to draw the
Trend Channels more precisely. You can do this by clicking on the "+" button located
on the Chart Toolbar at the bottom of the chart. Next you may want to identify the
bars for the support or resistant points by drawing circles on the bars as Mr. Hartle did
in the article, or you can use symbols from the symbol pallete. Both can be chosen
from the Drawing Toolbar which is on left side of the chart. After identifying the
points to draw the trendline, click on the Trendline button, also located on the
Drawing Toolbar, and draw the trendline between the closing prices of the two bars. If
you are using MetaStock 6.5, you may want to right-click on the trendline, choose
properties, and then check the Snap to Price checkbox. This will make the trendline
line up exactly with the closing prices. To create the second trendline of the Trend
Channel, right-click on the first trendline and choose Create Parallel Line. Drag this
parallel line so it aligns with the highest high between the two support points or the
lowest low between two resistance points. If desired, you can go to the properties of
each of these trendlines and choose to extend the lines to the right. Top

LONE RANGER

This is the calculation:

There are 2 calculations needed for this.


For the first, just take the highest value of the close in the past 3 days (including
today's close) and take this away from the lowest value of the cose in the past 3 days.
Call the result of this a.

Then divide a by volume. Subtract the result of this by the value of a divided by
volume 5 days ago.

Finally, multiply this number by -1.

62
Simple Interpretation:
This is a short term indicator which will show short term divergences against the
market instrument. You can also use it to compare its rate of change against that of
the market.
Extreme lows or highs in the indicator may be a signal of similar instances in the
market, however you would want to define a time period to make use of this function.

Metastock code for Lone Ranger:

(( Fml( "Z Range" ) / V) -


Ref((Fml( "Z Range" ) / V),-5)) * -1

Where Fml( "Z Range" ) = (HHV(c,3) - LLV(c,3))

FORECAST OSCILLATOR

Many moons ago, I posted a little linear regression system that featured
the Forecast Oscillator. The response was surprising (lots of it) and
today, I still communicate with many of the original respondents. I've
continued to use the same "framework" for my testing. In an earlier post
today (a private email that made it to the list...I'm a little dingy
tonight...had to get up a 5 am to trade cocoa), I alluded to using the CMO.
I've used many indicators in these tests (i.e., Forecast Oscillator, a
modified Time Series Forecast, MACD Histogram, Bollinger Band Histogram,
CMO, & others).

Before I explain the method to my madness, please read the following


sentences carefully. Backtesting systems is very dangerous. The act of
backtesting is not the dangerous part...believing that the results can be
duplicated in the future is very dangerous. Let's face it, we are "best
fitting" circumstances to static prices etched in stone. So please, I'd
prefer not to hear the lectures about the folly I pursue. I've been system
testing since 1975 and I've made a bazillion mistakes (and a little chump
change) over the years. I'm still looking for the holy grail. So, here's
the outline:

1. The basic formula:

Enter Long:
Cross(opt1,ForecastOsc(CLOSE,opt3))

Close Long:
Cross(ForecastOsc(CLOSE,opt3),opt2)

Enter Short:
Cross(ForecastOsc(CLOSE,opt3),opt2)

Close Short:
Cross(opt1,ForecastOsc(CLOSE,opt3))

63
You can substitute any standard formula for the ForecastOsc or you can put
in a custom formula (just remember that custom formulae need to look like:
fml("Karnack's SuperSecret") It's in your manual.

2. opt3:

In this search "opt3" represents the number of days inserted into the
forecast oscillator. I usually use three (3) to ten (10) for the forecast
oscillator, but if I'm using a custom formula, sometimes I don't even need
opt3, because I using a fixed set of parameters within the custom formula.

3. opt1:

Opt1 is the numeric value below a zero basis line that will trigger a long
position and close out the short. Yes Virginia, in my secular little
world, I prefer stop and reverse trading. The parameters for this option
depends on the commodity (and yes, it does work on stocks) you're trading.
One must eyeball the forecast oscillator to see how far it swings above and
below zero. For the forecast oscillator, I usually use 0 to -3.

4. opt2:

Opt2 is the numeric value above a zero basis line that will trigger a short
sale. Zero to 3 seems to work for this formula.

5. Steps:

I step opt3 using whole numbers to represent days. With Opt1 and Opt2, I
use: .1 steps.

6. Other indicators:

When substituting the CMO (or any indicator) for the Forecast Oscillator,
one must be aware of the terrain the indicator travels over. It would be
ridiculous to us zero to 3 (as the optimizing numbers) if the mid point is
50 and the indicator traverses between +10 (on the downside) and +90 (on
the upside).

The overall theory behind this test is that many indicator oscillate from
positive to negative and back again (duh). The trick is not to trigger
action when the indicator turns in a new direction (if you're interested,
I've been down that road and I'm still wearing a neck brace from the
whiplash). The theory is that once an indicator extends to a certain
level, the market is either overbought or oversold.

In downtrending markets (can you spell deflation?), the short sale trigger
(opt2) is going to be closer to the zero basis line than opt1. Please see
the attachment. What will happen when the grains, cocoa, crude, and damn

64
near everything else starts to go up? Good question Steve! The system

will not perform as well if you continue to use the same parameters. In a
perfectly sideways market, one would assume that the trigger points would
be equal distance from zero. As in many markets, this system works better
when things trend indefinitely.

I hope this post will help others who have inquired about the linear
regression system. Attached is the original system, using the Forecast
Oscillator, for March Crude Oil. In this example, opt3 is set to 8 (number
of days in the forecast oscillator); opt2 is .1 (sell signal); opt1 is -2.3
(buy signal).

To quote R.N. Elliot: "Even though we many not understand the cause
underlying a particular phenomenon, we can, by observation, predict the
phenomenon's recurrence."

To qoute Karnack (my alter ego): "I got knocked down seven times and got
up eight".

Finally, from a trader on the realtraders forum: "Futures trading involves


financial risk, lots of it".

Sweet dreams,

Steve Karnish
CCT
Alligator Indicators
Following are the Bill William's Alligator indicators I put together.
Please read his book "Trading Chaos" and pick up a demo of his
"Investor's Dream" software from his web site to see how they are used.

Hope you find them useful.

originally from Gary Randall -- Brunswick, Maine, U.S.A.


----------------------------------------------

Chaos Blue BL
{Alligator Blue Balance Line - Jaw }
{13 bar smoothed average offset 8 bars }

Ref(Wilders(MP(),13),-8);

----------------------------------------------

Chaos Red BL
{Alligator Red Balance Line - Teeth }
{8 bar smoothed average offset 5 bars }

Ref(Wilders(MP(),8),-5);

65
----------------------------------------------

Chaos Green BL
{Alligator Green Balance Line - Lip }
{5 bar smoothed average offset 3 bars }

Ref(Wilders(MP(),5),-3);

----------------------------------------------

Chaos Gator
{ Chaos Alligator }
{ Plot as histogram }

green := Fml("Chaos Green");


red := Fml("Chaos Red");
blue := Fml("Chaos Blue");

If(green > red AND red > blue, green - blue,


If(blue > red AND red > green, green - blue,
0));

----------------------------------------------

Chaos AO
{ Chaos Awsome Oscillator - measures momentum }
( A very close approximation of MFI }
{ Plot as histogram }

Mov(MP(),5,S) - Mov(MP(),34,S);

----------------------------------------------

Chaos AO Signal Line


{ Chaos Awsome Oscillator Signal Line }
{ Plot as line over AO histogram }

Mov(Mov(MP(),5,S) - Mov(MP(),34,S),5,S)

----------------------------------------------

Chaos AC
{ Chaos Accelerator/Decelerator Oscillator }
{ Measures acceleration }
{ Plot as histogram }

Fml("Chaos AO") - Mov(Fml("Chaos AO"),5,S);

66
----------------------------------------------

Chaos Fractal
{ Chaos Fractal (simple version +1=Up, -1=Dn) }

High1 := Ref(HIGH,-2);
High2 := Ref(HIGH,-1);
High3 := Ref(HIGH,0);
High4 := Ref(HIGH,1);
High5 := Ref(HIGH,2);
Low1 := Ref(LOW,-2);
Low2 := Ref(LOW,-1);
Low3 := Ref(LOW,0);
Low4 := Ref(LOW,1);
Low5 := Ref(LOW,2);
Fractal :=
If((High3 > High1) AND (High3 > High2) AND (High3 > High4) AND (High3 >
High5), +1,0);

Fractal :=
If((Low3 < Low1) AND (Low3 < Low2) AND
(Low3 < Low4) AND (Low3 < Low5),
If(Fractal > 0, 0, -1), Fractal);

Fractal;
Final Plot
{from Richard Estes}
Fml ( "Final Plot" ) =

If (BarsSince ( Fml ( "Downtrend" )) < BarsSince ( Fml ( "Uptrend" )),


{ then } Ref ( HHV (H,4), -1 ), { else } Ref (LLV (L,4) ,-1 ))

where........

Fml ( "Downtrend" ) =

Peak(1, If (L<Ref(LLV(L,4),-1) , Ref(HHV(H,4),-1), 0), 1) <>


Ref(Peak(1, If (L<Ref(LLV(L,4),-1) , Ref(HHV(H,4), -1), 0), 1)

and......

Fml ( "Uptrend" ) =

Peak(1, If (H>Ref(HHV(H,4),-1), Ref(LLV(L,4), -1), 0), 1) <>


Ref(Peak(1, If (H>Ref(HHV(H,4),-1), Ref(LLV(L,4), -1), 0), 1)

Binary Wave System Test for MetaStock

67
{created by Jim Greening}

The basic idea behind a MetaStock binary wave is to use "if" statements on several
MetaStock indicators and have them return plus one for a bullish indication, minus
one for a bearish indication, and zero for a neutral condition. Then you add them all
up for your binary wave indicator. I decided to format all my indicators so they could
be plotted as a histogram. For these indicators plotting as histograms, positive is
bullish and negative is bearish. To cut down on whipsaws, I decided that over +5
would be bullish, under -13 would be bearish and anything in between would be
neutral. Therefore my binary wave formulas are:
BW2 Demand Index
If(Tema(DI(),21) > 5,+1,If(Tema(DI(),21) < -13,-1,0))
BW3 Linear Regression Slope
If(Tema(10000*LinRegSlope(C,34)/C,34) > 5,+1,
If(Tema(10000*LinRegSlope(C,34)/C,34) < -13,-1,0))
BW4 CCI
If(Tema(CCI(21),21) > 5,+1, If(Tema(CCI(21),21) < -13,-
1,0))
BW5 ROC
If(Tema(ROC(C,21,%),21) > 2,+1,If(Tema(ROC(C,21,%),21) <
-2,-1,0))
BW6 Money Flow
If(Tema(MFI(21),21)-50 > 5,+1,If(Tema(MFI(21),21)-50
< -5,-1,0))
BW7 CMO
If(Tema(CMO(C,21),21) > 5,+1,If(Tema(CMO(C,21),21)
< -5,-1,0))
BW8 VAR ma
If(Mov(C,21,VAR) > Mov(C,55,VAR) AND
HHV(Mov(C,233,VAR),5) =
HHV(Mov(C,233,VAR),13),+1,If(Mov(C,21,VAR) <
Mov(C,55,VAR) AND LLV(Mov(C,233,VAR),5) =
LLV(Mov(C,233,VAR),13),-1,0))
The next formula just adds up the binary wave.
BW Add
Fml("BW2") + Fml("BW3") + Fml("BW4") + Fml("BW5") +
Fml("BW6") + Fml("BW7") + Fml("BW8")
Next, I decided to do something a little different. Since the whole purpose of this test
is to catch a trending stock, I decided to add an amplifier that would get larger as the
trend got stronger. Since I like Fibonacci numbers, I decided to use Rsquared as a
measure of trend strength and base my amplifier on Fibonacci numbers. The formula I
finally came up with after a lot of tinkering follows.
BW Amplifier
If(RSquared(C,21) > 0.8,5,If(RSquared(C,21) >
0.6,3,If(RSquared(C,21) > 0.4,2,
If(RSquared(C,21)>0.2,1,0.5))))
The last step in constructing the binary wave was to decide on the smoothing and put
it all together. Of course, I used tema smoothing.

68
Tema Binary Wave Composite

Periods := Input("Enter Tema Smoothing


Periods",8,233,21);
Tema(Fml("BW Add")*Fml("BW Amplifier"),Periods)

The final step is to come up with a system test for the Tema Binary Wave Composite.
Remember, the binary wave is just made up of a bunch of technical indicators that I
give a +1 value when bullish, 0 when neutral, and -1 when bearish. Then they are
summed and smoothed. So in general a positive value is bullish and a negative value
is bearish. Also a rising number is bullish and a falling number is bearish. Therefore
you could use a zero crossover to the upside as a buy signal and a crossover to the
downside as a sell signal. If you had a good algorithm, you could also use a rise from
a negative peak (or trough) as a buy signal and a fall from a positive peak as a sell
signal. I decided to use a 8 day moving average of the BW with a crossover of the
BW for my algorithm in an attempt to get an early signal on a rise from a negative
peak. It does have the disadvantage of finding way too many peaks so I only use it as
an Alert. For confirmation I use the QStick function and a variable moving average
function.
QStick was developed by Chande as a way to quantify candlesticks. Since the
difference between the open and close prices lies at the heart of candlestick charting,
QStick is simply a moving average of that difference. Negative values of QStick
correlate to black candlesticks, positive values to white candlesticks. Since in general
black candles are bearish and white candles are bullish, this indicator can also be
plotted as a histogram and interpreted the same was as the Binary Wave. The formula
is:
Periods := Input("Enter Periods",1,233,34);
Tema(Qstick(Periods),Periods)
Now to get my open long signal I use the ALERT signal with an 8 day vma BW
crossover of the BW. Then to actually get the signal, I have to have both the QStick
rising and the 21 day vma greater then the 55 day vma.

Therefore my buy signal became:


Enter Long
Alert(Cross(Fml("Tema Binary Wave Comp"),
Mov(Fml("Tema Binary Wave Comp"),8,S)),21) AND
HHV(Tema(Qstick(34),34),5) = HHV(Tema(Qstick(34),34),13) AND
Mov(H,21,VAR) > Mov(H,55,VAR)

Since the market has an upward bias, I wanted my sell signal to be more restrictive.
Therefore instead of trying to catch a fall from a positive peak as my sell alert, I
wanted a crossover of an optimized negative number. I still used QStick and vma to
confirm and also added that the close should be lower than yesterdays low.

Therefore, my sell signal became:


Enter Short
Alert(Cross(-opt2,Fml("Tema Binary Wave Comp")),8) AND
Tema(Qstick(34),34) < -0.1 AND
C < Ref(L,-1) AND
Mov(L,21,VAR) < Mov(L,55,VAR)

69
Then I wanted exit conditions that were less then full signal reversals. I decided that
the BW being less than a negative number would be my primary close long signal, but
I also wanted confirmation from other indicators. After a lot of trial and error I used
the following:

Close Long
Fml("Tema Binary Wave Comp") < -opt1 AND
Tema(Qstick(34),34) < 0 AND
LLV(Mov(L,21,VAR),5) = LLV(Mov(L,21,VAR),13)

Close Short
Fml("Tema Binary Wave Comp") > 0 AND
Tema(Qstick(34),34) > 0.08

Finally I also used Fibonacci numbers for my optimization:


Opt 1: Min 3, Max 13, Step 5
Opt 2: Min 3, Max 13, Step 5
SIGNAL FORMULAS
MetaStock for Windows System Tester
01_R2/Regress Slope/MFI/TSF - (Vol Rqd)

---------------
Enter Long:
Alert(RSquared(C,21) < 0.15,21) AND
LinRegSlope(C,34) > opt1 AND
HHV(LinRegSlope(C,34),5) =
HHV(LinRegSlope(C,34),13) AND
HHV(MFI(55),5) = HHV(MFI(55),13) AND
HHV(TSF(C,55),5) = HHV(TSF(C,55),13)
Close Long:
LLV(TSF(C,55),5) = LLV(TSF(C,55),13) AND
LinRegSlope(C,34) < opt1
Enter Short:
Alert(RSquared(C,21) < 0.15,13) AND
LinRegSlope(C,34) < opt2 AND
LLV(LinRegSlope(C,34),5) =
LLV(LinRegSlope(C,34),13) AND
LLV(MFI(55),5) = LLV(MFI(55),13) AND
LLV(TSF(C,144),5) = LLV(TSF(C,144),13)
Close Short:
HHV(TSF(C,144),5) = HHV(TSF(C,144),13)
OPTIMIZATION VARIABLES
----------------------
OPT1: Min = -0.10 Max = 0.00 Step = 0.10
OPT2: Min = -0.20 Max = 0.00 Step = 0.10
STOPS ALL OFF
------------------------------------------------------------
02_R2/Regress Slope/CMO - All
SIGNAL FORMULAS

70
---------------
Enter Long:
Alert(RSquared(C,21) < 0.15,21) AND
LinRegSlope(C,34) > opt1 AND
HHV(LinRegSlope(C,34),5) =
HHV(LinRegSlope(C,34),13) AND
CMO(C,55) > 0 AND
C = HHV(C,5)
Close Long:
LinRegSlope(C,34) < opt1 AND
CMO(C,55) < 0 AND
C = LLV(C,5)
Enter Short:
Alert(RSquared(C,21) < 0.15,13) AND
LinRegSlope(C,34) < opt2 AND
LLV(LinRegSlope(C,34),5) =
LLV(LinRegSlope(C,34),13) AND
CMO(C,55) < 0 AND
C = LLV(C,5)
Close Short:
LinRegSlope(C,34) > opt2 AND
CMO(C,55) > 0 AND
C = HHV(C,5)
OPTIMIZATION VARIABLES
----------------------
OPT1: Min = -0.10 Max = 0.00 Step = 0.10
OPT2: Min = -0.20 Max = 0.00 Step = 0.10

STOPS ALL OFF


------------------------------------------------------------
03_R2/Regress Slope/Qstick - (OHLC Rqd)
SIGNAL FORMULAS
---------------
Enter Long:
Alert(RSquared(C,21) < 0.15,21) AND
LinRegSlope(C,34) > opt1 AND
HHV(LinRegSlope(C,34),5) =
HHV(LinRegSlope(C,34),13) AND
Qstick(55) > opt1 AND
HHV(Qstick(55),5) = HHV(Qstick(55),13)
AND C=HHV(C,5)
Close Long:
LinRegSlope(C,34) < opt1 AND
Qstick(55) < opt1 AND
C = LLV(C,5)
Enter Short:
Alert(RSquared(C,21) < 0.15,13) AND
LinRegSlope(C,34) < opt2 AND
LLV(LinRegSlope(C,34),5) =

71
LLV(LinRegSlope(C,34),13) AND

Qstick(55) < opt2 AND


LLV(Qstick(55),5) = LLV(Qstick(55),13)
AND C = LLV(C,5)
Close Short:
LinRegSlope(C,34) > opt2 AND
Qstick(55) > opt2 AND
C = HHV(C,5)

OPTIMIZATION VARIABLES
----------------------
OPT1: Min = -0.10 Max = 0.00 Step = 0.10
OPT2: Min = -0.10 Max = 0.00 Step = 0.10

STOPS ALL OFF


------------------------------------------------------------
04_R2/Regress Slope/CCI/TSF - All
SIGNAL FORMULAS
---------------
Enter Long:
Alert(RSquared(C,21) < 0.15,21) AND
LinRegSlope(C,34) > opt1 AND
HHV(LinRegSlope(C,34),5) =
HHV(LinRegSlope(C,34),13) AND
HHV(CCI(55),5) = HHV(CCI(55),13) AND
CCI(55) > 0 AND
HHV(TSF(C,55),5) = HHV(TSF(C,55),13)
AND C = HHV(C,5)
Close Long:
LLV(TSF(C,55),5) = LLV(TSF(C,55),13) AND
LinRegSlope(C,34) < opt1 AND
CCI(55) < 0 AND
C = LLV(C,5)
Enter Short:
Alert(RSquared(C,21) < 0.15,13) AND
LinRegSlope(C,34) < opt2 AND
LLV(LinRegSlope(C,34),5) =
LLV(LinRegSlope(C,34),13) AND
LLV(CCI(55),5) = LLV(CCI(55),13) AND
LLV(TSF(C,144),5) = LLV(TSF(C,144),13)
AND C = LLV(C,5)
Close Short:
HHV(TSF(C,144),5) = HHV(TSF(C,144),13) AND
C = HHV(C,5)
OPTIMIZATION VARIABLES
----------------------
OPT1: Min = -0.10 Max = 0.00 Step = 0.10
OPT2: Min = -0.20 Max = 0.00 Step = 0.10

72
STOPS ALL OFF

{from "Jim Greening" <JimGinVA@msn.com>}


Shark Pattern
Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);

If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND


Ref(L,-1)>Ref(L,-2)),
If(apex <= (Ref(H,-2)-(WB*Symmetry)) AND Apex >=
(Ref(L,-2)+(WB*Symmetry)) ,1,0),0);

{simply place the above in the filter section}


Short term horizontal trading ranges
exploration by Jim Greening

HHV(C,21) < 1.1*Mov(C,21,S) AND


LLV(C,21) > 0.9*Mov(C,21,S)

{place the formulas above in the filter section; nothing else is required}

PRING's DAILY KST BUY

Notes: KST BUY SIGNAL FROM BELOW ZERO

ColA:
Name: Close
CLOSE
ColB:
Name: KST
(Mov(ROC(C,10,%),10,S)*1)+(Mov(ROC(C,15,%),10,S)*2)+
(Mov(ROC(C,20,%),10,S)*3)+(Mov(ROC(C,30,%),15,S)*4)
ColC:
Name: KST MA
Mov((Mov(ROC(C,10,%),10,S)*1)+(Mov(ROC(C,15,%),10,S)*2)+
(Mov(ROC(C,20,%),10,S)*3)+(Mov(ROC(C,30,%),15,S)*4),10,S)
ColD:
Name: KST-1
Ref( (Mov(ROC(C,10,%),10,S)*1)+(Mov(ROC(C,15,%),10,S)*2)+
(Mov(ROC(C,20,%),10,S)*3)+(Mov(ROC(C,30,%),15,S)*4),-1)
ColE:
Name: MA KST-1
Ref(Mov((Mov(ROC(C,10,%),10,S)*1)+(Mov(ROC(C,15,%),10,S)*2)+
(Mov(ROC(C,20,%),10,S)*3)+(Mov(ROC(C,30,%),15,S)*4),10,S),-1)
Filter:
When(colB,>,colC)AND When(colB,<,0)AND When( colD,<,colE)

73
John Hunt's Exploration for MetaStock

Place in FILTER section of Exploration.


No other information need be entered in the Exploration columns.}

When(C-Mov(C,25,S),>,0) AND
When(Ref(C-Mov(C,25,S),-1),<=,0) AND
When(HHV(Mov(Ref(C-Mov(C,25,S),-1),3,S),19),<=,0) AND
When(C,<,0.8*HHV(C,260))

{This means: when today's (close - moving average) > 0, when yesterday's (close -
moving average) <= 0, when highest value of 3 day moving average of yesterday's
(close - moving average) over past 19 days <= 0, and finally, when today's close <
80% of highest value of all closes for past year. (The third test is to eliminate past
false breakouts.)}

Dunn-Type1

{Market swing is defined as:


Up = higher highs and higher lows,
Down = lower highs and lower lows.}

TD1:=If(BarsSince(H>Ref(H,-1) AND L>Ref(L,-1)) <


BarsSince(L<Ref(L,-1) AND H<Ref(H,-1)),
{then}1,
{else}-1);
TD1

Dunn-Type2

{Market swing is defined as:


Up = 2 higher highs and 2 higher lows,
Down = 2 lower highs and 2 lower lows.}
TD1:=If(BarsSince((H>Ref(H,-1) AND L>Ref(L,-1))
AND (Ref(H,-1)>Ref(H,-2)
AND Ref(L,-1)>Ref(L,-2))) <
BarsSince((L<Ref(L,-1) AND H<Ref(H,-1))
AND (Ref(L,-1)<Ref(L,-2)
AND Ref(H,-1)<Ref(H,-2))),
{then}1,
{else}-1);
TD1

74
Dunnigan Trend

{Ask to use 1 day or 2 day Swing type}


St:=Input("Short Term Swing Type, 1 or 2 ?",
1,2,2);
{Call Swing Type Formula}
Sd:=If(Round(St)=1,
{then} FmlVar("Dunn-Type1","TD1"),
{else} FmlVar("Dunn-Type2","TD1"));
{Number Of Periods Since Swing Started Up}
Hc:=BarsSince(SD=-1);
{Number Of Periods Since Swing Started Down}
Lc:=BarsSince(SD=1);
{Find Highest Value Of Up Swing}
Hv:=If(Hc>Lc AND H>Ref(H,-1),
{then}HighestSince(1,Hc=1,H),
{else}0);
{Find Lowest Value Of Down Swing}
Lv:=If(Hc<Lc AND L<Ref(L,-1),
{then}LowestSince(1,Lc=1,L),
{else}0);
{Find The Low Of The Highest High}
Hlv:=ValueWhen(1,H=Hv,L);
{Find The High Of The Lowest Low}
Lhv:=ValueWhen(1,L=Lv,H);
{Calculate And Plot Trend Direction,
Note: 1= Uptrend,
-1= Downtrend}
TD2:=If(Sd=1 AND H>Lhv,
{then}1,
{else}If(Sd=-1 AND L<Hlv,
{then}-1,
{else}0));
TD3:=ValueWhen(1,TD2<>0,TD2);
TD3

{These formulas simply plot a 1 if market is up or -1 if down. I really didn't code this
to be used as an indicator, but to be used as a subroutine, or possibly in an "Expert
Adviser".
Best wishes, Adam Hefner.}

Dynamic Multiple Time Frame Indicator

Explanation of the Dynamic Multiple Time Frame Indicator by the author, Adam
Hefner:

"The Fixed Balance Point is calculated every Friday by


taking the weekly (high+low+close)/3. It really doesn't
need to be plotted, but is mostly used to base the other

75
indicators from.

The Fixed Balance Point Step, is a 5 week average of


the Fixed Balance Point.

The Dynamic Balance Point is the daily update of the


Fixed Balance Point.

The Dynamic Balance Point Step is the daily update


of the Fixed Balance Point Step.

Robert Krausz teaches that by watching the balance point


calculations of the longer (weekly) time, you have the market
direction (trend) for the shorter (daily) time. He also revealed
that the when the Dynamic Balance Point is above the Dynamic
Balance Point Step, then the trend is up, and opposite is true
for down trend. I have found that these act in much the same way
as a 5/25 moving average cross-over system.

I like the Fibonacci Support & Resistance best of all, seems (IMHO)
that these support/resistance areas are very easy to visualize using
this formula."

Krausz's Gann Swing HiLow Activator

I was only able to implement Krausz's Gann Swing HiLow Activator in Metastock,
because it's simply the average of the last three bars High (stop for short position or
long entry) or Low (stop for long position or short entry) plotted one period forward:

Ref(Mov(L,3,S),-1) or Ref(Mov(H,3,S),-1)

(from Thorsten Buhmann in Germany)

Use of Tema PV Binary Wave and Tema QStick Formulas

in MetaStock, from "JimG"

There are really two different ways to use these formulas. Since the Binary Wave is a
smoothed addition of several technical indicators that each give +1 when bullish, 0
when neutral and -1 when negative, it makes sense that a positive number is bullish
and rising numbers are bullish. Similarly negative numbers and falling numbers are
bearish.

The QStick is really a candlestick type indicator, but can be read as bullish or bearish
in same way as the Binary Wave.

The two traditional ways to play them are to buy on a rise from a negative peak and
sell on a fall from a positive peak, or to buy on a zero cross over to the upside and sell
on a zero crossover to the downside. Of course you can optimize and find various buy

76
and sell levels as long as you understand what is bearish and what is bullish.

My own MetaStock system tests alerts on the BW crossing a moving average of itself
and buys or sells on a confirmation of Qstick turning positive or negative respectively.
Having said that, I don't make my buy an sell decisions from the indicators or the
system test. I do use the system test as an initial screen and use a buy signal as a flag
to move the stock to my watch list. I make all buying and selling decisions based on
the trend channels. Over the years, I've found that works best for me.

The HIGHER CLOSES MetaStock exploration should be entered as follows:

colA CLOSE
colB ref(C,-1)
colC ref(C,-2)
filter colA > colB AND colB > colC

{General Purpose Intermediate Term MACD Indicator}


( Mov( C,13,E ) - Mov( C,34,E ) ) - Mov( ( Mov( C,13,E ) - Mov( C,34,E ) ),89,E )

{General Purpose Short Term MACD Indicator}


( Mov( C,8,E ) - Mov( C,17,E ) ) - Mov( ( Mov( C,8,E ) - Mov( C,17,E ) ),9,E )

Dave's New System

DNS is a binary consisting of 8 indicators.}

If(SAR(.02,.2)<C,1,0) +
If((Mov(C,5,E)>Mov(C,13,E)),1,0) +
If((Mov(C,13,E)>Mov(C,40,E)),1,0) +
If((Mov(C,8,E)-Mov(C,17,E))> (Mov(Mov(C,8,E)-Mov(C,17,E),9,E)),1,0)+
If(Mov(C,50,SIMPLE) - Ref(Mov(C,50,SIMPLE),-15) > 0,1,0)+
If((Mov(ROC(C,12,%),3,E)>=-6 OR ROC(C,12,%)>0),1,0)+
If(OBV()>Mov(OBV(),40,S),1,0)+
If(V>Mov(V,120,S),1,0)

{created by David R. Evans}

Fibonacci Trader - Fixed Balance Point - REVISED

{NOTE: under Color/Style options, change


plot to last "style" option}

{revised 1 Jan 99}

Mc1:=BarsSince(DayOfWeek()=1);
Fc1:=BarsSince(DayOfWeek()=5);
Fc2:=Ref(BarsSince(DayOfWeek()=5),-1)-1;
{Fixed Balance Point Calculation}

77
FBC:=If(Mc1=0 AND Fc1>2,
{then}(Ref(HHV(H,LastValue(mc1)),-1)+
Ref(LLV(L,LastValue(Mc1)),-1)+
Ref(C,-1))/3,
{else}If(Fc1=0 AND Mc1>5,
{then}(HHV(H,LastValue(Fc2))+
LLV(L,LastValue(Fc2))+C)/3,
{else}If(Fc1=0,
{then}(HHV(H,LastValue(Mc1))+
LLV(L,LastValue(Mc1))+C)/3,
{else}0)));
{Fixed Balance Point Plot}
FBP:=ValueWhen(1,FBC>0,FBC);
FBP;

Fibonacci Trader- Support & Resistance

{NOTE: under Color/Style options, change


plot to last "style" option}

{Weekly Price Range Calculation}


Mc1:=BarsSince(DayOfWeek()=1);
Fc1:=BarsSince(DayOfWeek()=5);
Fc2:=Ref(BarsSince(DayOfWeek()=5),-1)-1;
WRC:=If(Mc1=0 AND Fc1>2,
{then}Ref(HHV(H,LastValue(mc1)),-1)-
Ref(LLV(L,LastValue(Mc1)),-1),
{else}If(Fc1=0 AND Mc1>5,
{then}HHV(H,LastValue(Fc2))-
LLV(L,LastValue(Fc2)),
{else}If(Fc1=0,
{then}HHV(H,LastValue(Mc1))-
LLV(L,LastValue(Mc1)),
{else}0)));
WRP:=ValueWhen(1,WRC>0,WRC);
{Resistance Range}
RR1:= FmlVar("FT-FBP","FBP")+(WRP*.5);
RR2:= FmlVar("FT-FBP","FBP")+(WRP*.618);
{Support Range}
SR1:= FmlVar("FT-FBP","FBP")-(WRP*.5);
SR2:= FmlVar("FT-FBP","FBP")-(WRP*.618);
{Plot Ranges}
RR1;
RR2;
SR1;
SR2;

Fibonacci Trader-Fixed Balance Point Step

78
FPS:=(ValueWhen(1,FmlVar("FT-FBP","FBC")>0,
FmlVar("FT-FBP","FBC")) +
ValueWhen(2,FmlVar("FT-FBP","FBC")>0,
FmlVar("FT-FBP","FBC")) +
ValueWhen(3,FmlVar("FT-FBP","FBC")>0,
FmlVar("FT-FBP","FBC")) +
ValueWhen(4,FmlVar("FT-FBP","FBC")>0,
FmlVar("FT-FBP","FBC")) +
ValueWhen(5,FmlVar("FT-FBP","FBC")>0,
FmlVar("FT-FBP","FBC")))/5;
FPS

Fibonacci Trader - Dynamic Balance Point

{Dynamic Balance Point Calculation}


dt:=DayOfWeek();
DBC:=(HighestSince(5,DayOfWeek()=dt,H)+
LowestSince(5,DayOfWeek()=dt,L)+CLOSE)/3;
DBC
MetaStock Custom Indicator moving averages
periods1:=Input("Periods of ROC",2,50,12);
periods2:=Input("Smoothing Period",1,50,1);
Input("horizontal line 1",-50,50,5);
Input("horizontal line 2",-50,50,-5);
Mov(ROC(C,periods1,%),periods2,S);
{from Eric Kendall}
{MetaStock SAR Exploration}
{cola:BUY: this means: label column A as "BUY" and then enter the following
formula:}
Cross(L,(SAR(.02,.2)))
{colb:SELL: this means: label colum B as "SELL" and then enter the following
formula:}
Cross(SAR(.02,.2),H)
{enter the following in the filter section:}
cola=1 or colb=1
{where the AF=0.02 which you can change. try doing a sys test by
replacing the numbers with opt1 & opt2}
{from Mike Anoldi}

MOVING AVERAGE CHANNEL


"The MetaStock moving average function has an option for displacing the mov
both vertically and horizontally. most of the time, I prefer to use a mov
channel in place of Bollinger Bands."
from L. and G. Issen.
"I use moving average, instead of Bollinger Bands, creating three indicators
in the following way, and saving them in a template:
Mov(C, 28,S) displaced +10%
Mov(C, 28,S) displaced - 10%
Mov(C, 28,S)

79
28 days is the basic span of time. Like the 10% +/-, this should be adjusted
for each security and for the particular condition you are waiting for
(buy/sell). When I see a buying opportunity ahead, I just draw another trio
of faster MAs (keeping the slow on the chart) and use them, with other
indicators/oscillators, to time the entry. Same process to exit the market."
from G.G.
STOCHASTIC MOMENTUM INDICATOR

{Appeared in the January 1993 issue of Stocks & Commodities magazine}

100 * ( Mov( Mov(C - (.5 * ( HHV(H,13) + LLV(L,13))),25,E),2,E) / (.5*Mov(


Mov( HHV(H,13) - LLV(L,13),25,E),2,E)))

TRUE STRENGTH INDEX


{Appeared in the January 1993 issue of Stocks & Commodities magazine}

100 * ( Mov( Mov( ROC(C,1,$),25,E),13,E) / Mov( Mov( Abs(


ROC(C,1,$)),25,E),13,E))

LINEAR REGRESSION SLOPE

{The basic "programming" in MetaStock of the LRS-ROC indicator is like this:


NIO is the _basic_ number of points taken to calculate the ROCs. The four
ROCs _per day_ used for interpolation are:}

rll:=ROC(O,nio-1,%)/(nio-1);
rl:=ROC(O,nio,%)/nio;
rh:=ROC(O,nio+1,%)/(nio+1);
rhh:=ROC(O,nio+2,%)/(nio+2);

{Now, interpolation is done at a point XIO (0<=xio<=1), i.e., between the


points NIO and NIO+1, using a simple interpolation formula weighting with
the _distances_ of the four ROCs from the interpolation point XIO:}

rit:=(rll/(1+xio)+rl/(xio+.0001)+rh/(1-xio)+rhh/(2-xio))/(1/(1+xio)+1/(xio+.
0001)+1/(1-xio)+1/(2-xio));

{Then the LinearRegressionSlope is taken _twice_ (for numerical reasons)


from the interpolated ROC, using the basic number of points; i.e., NIO. That
is where we get our LRS-ROC indicator, named RO here:}

ro:=LinRegSlope(LinRegSlope(rit,nio),nio);

{NIO+XIO together represent the _real_ (not integer!) number of points or


days, the LRS-ROC indicator is calculated for, e.g. 4.57 days.
Unfortunately, MetaStock is not able to use _one_ real number (e.g., 4.57)
as input to be splitted into NIO and XIO and to be used in the formulas
above. So NIO and XIO have to be provided separately, because of the

80
restrictions in MetaStock, and both are subjected to some "optimization" in
accordance to the historical prices.

To be clear: This LRS-ROC indicator triggers _only the timing_ for


entering/closing a position, using an appropriate criterion. Additional
(also ROC-based) criterions are used to stay out/in during extreme
bearish/bullish situations.

Additionally: This "TA" is only one basic element of my option trading


system, primarily to catch some "special reality effects" that cannot be
modeled by example-based know-how recycling from historical data. But
probably this TA system may also be used as a "stand-alone" system.

rudolf stricker}

ANOTHER LRS-ROC INDICATOR

Lb:=Input("Look-Back Periods?",3,100,13);
ROC( LinRegSlope(C,Lb),Lb,$)

{by Adam Hefner}


DIVERGENCE BETWEEN CLOSE AND INDICATOR

Divergence between the Close and an Indicator (Rev. 03/18/97 from Equis Support)
The following formula will calculate the correlation of the Close and the MACD. It is
written using a "long form" MACD so that the time periods used by the MACD may
be changed. This indicator shows "divergence" between the close and the indicator: In
the Windows versions of MetaStock the formula is:
Correl(((Sum(Cum(1)*(Mov(C,12,E)-Mov(C,26,E)),100))-(Sum(Cum(1),100)*
Sum((Mov(C,12,E)-Mov(C,26,E)),100)/100))/((Sum(Power(Cum(1),2),100))-
(Power(Sum(Cum(1),100),2)/100)),((Sum(Cum(1)*C,100))-(Sum(Cum(1),100)*
Sum(C,100)/100))/((Sum(Power(Cum(1),2),100))-
(Power(Sum(Cum(1),100),2)/100)),12,0) The interpretation of the indicator output is
as follows: - .08 (80%) and lower is divergence between the Close and the MACD. - 1
is very strong divergence. + 1 is very strong correlation. The formula was constructed
this way so that most other indicators may be used in place of the MACD. For
example, here is the same indicator using the RSI(14):
Correl(((Sum(Cum(1)*(RSI(14)),100))-(Sum(Cum(1),100)*
Sum((RSI(14)),100)/100))/((Sum(Power(Cum(1),2),100))-
(Power(Sum(Cum(1),100),2)/100)), ((Sum(Cum(1)*C,100))-
(Sum(Cum(1),100)*Sum(C,100)/100))/((Sum(Power(Cum(1),2),100))-
(Power(Sum(Cum(1),100),2)/100)),12,0)

MACD TOPS AND BOTTOMS

QUESTION: As you know, MACD is always bottoming or topping before crossing


its trigger line. However, the MACD signal comes always a bit late compared to price
movement. Is there any way to calculate the MACD first derivative function to

81
identify MACD tops/bottoms, that could be use by the Explorer or the System Tester?
-- Augustin Bataille, Belgium ANSWER: One way to do what you want would be
using the 'Rate of Change' function. For example: RocPeriods:=1;
ROC(MACD(),RocPeriods,$) or for the MACD histogram you would have
RocPeriods:=1; ROC(MACD() - Mov(MACD(),9,E),RocPeriods,$) If that is to noisy,
you could smooth it a bit with: RocPeriods := 1; MovAvePeriod :=1; ; Mov(3 *
ROC(MACD(),RocPeriods,$) , MovAvePeriod,E) {the 3 just 'magnifies' the line on
the plot but doesn't affect the calculation} or for the MACD histogram: RocPeriods :=
1; MovAvePeriod :=1; ; Mov(3 * ROC(MACD() - Mov(MACD(),9,E),RocPeriods,$)
, MovAvePeriod,E) Another way to do what you want would be to look for peaks and
troughs using the 'Peak' and 'Trough' functions. I'm working on code to identify
divergences using this method. -- Dr. Robert Jackson robert.jackson@utoronto.ca -
QUESTION: As you know, MACD is always bottoming or topping before crossing
its trigger line. However, the MACD signal comes always a bit late compared to price
movement. Is there any way to calculate the MACD first derivative function to
identify MACD tops/bottoms, that could be use by the Explorer or the System Tester?
-- Augustin Bataille, Belgium ANSWER: One way to do what you want would be
using the 'Rate of Change' function. For example: RocPeriods:=1;
ROC(MACD(),RocPeriods,$) or for the MACD histogram you would have
RocPeriods:=1; ROC(MACD() - Mov(MACD(),9,E),RocPeriods,$) If that is to noisy,
you could smooth it a bit with: RocPeriods := 1; MovAvePeriod :=1; ; Mov(3 *
ROC(MACD(),RocPeriods,$) , MovAvePeriod,E) {the 3 just 'magnifies' the line on
the plot but doesn't affect the calculation} or for the MACD histogram: RocPeriods :=
1; MovAvePeriod :=1; ; Mov(3 * ROC(MACD() - Mov(MACD(),9,E),RocPeriods,$)
, MovAvePeriod,E) Another way to do what you want would be to look for peaks and
troughs using the 'Peak' and 'Trough' functions. I'm working on code to identify
divergences using this method. -- Dr. Robert Jackson robert.jackson@utoronto.ca –

Countback line for Metastock.


(Note. This is very good, but the limitation is the lookback period. The
calculation point for the CBL line might be 5, 10, 15, 30 days away from
todays date.Also watch for the way 'gap' days are treated. Daryl Guppy)
Copied from StockCentral - Thanks Ken D

Well .... last weekend I replied to a post requesting a MetaStock solution for
calculating the Countback Line discussed in Daryl Guppy's book "Share Trading: An
Approach to Buying and Selling". Subequently, about 30 requests for the formulas I
use were received. Not unexpectedly, a few defects were found with the original
offerings. This helped forge a somewhat more robust solution, which is here given to
the wider audience of this Forum, so that further improvements may be forthcoming.
Alternatives of presentation style are many, according to taste, but we are here
requesting improvements in substance, identification of possible flaws, or have real
simplification benefits - please provide solutions where possible.

ACKNOWLEDGEMENTS .... With thanks to the several people who have


commented, all constructively it is pleasing to say, particular credit is warranted by
the significant contributions from Bryan Stanton and Siobhan Channon.

LIMITATIONS .... With MetaStock, there seems to be a need for two different
formulas to handle the issue: - one for the CBL from a LOW (CBLlo), - the other for

82
the CBL from a HIGH (CBLhi). The formulas given below were generated using
v.6.52. Because of the use of PREV they won't work in some earlier MetaStock
versions it seems, though a bit of thought should overcome this limitation - anyone
able to comment? As written they are based upon relative prices over a DEFAULT
cover of 13 days (but adjustable from 3 to 55 days) - this is one of the potential
weaknesses which commands individual interpretation for a particular equity or
contract, which may cycle more or less frequently and require different timeframes.
Other indicators and assessments are, of course, needed to gauge the probability of a
CBL-indicated counter-trend holding. Also, for particularly choppy or indecisive
circumstances there may be a need to extend the Ref(H or L, -5) to a greater number
of comparison days by appropriate copying and adjustments to the basically simple
pattern in these formulas - but if it came to this perhaps the trade should be left alone
anyway! Owing to price vagaries it is not unusual for a CBLhi to be less than a CBLlo
calculation, or the converse, especially with low-gradient trends or sideways price
movements.

NOTE: With each formula below, copy exactly from "HighDays" or "LowDays"
down to "PREV )))))" into the Indicator Builder.

CBLhi:

HighDays := Input("Enter # days to cover last HIGH for CBL calc'n:", 3, 55, 13);

If(HIGH < HHV(HIGH, HighDays), {then ...} PREV, {previous CBLhi, else...}
If(Ref(L,-2) < Ref(L,-1) AND Ref(L,-2) < L AND Ref(L,-1) < L, {then ...} Ref(L,-2),
{2nd day back low, else...} If((Ref(L,-3)< Ref(L,-2) AND Ref(L,-3) < Ref(L,-1) AND
Ref(L,-3) < L) AND (Ref(L,-2)< L OR Ref(L,-1) < L), {then ... } Ref(L,-3), {3rd day
back low, else...} If((Ref(L,-4)< Ref(L,-3) AND Ref(L,-4) < Ref(L,-2) AND Ref(L,-
4) < Ref(L,-1) AND Ref(L,-4) < L) AND (Ref(L,-3)< L OR Ref(L,-2) < L OR
Ref(L,-1) < L), {then... } Ref(L,-4), {4th day back low, else...} If((Ref(L,-5)< Ref(L,-
4) AND Ref(L,-5) < Ref(L,-3) AND Ref(L,-5) < Ref(L,-2) AND Ref(L,-5) < Ref(L,-
1) AND Ref(L,-5) < L) AND (Ref(L,-4)< L OR Ref(L,-3) < L OR Ref(L,-2) < L OR
Ref(L,-1) < L), {then ...} Ref(L,-5), {5th day back low, else...} PREV )))))

and for the CBL from a LOW

CBLlo:

LowDays := Input("Enter # days to cover last LOW for CBL calc'n:", 3, 55, 13);

If(LOW > LLV(LOW, LowDays), {then ...} PREV, {previous CBLlo, else...}
If(Ref(H,-2) > Ref(H,-1) AND Ref(H,-2) > H AND Ref(H,-1) > H, {then ...} Ref(H,-
2), {2nd day back high,else...} If((Ref(H,-3)> Ref(H,-2) AND Ref(H,-3) > Ref(H,-1)
AND Ref(H,-3) > H) AND (Ref(H,-2)> H OR Ref(H,-1) > H), {then ... } Ref(H,-3),
{3rd day back high,else...} If((Ref(H,-4)> Ref(H,-3) AND Ref(H,-4) > Ref(H,-2)
AND Ref(H,-4) > Ref(H,-1) AND Ref(H,-4) > H) AND (Ref(H,-3)> H OR Ref(H,-2)
> H OR Ref(H,-1) > H), {then... } Ref(H,-4), {4th day back high,else...} If((Ref(H,-
5)> Ref(H,-4) AND Ref(H,-5) > Ref(H,-3) AND Ref(H,-5) > Ref(H,-2) AND Ref(H,-
5) > Ref(H,-1) AND Ref(H,-5) > H) AND (Ref(H,-4)> H OR Ref(H,-3) > H OR
Ref(H,-2) > H OR Ref(H,-1) > H), {then ...} Ref(H,-5), {5th day back high,else...}

83
PREV )))))

Please advise of any problems or suggested improvements in calculating the CBL. It


is again emphasized that this is by no means proposed as the best solution, but as
ONE solution which seems to work. Regards.

MetaStock Expert Commentary by Michael Arnoldi

Review of : <symbol>
as of <date>
TODAY'S CLOSE WriteVal(CLOSE,2.3)
TOMORROW's
PROJECTED HIGH
WriteIf(C<O, "WRITEVAL(-L+ (H+2*L+C)/2,25.2)")
WriteIf(C>O, "WRITEVAL(-L+ (2*H+L+C)/2,25.2)")
WriteIf(C=O, "WRITEVAL(-L+ (H+L+2*C)/2,25.2)")
PROJECTED LOW
WriteIf(C<O, "WRITEVAL(-H+ (H+2*L+C)/2,25.2)")
WriteIf(C>O, "WRITEVAL(-H+ (2*H+L+C)/2,25.2)")
WriteIf(C=O, "WRITEVAL(-H+ (H+L+2*C)/2,25.2)")

BOLLINGER BANDS
CLOSING PRICE:WRITEVAL(C,2.3)
BOLLINGERBAND TOP:
WRITEVAL( BBandTop(C,21,E,2),13.3)
21 DAY MOVING AVERAGE:
WRITEVAL(MOV(C,21,E),13.3)
BOLLINGERBAND BOTTOM:
WRITEVAL( BBandBOT(C,21,E,2),13.3)

PLOTTING FORWARD DAYS


>I want an indicator that will project an exponential moving average into
>the next period (i.e., draw tomorrow's line). It would be really spiffy if I
>could pl ug in tomorrow estimated/projected close and be able to adjust
>the indicator based on various projected closes. --Steve Karnish

The formula below may be close to what you want, but it will not plot on the forward
day. It will just plot the point where tomorrow's EMA would be. The equation is
based on the MetaStock manual, page 459, concerning exponential moving averages.
-- Chuck Wemlinger

TC:=Input("Tomorrow's close",0.001,1000,1);
MAP:=Input("Moving Average Period",2,144,55);
MA1:=Mov(C,MAP,E);

84
EPX:=2/(MAP+1);
MA2:=(TC*EPX)+(MA1*(1-EPX));
ValueWhen(1,Cum(1)=LastValue(Cum(1)),MA2)

MACD ADDITIONS
{These MetaStock MACD indicator formulas allow user input for parameters when
run}

mp1:=Input("Short MA",1,377,13);
mp2:=Input("Long MA",1,377,34);
Mov(C ,mp1 ,E )- Mov(C ,mp2 ,E )
MACD signal line
mp1:=Input("Short MA",1,377,13);
mp2:=Input("Long MA",1,377,34);
mp3:=Input("Signal MA",1,377,89);
Mov( (Mov(C ,mp1 ,E )- Mov(C ,mp2 ,E )),mp3,E)

MACD - Signal Line


mp1:=Input("Short MA",1,377,13);
mp2:=Input("Long MA",1,377,34);
mp3:=Input("Signal MA",1,377,89);
(Mov(C,mp1,E)-Mov(C,mp2,E))-(Mov((Mov(C,mp1,E)-Mov(C,mp2,E)),mp3,E))

{Thanks to Keith Massey}

GANN HIGH LOW

{name: GANN-HiLo}

HLd:=If(CLOSE>Ref(Mov(H,3,S),-1),
{then}1,
{else}If(CLOSE<Ref(Mov(L,3,S),-1),
{then}-1,
{else}0));
HLv:=ValueWhen(1,HLd<>0,HLd);
HiLo:=If(HLv=-1,
{then}Mov(H,3,S),
{else}Mov(L,3,S));
HiLo;
---------------------------------------------------
GANN-Swing

{Market swing is defined as:


Up = 2 higher highs,
Down = 2 lower highs.}

85
Us:=BarsSince((H > Ref(H,-1)) AND (Ref(H,-1) >

Ref(H,-2)));
Ds:=BarsSince((L < Ref(L,-1)) AND (Ref(L,-1) <
Ref(L,-2)));
Sd1:=If(Us=0,
{then}If(Ref(L,-1)<>LowestSince(1,Ds=0,L),
{then}1,
{else}0),
{else}If(Ds=0,
{then}If(Ref(H,-1)<>
HighestSince(1,Us=0,H),
{then}-1,
{else}0),
{else}0));
Sd2:=If(Sd1=1,
{then} If(Ref(BarsSince(Sd1=1),-1) >
Ref(BarsSince(Sd1=-1),-1),
{then}1,
{else}0),
{else} If(Sd1=-1,
{then}If(Ref(BarsSince(Sd1=1),-1) <
Ref(BarsSince(Sd1=-1),-1),
{then}-1,
{else}0),
{else}0));
TD1:=ValueWhen(1,Sd2<>0,Sd2);
Td1;
-------------------------------------------------------------
GANN-Trend

{Swing Direction}
Sd:= FmlVar("GANN-Swing","TD1") ;
{Swing Change High}
Sch:=If(Sd=1 AND Ref(sd,-1)=-1,
{then}1,
{else}0);
{Swing Change Low}
Scl:=If(Sd=-1 AND Ref(Sd,-1)=1,
{then}1,
{else}0);
{Peak Value}
Pv:=If(Scl=1,
{then}HighestSince(1,Sch=1,H),
{else}0);
{Trough Value}
Tv:=If(Sch=1,
{then}LowestSince(1,Scl=1,L),
{else}0);
{Trend Direction}

86
Td:=If(H>ValueWhen(1,Pv>0,Pv),
{then}1,

{else}If(L<ValueWhen(1,Tv>0,Tv),
{then}-1,
{else}0));
{UpTrend=1 DownTrend =-1}
Tdv:=ValueWhen(1,Td<>0,Td);
Tdv;

contributed by Adam Hefner

CREATE A GANN SWING EXPERT


Instructions

1. First create a new expert and name it whatever you want.

2a. under "trends" tab put this code for bullish:

ut:=FmlVar("GANN-Trend","TDV");
uplot:=If(BarsSince(Ut=1)<
BarsSince(Ut=-1),1,0);
uplot=1;

2b. and this for bearish:

dt:=FmlVar("GANN-Trend","TDV");
dplot:=If(BarsSince(dt=1)>
BarsSince(dt=-1),1,0);
dplot=1;

Then click on the "ribbon" option and turn off "Display Vertical Lines", I also turn off
the corner option.

3a. Under highlights tab create a new and call it "HiLo Change", choose color, and
enter this code:

HLd:=If(CLOSE>Ref(Mov(H,3,S),-1),
{then}1,
{else}If(CLOSE<Ref(Mov(L,3,S),
-1),
{then}-1,
{else}0));
HLv:=ValueWhen(1,HLd<>0,HLd);
HLv<>Ref(HLv,-1);

3b. Create new and call it "Up-Trend", choose color, and enter this code:

87
ut:=FmlVar("GANN-Trend","TDV");
uplot:=If(BarsSince(Ut=1)<
BarsSince(Ut=-1),1,0);

uplot=1;

3c. Create new and call it "Down-Trend", choose color, and enter this code:

dt:=FmlVar("GANN-Trend","TDV");
dplot:=If(BarsSince(dt=1)>
BarsSince(dt=-1),1,0);
dplot=1;

4a. Under "Symbols" tab create new and call it " UpSwing", enter this code:

FmlVar("GANN-Swing","SD2")=1;

then under graphic choose "Buy Arrow", choose color (Dark Green), and small size,
then pick "Above Price Plot".

4b. Create new and call it "DownSwing", enter this code:

FmlVar("GANN-Swing","SD2")=-1;

then under graphic choose "sell arrow", choose color (Dark Red), and small size, then
pick "Below Price Plot".

As for the HiLo ....just plot it as a regular indicator and choose the last "style" option
under "color/style" tab.

from Adam Hefner

RSI AND MOVING AVERAGES

{place in filter section}

C>MOV(C,5,E) AND C>MOV(C,200,E) AND CROSS(RSI(14),30)

{from Michael Arnoldi}


Alligator System modifications
from Murray Richards . . .

Drag this to the chart and change it to a histogram and plot green

AO oscillator Green
If( Mov(( H+L)/2, 5, S)- Mov(( H+L)/2, 34, S),
>,Ref(Mov( ( H+L)/2, 5, S)- Mov(( H+L)/2, 34, S),-1),( Mov(( H+L)/2, 5, S)-
Mov(( H+L)/2, 34, S )),0)

88
Put in the same window and plot it red as a histogram
A Oscillator red
If( Mov( ( H+L)/2, 5, S)- Mov( ( H+L)/2, 34, S),
<,Ref(Mov( ( H+L)/2, 5, S)- Mov( ( H+L)/2, 34, S),-1), Mov( ( H+L)/2, 5,
S)- Mov( ( H+L)/2, 34, S),0)

Acc
Mov(( H+L)/2, 5, S)- Mov(( H+L)/2, 34, S)-
Mov(Mov(( H+L)/2, 5, S)- Mov(( H+L)/2, 34, S) , 5, S)

Put in its on window as a histogram and plot red


AC Red
If( Fml( "Acc" )<Ref( Fml( "Acc" ),-1) ,Fml( "Acc" ),0 )

Put in the same window and plot green

AC green
If( Fml( "Acc" )<Ref( Fml( "Acc" ),-1) ,Fml( "Acc" ),0 )

Start a new expert and chose highlights


color red

Fml( "AC RED" )AND Fml( "A Oscillator red" )

Color green

Fml( "AC Green" ) AND Fml( "A Oscillator Green " )

Save as a template

WORKING WITH DMI

{Smoothed DMI Index (20 Period Moving Average)}

Mov(PDI(14)-MDI(14),20,S)

OPEN LONG:
close>hhv(low,21)

CLOSE LONG:
close<llv(high,21)

89
{by Dick Brow

Shark-32 system - Walter Downs

The Shark exit signals don't appear to be all that good. In some
cases, the sell signals provide good opportunities for short-selling,
but the signals appear to be too few and far between to rely on them
for sell signals for long trades. The Shark pattern occurs too
infrequently, and there's no guarantee it'll occur when the trend
reverses. With long trades, you'd have to look to other indicators,
such as CCI, as you say, or maybe Parabolic SAR. You could use price
breaking below certain moving averages, too -- or moving- average
crossovers.

Seems like entry but no exits in Shark. maybe standard CCI(13) with
200 and -150 triggers.

The shark pattern signals, in the third window in the chart I sent,
were really just alerts showing that the shark pattern had occurred on
those days. The shark system is based on the close rising above levels
set when the shark pattern occurs. The levels are set by the high and
low in the shark pattern, and the close must break through them within
25 days of the signal.

The shark pattern, in other words, isn't a buy or sell signal.

The buy signals were shown in the second window of the chart I sent.
The window is labeled "Shark buy signal." Also, the signals are marked
by green arrows over the price plot in the first window of the chart.

I didn't include sell signals in the chart I sent earlier today. In


the case of MU, the sell signals weren't very good, to be honest.

==========================

The Shark system is really based on two separate events: the occurrence
of the pattern and then the signal.

The pattern isn't the signal. The system gives a signal if and when
the stock breaks above the high point in the pattern over the next 25
days. The high on the first day of the pattern sets that high point.
It's like a resistance level, set by the highest point in the shark
fin. Sometimes the stock doesn't break above it, so there's no signal.
The Shark pattern shows consolidation, which may indicate an expansion
in price to come. But the breakout doesn't always occur.

If the stock breaks below the low point in the pattern, there's a sell
signal.

90
==========================

The idea behind the system is: Look for a three-bar shark pattern,
based on progressively smaller ranges. It looks like a shark fin. Once
that pattern appears, a level is set by the highest point in the fin,
which is the high(-2). In the scan, I call that level "Sharkhigh." To
get a buy signal, the price has to close above that level within 25
days. If you want to plot "sharkhigh" over a chart with the price, you
can do it with the "BuyOK" part of the Metastock formula by plotting
this in the Expert Adviser:

Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);

Shark:=If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND


Ref(L,-1)>Ref(L,-2))=1,
{ try Ref(L,-1)>Ref(L,-2)), without the "=1"}
If(apex <= (Ref(H,-2)-(WB*Symmetry)) AND Apex >=
(Ref(L,-2)+(WB*Symmetry)) ,1,0),0);

Buyok:=Cross(C,ValueWhen(1,Shark=1,Ref(H,-2)));
{try Buyok:=ValueWhen(1,Shark=1,Ref(H,-2));}

Chk:=Cum(Buyok)-ValueWhen(1,Shark=1,Cum(Buyok));

ValidChk:=Alert(Shark=1,25);

Buy:= Buyok=1 AND Ref(Chk,-1)=0 AND ValidChk=1;

Buy OR Ref(Buy,-1) OR Ref(Buy,-2) OR Ref(Buy,-3) OR Ref(Buy,-4) OR


Ref(Buy,-5);

From: Brooke
=================================
For the pattern in the Indicator Builder:

Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);

If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND


Ref(L,-1)>Ref(L,-2)),
If(apex <= (Ref(H,-2)-(WB*Symmetry)) AND Apex >=
(Ref(L,-2)+(WB*Symmetry)) ,1,0),0);

That's like a resistance level that the price has to break through. It
lasts for 25 days or until a new Shark signal appears.

91
=================================

Combining Statistical and Pattern Analysis, Shark – 32 - Walter T.


Down, TASC 10/1998
Equis

First, choose Expert Adviser from the Tools menu in MetaStock 6.5.
Next, choose New and enter the following formulas:

Name:
Click the Name tab and enter "Shark – 32" in the Name field.

Trends:
Click the Trends tab and enter the following formulas in the Bullish
and Bearish fields.

Bullish: Mov(C,5,S)>Mov(C,20,S);

Bearish: Mov(C,5,S)<Mov(C,20,S);

Highlights:

Click the Highlights tab, choose New, and enter "3rd Bar" in the Name
field. Now change the color in the Color field to Blue. Finally, enter
the following formula in the Condition field, and then choose OK.

Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);
Shark:=If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND
Ref(L,-1)>Ref(L,-2))=1,If(Apex <=
(Ref(H,-2)-(WB*Symmetry)) AND Apex >= (Ref(L,-2)+(WB*Symmetry))
,1,0),0);
Shark;

Using the same method as above, enter the following 2 highlight


formulas.

Name: 2nd Bar


Color: Blue
Condition:
Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);
Shark:=If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND
Ref(L,-1)>Ref(L,-2))=1,If(Apex <=
(Ref(H,-2)-(WB*Symmetry)) AND Apex >= (Ref(L,-2)+(WB*Symmetry))
,1,0),0);

92
Ref(Shark,+1)=1;

Name: 1st Bar

Color: Blue
Condition:
Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);
Shark:=If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND
Ref(L,-1)>Ref(L,-2))=1,If(Apex <=
(Ref(H,-2)-(WB*Symmetry)) AND Apex >= (Ref(L,-2)+(WB*Symmetry))
,1,0),0);
Ref(Shark,+2)=1;

Symbols:
Click the Symbols tab, choose New and enter "Shark Buy" in the Name
field. Now enter the following formula in the Condition field.

Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);
Shark:=If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND
Ref(L,-1)>Ref(L,-2))=1,If(apex <=
(Ref(H,-2)-(WB*Symmetry)) AND Apex >= (Ref(L,-2)+(WB*Symmetry))
,1,0),0);
Buyok:=Cross(C,ValueWhen(1,Shark=1,Ref(H,-2)));
Chk:=Cum(Buyok)-ValueWhen(1,Shark=1,Cum(Buyok));
ValidChk:=Alert(Shark=1,25);

{Note* The above ValidChk variable makes the Shark signal valid for 25
periods. If the price does not cross above the High value of the base
within 25 periods, you will not receive a signal. You can change the
number of periods by changing 25 to the number of periods you desire.
*}

Buy:= Buyok=1 AND Ref(Chk,-1)=0 AND ValidChk=1;


Buy;

Click the Graphic tab. Change the symbol in the Graphic field to Buy
Arrow. Now change the color in the Color field to Green. Finally, type
"Buy" in the Label field, and then choose OK.

Using the Same method as above, enter the following Symbol formula.

Name: Shark Sell


Condition:
Symmetry:=.28;
Apex:=(H+L)/2;
WB:=Ref(H,-2)-Ref(L,-2);

93
Shark:=If((H<Ref(H,-1) AND L>Ref(L,-1) AND Ref(H,-1)<Ref(H,-2) AND
Ref(L,-1)>Ref(L,-2))=1,If(apex <=
(Ref(H,-2)-(WB*Symmetry)) AND Apex >= (Ref(L,-2)+(WB*Symmetry))
,1,0),0);

Sellok:=Cross(ValueWhen(1,Shark=1,Ref(L,-2)),C);
Chk:=Cum(Sellok)-ValueWhen(1,Shark=1,Cum(Sellok));
ValidChk:=Alert(Shark=1,25);

{Note* The above ValidChk variable makes the Shark signal valid for 25
periods. If the price does not cross below the Low value of the base
within 25 periods, you will not receive a signal. You can change the
number of periods by changing 25 to the number of periods you desire.*}

Sell:= Sellok=1 AND Ref(Chk,-1)=0 AND ValidChk=1;


Sell;
Symbol: Sell Arrow
Color: Red
Label: Sell

=========================================================
BUILDING METASTOCK SYSTEM TESTS
Here's an excellent short article from Jim Greening, showing how MetaStock system
tests can be built up . . .

This week I'm going to discuss my third MetaStock Profit System Test - 03_Tema
PDI - MDI, ADX (Vol Required). This test is based on Wilder's directional movement
indicators. As the MetaStock manual indicates, Wilder says a buy signal occurs when
PDI - MDI moves above zero and a sell signal occurs when PDI-MDI falls below
zero. I started with that thought and experimented a little. Wilder used 14 day periods
to calculate his PDI and MDI functions. Since I like Fibonacci numbers, I used 13
days instead. Also I like to smooth my indicators so I used Tema smoothing. My
custom PDI - MDI formula then became:

Tema PDI - MDI


Periods := Input("Enter Tema Smoothing Periods",8,55,13);
Tema(PDI(13) - MDI(13),Periods)

I started with the idea that I would take the PDI-MDI crossover of an optimized
number as my basic buy and sell trigger. However, this number did not have to be
zero and did not have to be the same for entering long and entering short. After a lot
of trial an error I decide -1, -3, or -5 would be my enter long number and -5, -13, or -
21 would be my enter short number. This makes sense since the market is biased to
the up side, so entering a little under zero would get us in a little earlier. Also down
moves tend to be fast an extreme and this would only let us in short for larger, faster
down moves which is what I wanted. Finally I wanted some way to reduce the
number of false signals and I wanted to do that with directional movement indicators
only so this test would be completely uncorrelated with my other tests.
For long positions, I notice that most up moves started when adx was low and that adx
climbed during the move to a max and then started to fall at the end of the move.

94
Therefore, I thought an adx max and min for a buy signal would help reduce false
signals. After some experimenting, I set the min at 8 and the max at 21. I also noticed
that most good buy points occurred when MDI and ADX were close together so I
decided that the difference between the two should be small. After more
experimenting, I decided on the following for my open long signal:

Open Long:
Alert(Cross(Fml("Tema PDI - MDI"),opt1),13) AND
MDI(13) - ADX(13) <= 4 AND
MDI(13) - ADX(13) >= -2 AND
ADX(13) >= 8 AND
ADX(13) <= 21

To close my open long position I wanted the PDI-MDI to be less than opt1. When a
stock starts to drop, the MDI starts to rise, so I wanted the MDI to be greater than a
certain number to close a position. Finally, since markets are biased upwards, I also
wanted the 55 day variable moving average to be dropping before I closed the
position. Therefore, the close long became:

Close Long:
Fml("Tema PDI - MDI") < opt1 AND
MDI(13) > 21 AND
LLV(Mov(L,55,VAR),5) = LLV(Mov(L,55,VAR),13)

To open a short position, I wanted the PDI-MDI to cross below a fairly high negative
number. I wanted confirmation in that the adx was still fairly high when that
happened. The answer was:

Open Short:
Alert(Cross(opt2,Fml("Tema PDI - MDI")),8) AND
ADX(13) > 34

To close the short position, I only wanted PDI-MDI to be greater than a certain
positive number. I don't like a lot of confirmations for closing shorts. With the bias
being up, you need to close shorts fast. My close Short and optimization became:
Close Short:
Fml("Tema PDI - MDI") > 13

Optimization:
Opt1: Min = -1 Max = -5 Step = 2
Opt2: Min = -21 Max = -5 Step = 8

That's it. Any comments or questions?

JimG
Are there weekly patterns in the stock market?
Do price pressures build up over the weekend that cause predictable distortions in the
stock market on Monday? If the market is up or down a certain number of days in a
row, what are the chances it will follow the trend the next day? Is the trend on

95
Monday reversed on Tuesday? To find out, we loaded our S&P 500 data back to
1980, and ran a test. The results were this - the trend on Monday (either up or down)
was reversed 55% of the time, a fairly significant result. This might tell us that the
weekend causes an emotional buildup that moves the market an excessive amount on
Monday, which is then corrected by Tuesday. Larger stocks, as represented by the
Dow Jones Industrial Average, reversed slightly less - 54% of the time. Small stocks,
as represented by the Russell 2000 (data back to 1990) showed the opposite pattern,
going with the trend 60% of the time.

In the futures markets, the US dollar (data back to 1990) reversed 54% of the time,
and the 30 year treasury bond (data back to 1987) reversed 53% of the time.

In recent years, the pattern has been less pronounced. In fact, if you study just the last
two years, you get reversals of 53% in the Dow, 52% in the S&P 100, a continuation
in the trend 50.5% of the time in the S&P 500 and a continuation 54% of the time in
the Russell 2000 . The US dollar has reversed 58% of the time in the last two years,
the CRB index 54% of the time, while other futures have shown continuation trends -
55% for gold, 54% for treasury bonds, and 55% for crude oil.

Next, we studied every possible price trend for the five day period. A nice Thursday
trend emerged - if Monday and Tuesday went one direction, and then Wednesday
reversed this trend, there was a 62% chance that Thursday would continue this
reversal (we’ll represent this as XXOO, where X just means one direction, not
necessarily up or down, and O means the other direction). If the first four days of the
week all moved in the same direction (XXXX), Friday had a 61% chance of doing the
same (XXXXX). And if Tuesday reversed Monday, but was then reversed by
Wednesday, and the trend continued Thursday, there was a 63% chance that Friday
would continue the trend set Wednesday (XOXXX).

The MetaStock formulas for the Tuesday calculation are included below. Formulas
for the remaining days of the week build on these formulas, and are too extensive to
include here (you need 2 formulas for Tuesday, 4 for Wednesday, 8 for Thursday, and
16 for Friday).

To build an exploration that looks for stocks with a high incidence of Tuesday
reversal, simply put the formula "Tuesday % occurrence. of XX vs. XO" in a column
in the Explorer, run an exploration on all of your securities, then sort by the
aforementioned formula.

======================
Formula "Tuesday XX Pattern"

{ Looks for XX pattern, returns +1 if it finds it }


If(Ref(DayOfWeek(),-2) = 5 {2 days ago was Fri} AND
Ref(DayOfWeek(),-1) = 1 {Yesterday was Mon}
AND
DayOfWeek() = 2 {Today is Tuesday}
AND { Either both days were up or down }
((Ref(CLOSE,-2) > Ref(CLOSE,-1) AND
Ref(CLOSE,-1) > CLOSE ) OR

96
(Ref(CLOSE,-2) < Ref(CLOSE,-1) AND
Ref(CLOSE,-1) < CLOSE )) ,
+1, { +1 if XX pattern }
0) { Otherwise 0 }

======================
Formula "Tuesday XO Pattern"

{ Looks for XO pattern, returns +1 if it finds it }


If(Ref(DayOfWeek(),-2) = 5 {2 days ago was Fri} AND
Ref(DayOfWeek(),-1) = 1 {Yesterday was Mon}
AND
DayOfWeek() = 2 {Today is Tuesday}
AND { Tuesday is opposite direction of Monday }
((Ref(CLOSE,-2) > Ref(CLOSE,-1) AND
Ref(CLOSE,-1) < CLOSE ) OR
(Ref(CLOSE,-2) < Ref(CLOSE,-1) AND
Ref(CLOSE,-1) > CLOSE )) ,
+1, { +1 if XO pattern }
0) { Otherwise 0 }

======================
Formula "Tuesday % occurrence. of XX vs. XO"
{ Gives the % occurrence of XX (that Tuesday goes the same direction as Monday) }

Cum(Fml("Tuesday XX pattern"))/
(Cum(Fml("Tuesday XX pattern")) + Cum(Fml("Tuesday XO pattern")) ) * 100

======================

Note that unchanged days, either Monday or Tuesday, are ignored in the calculations.

by John DeBry

Kaufman's Adaptive RSI

MetaStock formula derived from calculations in Trading Systems and Methods, Third
Edition, by Perry J. Kaufman.
This formula adapts the standard RSI to a smoothing constant.

Period := Input("Period",1,10000,20);

sc := Abs(RSI(Period)/100 - .5)*2;

If(Cum(1) <= Period, CLOSE,


PREV + sc*(CLOSE - PREV))
Market Pressure - Ultimate:

97
This is the basic calculation:
If today's close is greater than yesterdays close and
today's volume is greater than yesterdays volume, write down today's volume * close,
otherwise,
If today's close is less than yesterdays close and
today's volume is less than yesterdays volume, write down today's volume as a
negative number * close, otherwise write down 0.

Then add up the past 7 days and * 4, add this to


the past 14 days total and * 2, add this to
the past 28 days total.
Plot this grand total in your chart for each new trading day.

Simple Interpretation:
Market Pressure - Ultimate can show divergences with the instrument it is plotted
against.
It may show signs of support and resistance when the indicator hits areas of
support/resistance on its own graph.
Comparing rates of change/moving averages of the indicator against that of the
instrument may reveal accumulation/distribution pressures.

Metastock code for Market Pressure - Ultimate:

Sum(If(C > Ref(C,-1)


AND V > Ref(V,-1),
V * C,
If(C < Ref(C,-1)
AND V < Ref(V,-1),
Neg(V) * C,0)),7) * 4 +

Sum(If(C > Ref(C,-1)


AND V > Ref(V,-1),
V * C,
If(C < Ref(C,-1)
AND V < Ref(V,-1),
Neg(V) * C,0)),14) * 2 +

Sum(If(C > Ref(C,-1)


AND V > Ref(V,-1),
V * C,
If(C < Ref(C,-1)
AND V < Ref(V,-1),
Neg(V) * C,0)),28)

Changing Ways Accumulation/Distribution:

This is the calculation for the first formula (Today's Change):


Today's close - yesterdays close

98
This is the main formula, incorporating the first calculation:
If today's change (1st formula) is greater than a 7 day exponential moving average of
today's change and today's close is greater than yesterdays close, write down today's
close + today's volume, otherwise,
If today's change is less than a 7 day exponential moving average of today's change
and today's close is less than yesterdays close, write down the negative value of
today's close + today's volume, otherwise write down 0.

Then add up all the days values and keep a cumulative running total for each new
trading day.

Simple Interpretation:
Changing Ways Accumulation/Distribution can show divergences against the
instrument.
When compared against volume activity, it can show what impact a day of high
turnover had on the share price for the coming periods. This is to say that if a day had
high volume and there was little movement in the indicator alongside this, then you
can suggest that all the volume for that day was absorbed into the price and there is
less likelihood of buying/selling pressure in that day taking hold in the market in
future trading days.

Metastock code for Changing Ways Accumulation/Distribution:

Cum(If(Fml( "Today's Change" ) > Mov(Fml( "Today's Change" ),7,E) AND C >
Ref(C,-1),
C + V,
If(Fml( "Today's Change" ) < Mov(Fml( "Today's Change" ),7,E) AND C < Ref(C,-
1),
Neg(C + V) ,0)))

Where Fml( "Today's Change" ) = c - ref(c,-1)

Front Weighted 36 Day Moving Average:

This indicator requires 3 sub calculations and then the totalling of all 3 to get the final
indicator:

This is the basic calculation:


Take the closing prices of your instrument 34 days ago - 26 days ago (inclusive),
multiply each daily value by 0.01 and write each value down.
Then take the closing prices of your instrument 25 days ago - 18 days ago (inclusive),
multiply each daily value by 0.02 and write each value down.
Then take the closing prices of your instrument 25 days ago - 18 days ago (inclusive),
multiply each daily value by 0.02 and write each value down.
Then take the closing price of your instrument 17 days ago and multiply by 0.03 ad
write the value down.
Then take the closing price of your instrument 16 days ago - 8 days ago (inclusive),

99
multiply by 0.031 and write each value down.
Then take the closing price of your instrument 7 days ago - 6 days ago (inclusive),
multiply by 0.006 and write each value down.
Then take the closing price of your instrument 5 days ago - 1 day ago (inclusive),
multiply by 0.07 and write each value down.
Then take the closing price of your instrument today, multiply by 0.079 and write this
value down.

Finally, add up all the values that you wrote down and plot the value on the chart,
repeat this for every new trading day.

Simple Interpretation:
Front Weighted 36 Day Moving Average is similar to all other moving averages. The
interpretation is just as with all others, the trend is up when prices are above the
moving average and the trend is down when prices are below the moving averages.
This particular variation attempts to weight the data at the front more than that at the
back, with a sliding scale for each trading days value.

Front Weighted 36 Day Moving Average:

Fml( "1FrontWeighted36BarMA1" ) +
Fml( "2FrontWeighted36BarMA2" ) +
Fml( "3FrontWeighted36BarMA3" )

Where Fml( "1FrontWeighted36BarMA1" ) =


0.01 * Ref(P,-34) +
0.01 * Ref(P,-33) +
0.01 * Ref(P,-32) +
0.01 * Ref(P,-31) +
0.01 * Ref(P,-30) +
0.01 * Ref(P,-29) +
0.01 * Ref(P,-28) +
0.01 * Ref(P,-27) +
0.01 * Ref(P,-26) +
0.02 * Ref(P,-25) +
0.02 * Ref(P,-24) +
0.02 * Ref(P,-23) +
0.02 * Ref(P,-22) +
0.02 * Ref(P,-21) +
0.02 * Ref(P,-20) +
0.02 * Ref(P,-19) +
0.02 * Ref(P,-18)

Where Fml( "2FrontWeighted36BarMA2" ) =


0.03 * Ref(P,-17) +
0.031 * Ref(P,-16) +
0.031 * Ref(P,-15) +
0.031 * Ref(P,-14) +
0.031 * Ref(P,-13) +
0.031 * Ref(P,-12) +

100
0.031 * Ref(P,-11) +
0.031 * Ref(P,-10) +

0.031 * Ref(P,-9) +
0.031 * Ref(P,-8) +
0.006 * Ref(P,-7) +
0.006 * Ref(P,-6) +
0.07 * Ref(P,-5) +
0.07 * Ref(P,-4) +
0.07 * Ref(P,-3) +
0.07 * Ref(P,-2)

Where Fml( "3FrontWeighted36BarMA3" ) =


0.07 * Ref(P,-1) +
0.079 * P

Excel Confidence %:

This is the calculation:

Take toadies volume * 50 and find the square root of that number. Then divide 2.5 by
your result. Then take the result of dividing by 2.5 and * today's close. Write this
figure down. Then plot a 10 day moving average of this figure. This is the
fundamental calculation which we shall call a.

Take the value for a and take it away from the lowest value of itself over the past 5
days. Add up these results for the past 3 days. This number is called b.

Now take the highest value for a over the past 5 days and subtract the lowest value for
a, also over the past 5 days. Call this number c.

Finally, divide b by c and multiply the answer by 100. (phew!)

Simple Interpretation:
Excel Confidence % should oscillate between 0 and 100, usually at the extreme ends
of the scale. A value of 0 indicates no confidence in the market going up, whilst 100
indicates perfect confidence in the market going up. Although this obviously isn't the
holy grail of indicators, it does offer some insight into what the market is thinking and
how one can measure investor sentiment.
You might like to add a slower version of this (just increase the 3 day and 5 day
calculations to something you believe to be appropriate - try 7 & 15) and trade the
crossovers, as with stochastics.
You can also just trade the values ie 90 or higher, buy, 10 or lower, sell.

Metastock code for Excel Confidence %:

(Sum(
Mov(C * (2.5/ Sqrt(50 * V)),10,S)-
LLV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5), 3 ) /
Sum(

101
HHV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5) -
LLV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5), 3) ) * 100

BULLISH ENGULFING PATTERN

ColA: CLOSE

Filter BarsSince(EngulfingBear())<=5 AND BarsSince(ROC(C,60,%)>15)<=5 AND


BarsSince(Stoch(9,1)>90)<=5

Filter enabled Yes

Periodicity Daily

Records required 1300

BEARISH ENGULFING PATTERN

Col A: CLOSE

Filter BarsSince(EngulfingBull())<=5 AND BarsSince(ROC(C,60,%)<-15)<=5


ANDBarsSince(Stoch(9,1)<10)<=5

Filter enabled Yes

Periodicity Daily

Records required 1300

UP 20% ON DOUBLE AVERAGE VOLUME

Col A: CLOSE

Col B:ROC(C,5,%)

Filter ROC(C,5,%)>=20 AND Mov(V,5,S)>=(2*Ref(Mov(V,60,S),-5))

Filter enabled Yes

Periodicity Daily

Records required 1300

DOWN 20% ON DOUBLE AVERAGE VOLUME

102
Col A: CLOSE

Col B: ROC(C,5,%)

Filter ROC(C,5,%)<=-20 AND Mov(V,5,S)>=(2*Ref(Mov(V,60,S),-5))

Filter enabled Yes

Periodicity Daily

Records required 1300

CROSS ABOVE 200 MA ON TWICE AVERAGE VOLUME

Filter (C>Mov(C,200,S) AND Ref(C,-5)<Ref(Mov(C,200,S),-5)) AND C>5 AND


V>Mov(V,200,S)*2

CROSSING BELOW 200 DAY MA ON DOUBLE AVERAGE VOLUME

Filter (C<Mov(C,200,S) AND Ref(C,-5)>Ref(Mov(C,200,S),-5)) AND C>5 AND


V>Mov(V,200,S)*2

CONSOLIDATION OVER 16 WEEKS

Col A: CLOSE

Filter Fml("congestion index") <= 10 AND BarsSince(Fml("congestion index")>10) >


0

Filter enabled Yes

Here is the "congestion index" formula:

((HHV(C,80)-LLV(C,80))/LLV(C,80))*100

CONSOLIDATION BREAKOUT, UPSIDE


Col A: CLOSE

Filter: Fml("Consolidation breakout (upside)") = 1

Filter enabled: Yes

CONSOLIDATION BREAKOUT DOWNSIDE

103
If(Ref(Fml("congestion index"),-5),<,10,

{and} If(Fml("congestion index"),>=,10,

{and} If(CLOSE,>,Ref(HHV(C,80),-5),

{and} If(Mov(V,5,S),>=,1.5*(Ref(Mov(V,60,S),-5)),

+1,0),0),0),0)

Stocks breaking out of consolidation (downside)

Col A: CLOSE

Filter: Fml("Consolidation breakout (downside)") = 1

Filter enabled: Yes

Here is the "consolidation breakout(downside)" formula:

If(Ref(Fml("congestion index"),-5),<,10{%},

{and} If(Fml("congestion index"),>=,10{%},

{and} If(CLOSE,<,Ref(LLV(C,80),-5),

{and} If(Mov(V,5,S),>=,1.5*(Ref(Mov(V,60,S),-5)),

+1,0),0),0),0)

VOLATILITY OVER 16 WEEKS

Col A: CLOSE

Col B: Vol(10,80)

Filter: Vol(10,80)>200

Filter enabled: Yes

GAIN BY %

Col A: CLOSE

Col B: ROC(C,5,%)

104
Filter: (ROC(C,5,%)>10 OR ROC(C,5,%)<-10) AND C>5

Filter enabled: Yes

BIGGEST LOSERS

Col A: CLOSE

Col B: ROC(C,5,%)

Filter: (ROC(C,5,%)>10 OR ROC(C,5,%)<-10) AND C>5

Filter enabled: Yes

OVERBROUGHT / OVER SOLD


Col A: CLOSE

Col B: Fml("ob/os summation")

Filter: Fml("ob/os summation") > 450 OR Fml("ob/os summation") < -50

Filter enabled: Yes

Here is the "ob/os summation" formula:

RSI(25)+Stoch(25,3)+Mo(25)+CCI(25)

ELLIOTT WAVE IDFENTIFICATION

As far as using MetaStock for identifying waves, use a 5/34 histogram for
finding wave 4, the end of wave 3 and for help with identifying wave 1/2,
which apparently Advanced Get uses extensively. You can write MetaStock
explorations/templates/experts, etc., with this indicator; e.g.,
explorations to find the peaks and troughs of the 5/34 histogram.

The version of the indicator I use in MetaStock v6.52 is:

Mov(OscP(5,34,E,$),5,S)

-150 days minimum of data.

The peaks of the histogram help identify waves 1, 3 and 5 and troughs for
waves 2 and 4. Use MetaStock line studies (both trendlines, channels and
fib retracements) for additional wave identification/analysis. Of course,

105
you can label the waves with the text box.

from Kevin Campbell

WILDERS ATR FROM EQUIS


{The actual ATR does not use a simple moving average. Welles Wilder uses
his own smoothing (a modified exponential average) which is the function
named "Wilders" in MetaStock. Try your formula this way:}

periods:=Input("ATR Periods?",1,100,10);
TH:=If(Ref(C,-1) > H,Ref(C,-1),H);
TL:=If(Ref(C,-1) < L,Ref(C,-1),L);
TR:=TH-TL;
Wilders(TR,periods)

{Equis Support}

ATR CUSTOM INDICATOR

periods:=Input("ATR Periods?",1,100,10);
TH:=If(Ref(C,-1) > H,Ref(C,-1),H);
TL:=If(Ref(C,-1) < L,Ref(C,-1),L);
TR:=TH-TL;
Mov(TR,periods,S)

{from Yngvi Hardarson}

MTF TENDENCY UPDATE

{Multiple Time Frame - Tendency 5/23/99}


{This will plot 1 for Bullish
-1 for Bearish}
dw:=DayOfWeek();
Fw:=If(dw<Ref(dw,-1),1,0);
Mt:=If(Fw=1 AND Ref(dw,-1)<>5,
{then}Ref(C,-1)- FmlVar("MTF-Fixed Balance Point","DWP"),
{else}If(dw=5,
{then}C-((HighestSince(1,Fw=1,H)+
LowestSince(1,Fw=1,L)+C)/3),
{else}0));
If(Mt>0,1,If(Mt<0,-1,0));

{from Adam Hefner}

106
GUPPY MMA EXPLORATION FROM TRADING TACTICS, part 2

NOTE This EXPLORATION uses the results of several INDICATOR FORMULAS.


You must create the INDICATORS first before running the exploration. Also,
depending on your system you may have some problems importing this into early
versions of Metastock 7.

Ref(C,-1)

Ref(C,-2)

Fml("mma 3/30") +Fml("mma 5/35") +Fml("mma 8/40") + Fml("mma


10/45")+Fml("mma 12/50")+Fml("mma 15/60")

Ref(Fml("mma 3/30") +Fml("mma 5/35") +Fml("mma 8/40") + Fml("mma


10/45")+Fml("mma 12/50")+Fml("mma 15/60"),-1)

Ref(Fml("mma 3/30") +Fml("mma 5/35") +Fml("mma 8/40") + Fml("mma


10/45")+Fml("mma 12/50")+Fml("mma 15/60"),-2)

When(colD,>,0) AND When(colE,<=,0)

PERFORMANCE INTRA DAY AND DAILY

ColA:C {label CLOSE}


ColB:O {label OPEN}
ColC:Sub(C,O) / O {label Intr.dy%}
ColD:Sub(C,Ref(C,-1)) / Ref(C,-1) {label 1 dy %}
ColE:Sub(C,Ref(C,-2)) / Ref(C,-2) {label 2 dy %}
ColF:Sub(C,Ref(C,-3)) / Ref(C,-3) {label 3 dy %}
Filter: O>.2 AND
C<.3 AND
C>.2

Filter: enabled
Periodicity: Daily
Records required: 5

----------------------------
Patrick McDonald

GAP UP SYSTEM WITH DELAYED EXIT

Enter long
GapUp()

Close long
Ref(GapUp(),-5)

Initial equity 10000

107
Positions Long and short
Trade price Open
Trade delay 1
Entry commission 0%
Exit commission 0%
Interest rate 0%
Margin req. 100%

ELLIOTT OSCILLATOR

Mov(C,5,S)-Mov(C,35,S)

{from Jan Robert Wolansky}

{TIMESERIES TRIX - by Joe Luisi}

{published in S&C - TASC article "Playing Trix" by Joe Luisi (June 1997) and
to be used on weekly data}

CLA:=TRIX(3);
CLB:=Ref(TRIX(3),-1);
CLC:=Mov(TRIX(3),8,TIMESERIES);
CLD:=Ref(Mov(TRIX(3),8,TIMESERIES),-1);
SHORT:=When(CLA,>,CLC) AND When(CLB,<,CLD) AND
When(CLA,<,0)AND When(CLA,>,-2);
LONG:=When(CLA,<,CLC) AND When(CLB,>,CLD) AND
When(CLA,>,0)AND When(CLA,<,+2);
If(LONG>0,+1,
If(SHORT>0,-1,PREVIOUS))

WEEKLY TRIX MOVING AVERAGE TEST

COLA: TRIX(3)
COLB: REF(TRIX(3),-1)
COLC: MOV(TRIX(3),8,TIMESERIES)
COLD: REF(MOV(TRIX(3),8,TIMESERIES),-1)
COLE: C

Filter enabled:yes

when(cola,>,colc)and when(colb,<,cold)and when(cola,<,0)and


when(cola,>,-2)

from A. J. Maas

ROC MOVING AVERAGE SYSTEM TEST

ENTER LONG:

108
ROC(Mov(C,12,E),1,%)>0 AND ROC(Mov(C,60,E),1,%)>0

EXIT LONG:
(ROC(Mov(C,12,E),1,%)<0 AND ROC(Mov(C,60,E),1,%)>0)
OR
(ROC(Mov(C,12,E),1,%)>0 AND ROC(Mov(C,60,E),1,%)<0)

SHORT:
ROC(Mov(C,12,E),1,%)<0 AND ROC(Mov(C,60,E),1,%)<0

EXIT SHORT:
(ROC(Mov(C,12,E),1,%)<0 AND ROC(Mov(C,60,E),1,%)>0)
OR
(ROC(Mov(C,12,E),1,%)>0 AND ROC(Mov(C,60,E),1,%)<0)

{Ref(c,-1) gives yesterday's close today. So all values are shifted to the
right!}

{from Onno Goedknegt}


DAYS SINCE CROSSOVER
{place formula in filter section of explorer, making sure that formulas
within quotes are valid indicators}

BarsSince(Cross(45, Fml( "Stochrsi (14)" )))>


BarsSince(Cross(Fml( "Stochrsi (7,3)" ),72)) AND
Ref(BarsSince(Cross(45,Fml( "StochRSI (14)" ))) <
BarsSince(Fml( "staters (7,3)")>72), -1)

{from Stefan Schittko}


ANTI TRIGGER - L.B. Raschke (For MetaStock v6.5)
----------------------------------------------------------------------------
-------
Original formula based on L.B. Raschke's "Street Smarts"
book's Quick Indicator Articles. Re-written by Ton Maas.
==============================================
{FUNCTIONS-IND-REFERENCE-INDEX:
FF=FASTLINE,SS=SLOWLINE,SETBARS=3DAYMOVAVE,
ENTRYADD=+1,EXITADD=+1}
{FUNCTIONS-VAR-REFERENCE-INDEX:
BBUY=(VAR),SSELL(VAR),CBUY(VAR),CSELL(VAR),FF(VAR),SS(VAR),
LXSTOP(VAR),SXSTOP(99999),MP(VAR)}
{FUNCTIONS-MISC-REFERENCE-INDEX:
AT0BBUY =BULLLONG
AT0SSELL =BEARSHORT
AT0CSELL =CLOSEBEARSHORT
AT0CBUY =CLOSEBULLLONG
AT0MP =MARKETPOSITION (-1=LONG,+1 SHORT)
AT0LXSTOP=CLOSELONGEXITLEVEL(STOPLOSS)
AT0SXSTOP=CLOSESHORTEXITLEVEL(STOPLOSS)}

109
{INDICATOR NAME : ANTI TRIGGER}

{THE FORMULA (+REQUIRED FUNCTIONS) FOR THE ANTI TRIGGER


INDICATOR}
AT0SETBARS:=3;
AT0FF:=Stoch(7,AT0SETBARS);
AT0SS:=Mov(Stoch(7,AT0SETBARS),10,E);
AT0ENTRYADD:=+1;
AT0EXITADD:=+1;
AT0CSELL:={use in expadv or systest}{for RT del the REF-function}
If(AT0FF>Ref(AT0FF,-1) AND AT0SS<Ref(AT0SS,-1),C+1,0);
AT0CBUY:={use in expadv or systest}{for RT del the REF-function}
If(AT0FF<Ref(AT0FF,-1) AND AT0SS>Ref(AT0SS,-1),C+1,0);
AT0BBUY:={use in expadv or systest}{for RT del the REF-function}
If(AT0CBUY>AT0SETBARS,H+AT0ENTRYADD,99999);
AT0SSELL:={use in expadv or systest}{for RT del the REF-function}
If(AT0CSELL>AT0SETBARS,L-AT0ENTRYADD,0);
AT0MP:={use in expadv or systest}If(AT0BBUY<99999, -1,If(AT0SSELL>0,1,0));
{AT0LXSTOP:=}{use in expadv or systest}{for RT del the REF-function}
{IF(REF(AT0MP,-1)<1 OR (REF(AT0BBUY,-1)<99999 AND
H>REF(AT0BBUY,-1)), L-AT0EXITADD,0);}
{AT0SXSTOP:=}{use in expadv or systest}{for RT del the REF-function}
{IF(REF(AT0MP,-1)>-1 OR (REF(AT0SSELL,-1)>0 AND
L<REF(AT0SSELL,-1)), H+AT0EXITADD,0);}
AT0MP
============================================================
RECURSIVE MOVING TREND AVERAGE

Lb:=Input("Look-Back Period?",3,100,21);
Ty:=Input("1=C 2=H 3=L 4= Median Price",1,4,1);
Tv:=If(Ty=1,C,If(Ty=2,H,If(Ty=3,L,MP())));
Alpha:=2/(LB+1);
Bot:=(1-Alpha)*(If(Cum(1)<Lb,Tv,PREV))+Tv;
RMTA:=(1-Alpha)*(If(Cum(1)<Lb,Tv,PREV))+
(Alpha*(Tv+Bot-Ref(Bot,-1)));
RMTA

{from Adam Hefner}

TSF OPTIMISED TRADING SYSTEM FOR METASTOCK

Enter long:
Cross(opt1,((CLOSE-Ref(TSF(C,opt3),-1))/CLOSE*100))

Close long:
Cross(((CLOSE-Ref(TSF(C,opt3),-1))/CLOSE*100),opt2)

110
Enter short:
Cross(((CLOSE-Ref(TSF(C,opt3),-1))/CLOSE*100),opt2)

Close short:
Cross(opt1,((CLOSE-Ref(TSF(C,opt3),-1))/CLOSE*100))

opt 1: zero to -2 (with .1 step)


opt 2: zero to +2 (with .1 step)
opt 3: 2 to 8 (with 1 step)

{I use this for futures and the above parameters (optimized settings) keep
it in the ballpark. If you are applying it to equities (or commodities),
it always makes sense to look at the indicator and understand the outside
parameters for each of its "steps". It makes no sense to limit your outside
limits to -2 and +2 if the TSF oscillates between -8 and +8. So do a little
homework on the "outside" limits of the indicator and then
optimize accordingly. from Steve Karnish.}

THE END POINT MOVING AVERAGE

{The End Point Moving Average was introduced in the October 95 issue of
Technical Analysis of Stocks & Commodities in the article "The End Point
Moving Average", by Patrick E. Lafferty. The exact formula for the End Point
Moving average is as follows:}

( 14 * Sum( Cum( 1 ) * C,14 ) - Sum( Cum( 1 ),14) * Sum( C,14) ) / (14


* Sum( Pwr( Cum( 1 ),2),14 ) - Pwr( Sum( Cum( 1 ),14 ),2 ) ) * Cum( 1 )
+ (Mov(C,14,S) - Mov( Cum( 1 ),14,S) * (14 * Sum( Cum( 1 ) * C,14) -
Sum( Cum( 1 ),14 ) * Sum( C,14) ) / (14 * Sum( Pwr( Cum( 1 ),2 ),14) -
Pwr( Sum( Cum( 1 ),14 ),2 ) ) )

{The above formula plots the last value of a linear regression line of the
previous 14 periods. The Time Series Forecast (TSF) takes this value and the
slope of the regression line to forecast the next day and then plots this
forecasted price as today's value. from Equis.}

METASTOCK ADJUSTABLE TRADING BANDS

Using the default values used in the formulas, I have found that these upper
and lower bands provide effective risk control while trading. The upper band
can be used as the extreme point to get rid of shorts and vice versa. In
fact, prices tend to remain above both the bands while the market is in a
strong uptrend, and prices remain below the bands in a downtrend. During
short-term range-bound markets, they tend move between the bands. I have
found this idea in Tushar Chande's "New Technical Trader". Since you have

111
studied ATR so thoroughly, it would be be very nice if you could comment on

them. Can be made into a template for easier usage.

from Rajat K Bose

Upper Band

Prd1:=Input("ATR Period",5,20,5);
Prd2:=Input("Period for Highest High Value",5,20,10);

(HHV(LLV(L,Prd1)+ATR(Prd1),Prd2))

Lower Band

Prd1:=Input("ATR Period",5,20,5);
Prd2:=Input("Period for Lowest Low Value",5,20,10);

(LLV(HHV(H,Prd1)-ATR(Prd1),Prd2))

Customisable StochRSI

from Nicholas Kormanik

The formula I've adopted was put on the Silicon Investor web site thread by
'bdog'. Basically, I just leave the Slowing Periods (mp3) to 1, so it
really plays no part in things. However, if somebody presents a good
argument for using other than 1 ... hey, I'm amenable.

Chande, the original inventor, didn't use a moving average on the whole
thing. Chande's result was therefore sort of choppy. I guess along the way
people decided to add the EMA Periods to smooth things out.

Here's the MSWin formula:

mp1:=Input("RSI Periods",1,377,13);
mp2:=Input("Stoch Periods",1,377,13);
mp3:=Input("Slowing Periods",1,377,1);
mp4:=Input("EMA Periods",1,377,5);

Mov(Sum((RSI(mp1)-
LLV(RSI(mp1),mp2)),mp3)/Sum((.0000001+(HHV(RSI(mp1),mp2)-(
LLV(RSI(mp1),mp2)))),mp3),mp4,E)*100

Now, from various posts, etc., the following parameters (mp1, mp2 and mp4)

112
*seem* to be the one's recommended. I'm trying to further find consensus
among users of StochRSI on what really appears to work for them.

StochRSI Set
--------------------
5 -- 5 -- 3
8 -- 8 -- 5
13 -- 13 -- 13
21 -- 15 -- 13
21 -- 21 -- 13
34 -- 34 -- 13
55 -- 55 -- 21
89 -- 13 -- 34
89 -- 89 -- 21
233 -- 233 -- 34
52 Week Hi-Lo Exploration

ColA: {Close}C;
ColB: {52-week High} HighestSince(1, (DayOfMonth()=08 AND Month()=05
AND Year()=1998), H);
ColC: {52-week Low} LowestSince(1, (DayOfMonth()=08 AND Month()=05 AND
Year()=1998), L);

{Choose one of these filters}


{Filter 1:} ColA >= (0.9*(ColB))
{Filter 2:} ColB >= 2*ColC

{If you want both the conditions to be satisfied in the same query, just
join the two filters by the AND operator:}

Filter: (ColA >= (0.9*(ColB)) AND ColB >= ColC)

{One problem with the 52-wk High and 52-wk Low formula--every day you've got
to change the values for dayofmonth(), Month() and Year() functions. The
formula given above assumes that you would be running the query on May 07,
1998. Change the values of the above functions accordingly.}

{from Rajat Bose}

TRAILING STOP LOSS INDICATOR

If(cum(1)=1,
{then} Close,
{else} If((C*1.1) <= PREV,
{then}(C*1.1),
{else} PREV));

113
{from Adam Hefner}

{Regarding the Recursive Moving Trendline System, I ended up making an


oscillator out of it (subtracting the ema from the rta). If you wish to try
"tuning" it in MetaStock, you could try different entry levels from the
oscillator. For example, go long when TOSC crosses from below -2, or go
short when TOSC crosses from above +2. }

{TOSC}
Lb:=Input("Look-Back Period?",3,100,21);
Ty:=Input("1=C 2=H 3=L 4= Median Price",1,4,1);
Tv:=If(Ty=1,C,If(Ty=2,H,If(Ty=3,L,MP())));
Alpha:=2/(LB+1);
Bot:=(1-Alpha)*(If(Cum(1)<Lb,Tv,PREV))+Tv;
RMTA:=(1-Alpha)*(If(Cum(1)<Lb,Tv,PREV))+
(Alpha*(Tv+Bot-Ref(Bot,-1)));
TOSC:=RMTA-Mov(Tv,lb,E);
TOSC;

{NOTE: this code will work slowly because of all of the "PREV" functions.
from Adam Hefner.}

{Single 60 Day Period BreakOut Signal Indicator}

ACol:= C;
BCol:= Ref(HHV(H,59), -1);
CCol:= HHV(H,60);
SSDPBOS:= (ACol>BCol) AND (Ref(C,-1)<BCol) AND
(H=CCol);
SSDPBOS

{from Ton Maas}

METASTOCK -- STOCKS CLOSING ABOVE 60 DAY HIGH

To find the securities that have closed above their high today (the last
trading day in the database) for the first time, I have written this
MetaStock Explorer.

ColA: {Close) C
ColB: {Previous 60-day High} Ref(HHV(H,60), -1)
ColC: {Current 60-day High} HHV(H,60)
ColD: {Volume} V
Filter: (colA>colB) AND (Ref(C,-1)<Ref(HHV(H,60), -1)) AND
(H=HHV(H,60))

114
This formula does two things:

1) It lists only those securities which have met the required conditions
only on the last trading day.
2) The new 60-day high must have taken place only on the last trading day.

from Rajat Bose

{Stocks Closing Above 60 Day Highs}

{closing above the 60-day high of the close}

close>ref(hhv(close,60),-1)

if you want those that are {closing above the 60-day intraday high}

close>ref(hhv(high,60),-1)

{from Debra Orlow}

SINE WEIGHTED MOVING AVERAGE

{from Equis}

PI:=3.1415926;
SD:=180/6;
S1:=Sin(1*180/6)*C;
S2:=Sin(2*180/6)*Ref(C,-1);
S3:=Sin(3*180/6)*Ref(C,-2);
S4:=Sin(4*180/6)*Ref(C,-3);
S5:=Sin(5*180/6)*Ref(C,-4);
Num:=S1+S2+S3+S4+S5;
Den:=Sin(SD)+Sin(2*SD)+Sin(3*SD)+Sin(4*SD)+Sin(5*SD);
Num/Den

I use the peak and trough function in MetaStock to show support and
resistance levels. It could also be used as a trailing stoploss method.

from Anil Chugani

===================================
SUPPORT AND RESISTANCE LEVELS

AVd:=If(CLOSE>Ref(Peak(1,H,1) ,-1),

115
{then}1,
{else}If(CLOSE<Ref(Trough(1,L,1),-1),

{then}-1,
{else}0));
ANv:=ValueWhen(1,AVd<>0,AVd);
SuRe:=If(ANv=-1,
{then}Peak(1,H,1),
{else}Trough(1,L,1));
SuRe;

{StochCMO}

mp1:=Input("RSI Periods",1,377,13);
mp2:=Input("Stoch Periods",1,377,13);
mp3:=Input("Slowing Periods",1,377,1);
mp4:=Input("EMA Periods",1,377,5);

Mov(Sum((CMO(c,mp1)-
LLV(CMO(c,mp1),mp2)),mp3)/Sum((.0000001+(HHV(CMO(c,mp1),
mp2)-(LLV(CMO(c,mp1),mp2)))),mp3),mp4,E)*100

25x25 BOND SYSTEM METASTOCK FORMAT

This system is provided free to people who join the System Traders Club. It is a
profitable Bond Trading System that we supply in order to demonstrate the quality of
our work, and as an example of the documentation that comes with each of our
systems.

Gary Randal mailto:Randall_Gary@tmac.com has ported this system into MetaStock


format. His comments and code for MetaStock follow our normal system
Documentation. A Rrade by Trade Report concludes the document

"25 x 25" BOND TRADING SYSTEM


by Charles LeBeau and Terence Tan

Introduction

In this report we will present several useful concepts for trading the Bond futures
markets, and illustrate these concepts with a Bond trading system that we have called
the "25 x 25". The "25 x 25" system is a long-only trend-following system designed
for the Bond market which has made hypothetical profits of $53,000 over the last 10
years of historical data, with an accuracy rate of 76%.

Aims of the System Traders Club

116
Before we present the details of the system, we will review some of the goals we hope
to achieve for the System Traders Club.

First, we do not hope to reveal any "holy grails" to trading. Many of the systems that
you will see in the System Club reports include indicators that you may already be
familiar with, or that can be easily programmed into the computer. In addition, you
will find that many of these systems are not perfect: they will all have drawdowns,
and none of them are 100% accurate over the long run. However, we think they
deserve serious consideration for actual real-time trading applications. We realize that
in the business of trading the futures markets there is no single method that makes
money automatically. We believe that a combination of logical system concepts and
reasonable entry and exit strategies greatly increases the probability of success in
trading. We hope to be able to communicate to you, through these reports, many of
the concepts that we have learned over the years.

Second, we hope that these reports will serve both an informative as well as a
practical purpose. We will share with you lessons that we have accumulated over the
years regarding trading strategies and techniques that have worked in various markets,
and the logic behind them. You may also want to view the systems presented as
illustrations of general principles and concepts in systematic trading of the futures
markets. We hope that you may also apply these concepts to your own favorite
markets and time-frames. We would welcome any feedback you may have on
possible improvements and different applications of these systems.

Third, we intend to provide many different systems and market combinations in our
reports. Multiple systems can be combined together in a portfolio to generate more
frequent trades and higher returns than any single system. We believe in
diversification; but we also realize that diversification is a function of personality and
preference. For this reason, we will be offering many different types of systems, from
which you will be able to select systems that suit your personality and preference and
combine them into your own diversified trading portfolio.

"25 x 25" System Rules

We will concisely present the system rules first, and then elaborate and explain the
concept and logic behind some of the more important trading techniques represented
in the system:

To go long in the Bond market, three conditions must be met.

1. The 14-day +DI must be above the 14-day -DI.

2. The 14-day ADX must be above 20.

3. The 4-day RSI must be below 50.

If these three conditions are met then buy tomorrow only if and when prices rise 18
ticks (18/32) above today's close. Enter on a buy stop order.

117
After a trade has been entered, place a sell stop at whichever of the positions below
are closest to the market price.

1. A stop order at $2,500 below the entry price.

2. Or a stop order at the lowest low of the last 25 days.

3. After 25 days (count entry day as day 1), change stop #2 from the lowest low of 25
days to the lowest low of 2 days.

4. Regardless of the number of days in the trade, after any close where the open profit
is greater than 5 Average True Ranges the exit stop should be at the lowest low of 2
days. (Important: use 45 days to calculate the ATR)

Historical Results

Table 1 shows the historical results of trading 1 contract on the system tested over 10
years of data. For the testing purposes, we used continuous back-adjusted daily data.
We ignored all night sessions, and all calculations were based on day-session prices
and ranges only. $100 was deducted from every trade to simulate the effects of
commissions and slippage. The test period was from 1/1/88 to 1/16/98 with
MaxBarsBack set to 50 to enable adequate smoothing on the ADX calculations.
(MaxBarsBack refers to the number of bars of data necessary to calculate the rules in
a system. System rules only begin after the MaxBarsBack period. The test period
includes the MaxBarsBack period, so that no trades are taken for the first 50 trading
days.)

Table 1. “25 x 25” System v.2.0 Hypothetical Results (TradeStation format) This
system was created originally for Tradestation and then interpreted into MetaStock
Format by one of our members. We do not have MetaStock reports.

Total net profit $ 55,112.50 Open position P/L $ 1,875.00


Gross profit $ 64,887.50 Gross loss $-9,775.00

Total # of trades 32 Percent profitable 72%


Number winning trades 23 Number losing trades 9

Largest winning trade $ 5,181.25 Largest losing trade $ -2,600.00


Average winning trade $ 2,821.20 Average losing trade $ -1,086.11
Ratio avg win/avg loss 2.60 Avg trade(win & loss) $ 1,722.27

Max consec. winners 5 Max consec. losers 2


Avg # bars in winners 26 Avg # bars in losers 12

Max intraday drawdown $ -3,381.25


Profit factor 6.64 Max # contracts held 1
Account size required $ 3,381.25 Return on account 1,630%

118
The hypothetical performance data above was generated using Omega TradeStation,
with $100 deducted per trade for commissions and slippage. In our opinion, the
"account size required" and "return on account" calculations may not accurately
reflect the actual account size required to trade this system nor the return to be
expected.

PAST PERFORMANCE IS NOT NECESSARILY INDICATIVE OF FUTURE


RESULTS.

HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE


CERTAIN INHERENT LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE
RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING.
ALSO, SINCE THE TRADES HAVE NOT ACTUALLY BEEN EXECUTED, THE
RESULTS MAY HAVE UNDER-OR-OVER COMPENSATED FOR THE
IMPACT, IF ANY, OF CERTAIN MARKET FACTORS SUCH AS LACK OF
LIQUIDITY. SIMULATED TRADING PROGRAMS IN GENERAL ARE ALSO
SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT
OF HINDSIGHT. NO REPRESENTATION IS BEING MADE THAT ANY
ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFITS OR LOSSES SIMILAR
TO THOSE SHOWN.

System Concept

The concept behind the system is simple. We designed 25 x 25 to be a trend following


system that will enter an uptrend during a dip in prices. To do this we will implement
three entry strategies. First, there is a trend indicator to identify a strongly uptrending
market. Second, there is a shorter term retracement indicator that will identify a small
dip in the uptrend which will set up the trade. Third, we have a precise short-term
entry signal which will enter the trade when the uptrend resumes.

Trend Indication

For the trend indicator, we employ one of our favorite trend indicators, the Directional
Movement Indicator. Specifically we will use the relationship between the +DI (Plus
Directional Indicator), -DI (Minus Directional Indicator), and the ADX (Average
Directional Movement Index). These indicators were described by Welles Wilder in
his book, New Concepts In Technical Trading Systems, and are pre-programmed into
most of the modern computerized charting software. The default value chosen by Mr
Wilder was 14-days for all the indicators, and this is the value we have chosen for the
system.

For our trend indication, we will require that the 14-day +DI must be above the 14-
day -DI, and that the value of the ADX must be above 20. The relationship of the +DI
to the -DI is a useful way of determining the direction of the intermediate trend;
however this definition of trend is inadequate without the inclusion of the ADX which
actually measures the strength of the trend. Trend indicators traditionally only indicate

119
whether the trend is up or down, which is not an accurate representation of how the
market behaves. As you are aware, markets spend most of their time neither in an
uptrend or downtrend, but in a sideways market. By demanding that the ADX be
above 20, we effectively filter out these sideways markets, and enable our system to
enter during periods of relatively strong uptrends. It is important to understand that
the ADX does not indicate the direction of the trend, merely its strength, which is why
we need to combine the strong ADX reading with the DI relationship.

As a general concept it is a good idea to always trade markets according to the


direction of the intermediate trend. For instance, with our trend indicator installed, the
25 x 25 system made $53,000 over 10 years with an accuracy of 76%, and had an
average trade of $1,829. This indicator included a requirement for the ADX to be
above 20.

To assess the impact of an uptrend in trading the Bond market from the long side, we
eliminated the ADX requirement and reversed the rules of the system so that it only
took trades when the +DI was below -DI, indicating a downtrend. The results are
illuminating: trading the Bond market with all the same entry signals but during a
downtrend as defined as -DI being above +DI produced losses of $781 over 10 years
of trading, with a dismal accuracy of 29%, an average trade of -$6, and a drawdown
of $25,000! You clearly do not want to be buying the Bond market using this
technique in an intermediate downtrend.

We have mentioned the value of the ADX value in assessing the strength of the
uptrend. To see the impact of the ADX value, we re-tested the system to see how it
would perform if the ADX were below 20 while maintaining the requirement for the
+DI to be above the -DI. When the ADX is below 20 in a prevailing uptrend (as
defined by the +DI and -DI relationship), the system only made $8,900, was only 47%
accurate, and had an average trade of only $595 and a drawdown of $6,500, a
significant deterioration of results. We conclude that an uptrend indication on a trend
indicator such as the DI only gives average results; however, combining the trend
indicator with an ADX value is significantly superior because the ADX level serves to
filter out periods of sideways markets.

Retracement Indicator

The second indicator we have adopted is the 4-day RSI (Welles Wilder's Relative
Strength Index) which we use to identify a short-term dip in the market prices during
the prevailing uptrending Bond market. We use the RSI because of its popularity and
inclusion in most charting applications. Mr Wilder described a longer-term RSI, and
our choice of a 4-day RSI reflects our design intention of identifying short-term
retracements that would set up high probability trades. The RSI oscillates between a
minimum and maximum value of 0 and 100. When the RSI declines to below 50 (the
midpoint), we have defined a short-term decline in the market.

Does the short-term decline, as measured by the 4-day RSI falling below 50 actually
make that much difference to trading this market? To study the difference, we ran
another test on the system with the exact same rules, but eliminating the 4-day RSI
rule. The tests over 10 years of data showed a profit of $22,400 over 51 trades, with

120
an accuracy of 51%, an average trade of $440, and a drawdown of $9,200. The results
are striking: by eliminating the retracement indicator and entering the markets at any
point during an uptrend, the system makes less than half of the profits made when
entering on a short-term decline. The average trade declined to less than 25% of the
average trade when entering during a retracement! ($440 as compared with $1,800).
We concluded therefore that in an uptrending Bond market, waiting for a short-term
decline or dip in prices to set up a long trade is preferable to entering the trend on
strength.

Entry Trigger

With the +DI, -DI and ADX rules in place, and a short-term market decline measured
by the RSI, we have identified a market situation that is highly bullish. What we
require next is a very short term indicator that will get us into the market. In our
opinion, this particular indicator is the least important. It only serves to time our entry
a bit more precisely. In fact, our tests show that you could ignore this entry trigger,
and just enter the trade on the opening of the next trading day after the ADX and RSI
setups are present, to get a profit of $49,600 over 10 years and 57% accuracy with an
average trade of $974, a drawdown of $6,000, and a profit factor of 2.63! Entering on
the open would have traded 51 times over the last 10 years, significantly more than
the 29 trades with our 18-tick entry rule.

But entering on the opening after a decline has its difficulties, especially if the market
continues to decline. On a psychological level, many traders (including us) are more
comfortable knowing that the market is moving up in the direction of the trade before
entering the position. Hence the logic of our entry trigger: to wait till the market
proves itself by rallying 18 ticks from the previous day's close before we enter the
trade. This is a significant rally, but forcing the prices to rally significantly before
entering enables the system to produce a much higher percentage (76% over 10 years)
of winning trades.

There is no particular magic about the 18-tick number. In fact to test the robustness of
this entry parameter, we ran a series of tests using the same entry rules, and varying
the entry trigger from 2-ticks to 36-ticks above the closing price. The results are
presented in Table 2 below.

The most significant fact of the optimization is that all the tests are profitable, which
is a good indicator of a parameter robustness. Significantly also, all tests have large
average trades exceeding $1,000 per trade, and all tests show profit factors better than
2.50, and no drawdown on any test is greater than $6,000. It probably does not matter
how many ticks above the close you decide to take for the entry point. As mentioned
previously, even blindly entering on the opening is profitable over the historical data.
Also, we could trade more frequently if we acted on smaller moves above the
previous close, but we would expect to have a lower percentage of winners. For
instance, we could have chosen a smaller move of 8 ticks above the close to get a
profit of $52,500 on more trades (40 trades), but with a lower accuracy rate (68%) and
a slightly higher drawdown ($5,600). Since all tests are profitable, if a trader wishes
to deviate from the published system, we will leave it up to the individual trader to
decide which profile of trades bests suits him.

121
Table 2. Optimization Results on Entry Trigger Parameters

Ticks Net Profit Avg Trde PFact MaxDD #Trds %Prft

2.00 54712.50 1189.40 2.93 -5168.75 46 61


4.00 54087.50 1175.82 2.95 -4825.00 46 59
6.00 48475.00 1101.70 2.66 -5606.25 44 61
8.00 52562.50 1314.06 3.39 -5668.75 40 68
10.00 48575.00 1278.29 3.39 -5731.25 38 68
12.00 49300.00 1332.43 3.72 -5793.75 37 70
14.00 51375.00 1467.86 4.69 -3881.25 35 71
16.00 48837.50 1575.40 5.40 -4256.25 31 71
18.00 53068.75 1829.96 7.17 -3381.25 29 76
20.00 46100.00 1589.66 5.01 -4037.50 29 72
22.00 46700.00 2030.43 7.64 -4100.00 23 78
24.00 46362.50 2107.39 8.66 -4131.25 22 82
26.00 39306.25 1871.73 6.11 -4193.75 21 76
28.00 30787.50 1620.39 4.71 -4256.25 19 68
30.00 15343.75 1022.92 2.52 -4318.75 15 60
32.00 17637.50 1356.73 3.05 -4381.25 13 62
34.00 16400.00 1490.91 3.02 -4443.75 11 64
36.00 12281.25 1228.13 2.50 -4506.25 10 60

Testing the Entry Technique

Often, when we want to study the effectiveness of an entry technique by itself, we do


optimization tests on the entry technique and exit simply at a close X days in the
future. This often gives a good indication of the profit potential of any entry
technique. The percentage of winning trades is a good indication of the efficiency of
the entry technique. Table 3 below presents the results of the entry technique
described above, and exiting at the Xth close after the entry. These tests do not
include any money management stops or any other risk-management strategies.

Notice that all exits were profitable except an exit on the first close, which amounts to
exiting on the close of the day of entry. You certainly do not want to be day-trading
with this trend-following technique! Notice the high accuracy rates of 85 to 90%
when the trade is held 20 days or more. For instance, if you exited each trade on the
22nd close, you would make $54,800 with a 91% accuracy rate and a drawdown of
less than $5,500! And this is accomplished without any stop! We can conclude that
this entry technique predicts,with almost 85 to 90 percent accuracy, a resumption of
the trend that lasts between 20 to 25 days

Table 3. Results of the Entry Technique and Exiting on Xth Close.

X NetPrft AvgTrd PFact MaxDD #Trds %Prft

122
1.00 -412.50 -5.81 .96 -3900.00 71 45
2.00 2506.25 36.32 1.15 -4243.75 69 51
3.00 3231.25 51.29 1.18 -5493.75 63 52

4.00 9562.50 173.86 1.75 -4781.25 55 64


5.00 14925.00 287.02 2.30 -4043.75 52 63
6.00 21343.75 426.88 3.21 -3518.75 50 66
7.00 24650.00 535.87 3.05 -4056.25 46 65
8.00 31350.00 712.50 3.77 -3650.00 44 73
9.00 22481.25 522.82 2.73 -4212.50 43 60
10.00 21325.00 495.93 2.49 -5337.50 43 58
11.00 21418.75 498.11 2.51 -6431.25 43 63
12.00 27868.75 679.73 3.34 -4687.50 41 66
13.00 24187.50 604.69 2.73 -6081.25 40 63
14.00 19731.25 519.24 2.04 -7181.25 38 58
15.00 20768.75 561.32 2.11 -7393.75 37 70
16.00 25737.50 695.61 2.58 -7050.00 37 68
17.00 37000.00 1057.14 4.49 -5468.75 35 71
18.00 40631.25 1195.04 4.75 -5468.75 34 74
19.00 46162.50 1357.72 6.23 -5468.75 34 79
20.00 52793.75 1599.81 7.52 -5468.75 33 85
21.00 57168.75 1732.39 8.29 -5468.75 33 85
22.00 54862.50 1714.45 7.92 -5468.75 32 91
23.00 56618.75 1826.41 9.00 -5468.75 31 90
24.00 53318.75 1838.58 8.27 -5468.75 29 90
25.00 56168.75 2006.03 7.45 -5468.75 28 86
26.00 54075.00 1931.25 6.01 -5468.75 28 79
27.00 52325.00 1868.75 6.45 -5468.75 28 79
28.00 51043.75 1822.99 6.83 -5468.75 28 75
29.00 47893.75 1773.84 5.92 -5468.75 27 78
30.00 47581.25 1762.27 6.38 -5468.75 27 78

The Exit Techniques

For the exits we have included a $2,500 money management stop, which attempts to
limit the worst possible loss sustainable on any particular trade. We are always most
comfortable trading with stops that will limit the maximum dollar loss on any trade,
although we realize that this protection may be limited if the market gaps against the
position overnight. We have chosen $2,500 as the dollar-stop in this system. This is a
large stop designed to avoid whipsaws, and it has only been hit once in the last 10
years. In spite of the fact that this stop is rarely triggered we believe it is essential and
its presence makes us comfortable. We recommend dollar stops on all systems to
protect against catastrophic losses.

The second exit strategy is a common one: the channel low exit. In this case we have
chosen the low of the last 25 market days. Again, the exact number of days is
probably unimportant; the concept of trailing a stop at a low point in the market is
very popular and has been used successfully by market technicians for a long time.

If we merely installed the $2,500 dollar stop and the 25-day channel low exit, the

123
system makes $43,000 over 10 years of trading, with 18 trades. The average bars in
winners is 67, which is a relatively long period, and the average bars in losers is 14,
showing that the trailing exit effectively cuts losses short and lets profits run. The
system is 67% accurate, and has a huge average trade of $2,400. The ratio of average
win to loss with this exit is 3.78.

While this variant of the system is profitable and tradable on its own, it suffers from
several disadvantages: Firstly, it holds trades for a very long period. To take a profit
on a winning trade, a trader would have to hold through an average of 67 days. This
may not be psychologically appealing for many traders. But secondly, and even
worse, the exit is inefficient in that it frequently gives up large amounts of open
profits, since it always requires the market to reverse to a 25-day low before
signalling an exit. We have frequently seen trades give up one-third, or half, or all of
their open profits before exiting a trade on a trailing channel stop. In addition to
suffering a "roller coaster" sensation while waiting for a profitable trade to retrace to a
25-day low, many winning trades could turn into losses because of the slow exit. This
would not make us comfortable in spite of the potential profits.

A simple “twist” to the exit strategy allows us to reduce the number of days in the
average holding period, increase total profits, increase the accuracy to 72%, and trade
more frequently. The technique is this: we will wait patiently for a trade to develop
over a specific number of days, using the conventional dollar and channel stops, and
then switch to a tighter channel stop to effect a quick exit. Specifically, we will install
the 25-day channel low exit for the first 25 days of a trade (count the day of entry as
day 1), and on the 26th day, we will change the exit technique to a much tighter stop
at the lowest low of the last 2 days. This dramatic hange will obviously trigger a more
sensitive exit but will still allow us to maintain our position in a fast moving market.

We must also remember that our goal in trading is most directly related to the size of
the profit and not to the average holding period. Holding a trade longer may be best in
most cases but not in all. For those cases where we are fortunate enough to have a
large profit in less than 25 days we want to raise our stop to protect those profits
regardless of how long we have been in the trade. We have defined a large profit as a
profit of 5 average true ranges or more. Once our open profit on a closing basis
reaches this level we will implement our 2 day low exit regardless of the number of
days in the trade.

The combination of the $2,500 dollar stop, the 25-day lowest low stop, and the switch
in exits after 25 days creates a unique exit strategy which leads us to the name for this
system.

Conclusion

This report has presented several profitable concepts for trading Bonds, which we
believe should be equally applicable in other markets. For example, we have observed
that minor variations of this system work well in testing over data in T Notes and
Swiss Francs. We have shown the impact of a strong prevailing trend on winning
trades and recommend taking long trades only when the trend is clearly and strongly
up. In spite of the strong trend we have also shown that it is more advantageous to

124
wait for a decline in prices during the uptrend in order to set up a high-probability
entry point. Also, we have shown how a simple adaptation of an age-old exit
technique can increase profitability and accuracy, while reducing the average holding
period per trade.

We hope that this system as well as all our systems will be profitable in the future.
There are no guarantees. Constructing systems that perform well over past data is
relatively easy once you learn a few basic rules. But in addition to showing great
hypothetical performance, our goal is to develop systems that will serve our club
members as valuable learning tools and hopefully produce reasonably good results
over the unseen data in the future. Please give us your comments and suggestions
about this system and other systems that you would like to see.

MetaStock Efficiency Issues

In order to implement the system several techniques were required that slow
performance considerably. Daily commentaries suffer the most. On fast Pentium II
processors the delays are bearable, but on a 486 processor it may take 3-5 minutes to
update a commentary. System testing with a large data set requires a lot of patience. If
charts are limited to a year’s daily data (250 bars more or less), delays will be
minimized. Commentaries need only be enabled on setup and actual trade days. Keep
open charts to a minimum.

Overview of MetaStock implementation

The 25x25 Bond System enters and exits trades at intraday prices. In order to create a
MetaStock 6.50 version it was necessary to develop several indicators to keep track of
the intraday entry and exit prices. While this sounds simple enough, MetaStock does
not provide global variables or allow circular procedure referencing which would
greatly simplify the task.

On top of these shortcomings, MetaStock imposes tremendous processing overhead


by not allowing variable assignments within structured code. This means that all
values that might be needed in a procedure must be calculated ahead of time, whether
required or not, and are constantly updated when referencing previous values.

The 25x25 system only takes long trades. This MetaStock 6.50 system is designed as
a template for more complex systems taking both long and short trades based on
intraday prices and complex entry/exit procedures.

The main indicator is “25x25 LongEntry” which returns the entry price for a trade for
each day in the trade. A zero value indicates no position. The exit day is signaled by
setting the entry price negative. Thus, the value returned by a single fml(“25x25
LongEntry”) statement tells you the market position, the entry price, and whether it’s
the last day of a trade or not, and can be used to calculate a trade’s open profit and
days in the trade. This indicator is the heart of the system. It should be carefully
studied to understand how it decides when to enter a trade and whether to continue or
exit the trade. It stands alone and the other indicators depend on it.

125
The second indicator is “25x25 LongExit” which returns the exit price when “25x25
LongEntry” returns a negative value. It simply recalculates the exit stop value which
triggered a “25x25 LongEntry” negative value. The result is only used to determine a
trade’s closed profit. These two indicators may seem redundant for the 25x25 System,
but the technique allows for more complex systems that may stop and reverse on
intraday prices. By building corresponding “ShortEntry” and “ShortExit” indicators
almost any system can be modeled.

A third indicator, “25x25 TP”, returns the Trade Position and all other variables
needed by the MetaStock Expert. While not efficient, the Expert allows the system to
be traded without the need to plot the indicators.

Since MetaStock’s System Tester does not handle intraday prices, it can’t test the
25x25 performance. The “25x25 Equity” indicator allows the user to plot an equity
curve but, unfortunately, a trade by trade report cannot be generated. This indicator is
not required by the system and should only be plotted when testing.

The “25x25 Stop” indicator is another stand alone indicator not required by the
system but which is very helpful in seeing the stop values while in a trade. Unlike the
other indicators, which should be plotted in separate windows, the “25x25 Stop” can
be plotted directly on the daily bar chart. It should be plotted as a dashed line. Note
that stop values for days with no trade position are plotted as the days’ low value just
to keep the chart properly scaled.

Discrepancies between MetaStock and TradeStation Results

MetaStock and TradeStation do not compute several indicators exactly the same. In
order to duplicate the TradeStation design as closely as possible, the following
MetaStock indicators were modified:

Relative Strength Index (RSI(4)) results are rounded to two decimal places with the
following code: PREC(RSI(4) + .005, 2)

Average True Range(ATR(45)) smoothing is removed with the following code:


Mov(ATR(1), 45, S)

Even with these modifications not all 25x25 trades are exactly matched. However,
they are very close. MetaStock’s ten year test equity is $51,556.27 compared to
TradeStation’s $53,068.75.

*********************************************************************
************

{METASTOCK CODE}

{Chuck Le Beau's System Trader's Club}


{ http://traderclub.com }

126
{ mailto:chuck@traderclub.com }

{"25 x 25" Bond System MetaStock format}

25X25 LongEntry

{Returns long trade entry price. }


{A non-zero number if in a long trade. }
{A negative value if the last day of a trade. }

{Note: Modifications to MetaStock indicators }


{were req'd to simulate TradeStation results }
{ RSI: rounded to two decimal places }
{ ATR: Wilder's smoothing removed }

{Variables to avoid duplicate function calls }


PLLV2 := Ref(LLV(L,2),-1);
PLLV25 := Ref(LLV(L,25),-1);

{ Was yesterday a setup day? }


IsSetUp :=
Cum(1) > 50 AND
Ref(PDI(14),-1) > Ref(MDI(14),-1) AND
Ref(ADX(14),-1) > 20 AND
PREC(Ref(RSI(4),-1)+.005,2) < 50;

{Determine initial entry price condition}


EntryPriceCond := Ref(C,-1) + 0.5625;
{Adjust it to enter on open if open is greater}
EntryPriceCond :=
If(O > EntryPriceCond, O, EntryPriceCond);

{Return entry price, zero if no trade. }


If(PREV <= 0,
{Not in a long trade}
If(IsSetUp AND H >= EntryPriceCond,
{Trade entered today, was it stopped?}
If(L <= PLLV25 OR
L <= EntryPriceCond - 2.5,
-EntryPriceCond, {Yes}
EntryPriceCond {No}
),
{Not in trade and not entered today}
0
),
{Have been in trade for over one day. }
{Was it stopped today? }
{Note: BarsSince() gives days in trade }

127
If(L <= PREV - 2.5, - PREV,
If(BarsSince(PREV=0) > 24,

{More than 24 days in trade}


If(L <= PLLV2, -PREV, PREV),
{Less than 25 days in trade}
If(L <= PLLV25, -PREV,
If(Ref(C,-1) - PREV >
5*Ref(Mov(ATR(1),45,S),-1),
If(L <= PLLV2, -PREV, PREV),
PREV
)
)
)
)
);

25x25 Long Exit

{Returns exit price if last day of long trade}

EntryPrice := Fml("25x25 LongEntry");


ExitingTrade := EntryPrice < 0;

EntryPrice := Abs(EntryPrice);

{Variables to avoid duplicate function calls }


{Lowest low of previous two days }
PLLV2 := Ref(LLV(L,2),-1);
{Lowest low of previous 25 days }
PLLV25 := Ref(LLV(L,25),-1);
TradeDays := If(EntryPrice > 0,
BarsSince(Fml("25x25 LongEntry") = 0), 0);

{ Determine type of stop(s) }


Stop1 :=
ExitingTrade AND TradeDays>24 AND L<=PLLV2;
Stop2 :=
ExitingTrade AND TradeDays>0 AND TradeDays<=24 AND L<=PLLV25;
Stop3 :=
ExitingTrade AND L <= EntryPrice - 2.5;
Stop4 :=
ExitingTrade AND Ref(C,-1) - EntryPrice > 5*Ref(Mov(ATR(1),45,S),-1) AND L <=
PLLV2;

{ Determine prices for activated stops }


Stop1Price :=
If(Stop1, Min(O, PLLV2), 0);
Stop2Price :=
If(Stop2, Min(O, PLLV25), 0);

128
Stop3Price :=
If(Stop3, Min(O, EntryPrice - 2.5), 0);
Stop4Price :=

If(Stop4, Min(O, PLLV2), 0);

{ Assume best stop price stopped the trade }


StopPrice :=
Max(Stop1Price,Max(Stop2Price,
Max(Stop3Price,Stop4Price)));

If(ExitingTrade, StopPrice, 0);

25x25 TP

{ Calculate today's trade position and other }


{ values used by the expert. }

{ LE = LongEntryPrice from indicator }


{ SULE = Tommorow's LongEntry if setup day }
{ SULS = Tommorow's LongStop if setup day }
{ TP = TradePosition +1,0 }
{ TLS = Tomorrow's LongStop if in trade }
{ PRFT = Trade Profit }
{ RISK = Tommorow's theoretical capital risk }

LE := Fml("25x25 LongEntry");
TP := If(LE <> 0, +1, 0);
PRFT := If(LE = 0, 0,
If(LE > 0, C - LE,
Fml("25x25 LongExit") + LE));
TradeDays := If(LE <> 0,
BarsSince(Fml("25x25 LongEntry") = 0), 0);

{Calculate tomorrow's entry prices }


SULE :=
If(TP = 0,
If(PDI(14) > MDI(14) AND ADX(14) > 20 AND
PREC(RSI(4)+.005,2) < 50,
C + .5625, 0), 0);

{Calculate initial stop price}


SULS :=
If(SULE <> 0, Max(LLV(L,25), SULE-2.5), 0);

{Calculate tomorrow's stops }


S1 := If(LE > 0,
If(TradeDays >= 24,
LLV(L,2),

129
LLV(L,25)), 0);
S2 := If(LE > 0, LE - 2.5, 0);
S3 := If(LE > 0 AND
PRFT >= 5*Ref(Mov(ATR(1),45,S),-1),

LLV(L,2), 0);

{Tomorrow's Long Stop}


TLS := Max(S1, Max(S2, S3));

PRFT := PRFT * 1000;

RISK :=
If(LE > 0, (LE-TLS)*1000,
If(SULE <> 0, (SULE-SULS)*1000, 0));

TP;

*********************************************************************
*******************
The following Trade by Trade Report was produced using the data supplied with this
archive
which is continuous contract, back-adjusted, day session only, Bond futures data.

Bond "25" System UA.LNG-Daily 01/04/88 - 01/16/98

Date Time Type Cnts Price Signal Name Entry P/L Cumulative

06/22/88 Buy 1 64^10


07/13/88 LExit 1 62^22 L25 $ -1725.00 $ -1725.00
09/29/88 Buy 1 64^24
11/04/88 LExit 1 67^10 $ 2462.50 $ 737.50
05/05/89 Buy 1 67^23
06/15/89 LExit 1 73^13 $ 5587.50 $ 6325.00
06/20/89 Buy 1 73^14
08/03/89 LExit 1 77^21 $ 4118.75 $ 10443.75
08/15/89 Buy 1 74^12
08/22/89 LExit 1 73^24 L25 $ -725.00 $ 9718.75
08/23/89 Buy 1 74^08
08/29/89 LExit 1 73^17 L25 $ -818.75 $ 8900.00
10/19/89 Buy 1 76^14
11/27/89 LExit 1 77^01 $ 493.75 $ 9393.75
06/26/90 Buy 1 71^13
07/10/90 LExit 1 70^27 L25 $ -662.50 $ 8731.25
11/09/90 Buy 1 70^14
12/17/90 LExit 1 74^23 $ 4181.25 $ 12912.50

130
08/28/91 Buy 1 77^31
10/03/91 LExit 1 80^22 $ 2618.75 $ 15531.25
11/06/91 Buy 1 80^05
12/13/91 LExit 1 82^05 $ 1900.00 $ 17431.25
01/17/92 Buy 1 84^16

01/29/92 LExit 1 83^07 L25 $ -1381.25 $ 16050.00


05/29/92 Buy 1 83^25
07/08/92 LExit 1 86^13 $ 2525.00 $ 18575.00
07/15/92 Buy 1 86^17
08/21/92 LExit 1 89^22 $ 3056.25 $ 21631.25
12/29/92 Buy 1 91^18
02/10/93 LExit 1 93^31 $ 2306.25 $ 23937.50
02/11/93 Buy 1 93^31
03/22/93 LExit 1 97^17 $ 3462.50 $ 27400.00
08/09/93 Buy 1 104^20
09/15/93 LExit 1 108^25 $ 4056.25 $ 31456.25
12/13/94 Buy 1 94^05
01/20/95 LExit 1 94^15 $ 212.50 $ 31668.75
02/10/95 Buy 1 97^04
03/21/95 LExit 1 99^06 $ 1962.50 $ 33631.25
03/24/95 Buy 1 99^02
05/11/95 LExit 1 104^04 $ 4962.50 $ 38593.75
06/13/95 Buy 1 108^18
07/19/95 LExit 1 107^31 $ -693.75 $ 37900.00
09/19/95 Buy 1 110^13
10/27/95 LExit 1 112^05 $ 1650.00 $ 39550.00
10/27/95 Buy 1 112^31
12/07/95 LExit 1 116^16 $ 3431.25 $ 42981.25
08/16/96 Buy 1 108^22
08/26/96 LExit 1 106^06MM $ -2600.00 $ 40381.25
10/11/96 Buy 1 108^17
11/25/96 LExit 1 113^02 $ 4431.25 $ 44812.50
05/08/97 Buy 1 108^21
06/18/97 LExit 1 110^22 $ 1931.25 $ 46743.75
06/27/97 Buy 1 110^28
08/04/97 LExit 1 113^28 $ 2900.00 $ 49643.75
09/26/97 Buy 1 115^14
11/03/97 LExit 1 117^05 $ 1618.75 $ 51262.50
11/06/97 Buy 1 117^15
12/17/97 LExit 1 119^12 $ 1806.25 $ 53068.75
12/31/97 Buy 1 120^05

To view an equity chart based on the above trades go to:

http://www.traderclub.com/systems_25.htm

PAST PERFORMANCE IS NOT NECESSARILY INDICATIVE OF FUTURE


RESULTS.

131
HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE
CERTAIN INHERENT LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE
RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING.
ALSO, SINCE THE TRADES HAVE NOT ACTUALLY BEEN EXECUTED, THE
RESULTS MAY HAVE UNDER-OR-OVER COMPENSATED FOR THE
IMPACT, IF ANY, OF CERTAIN MARKET FACTORS SUCH AS LACK OF
LIQUIDITY. SIMULATED TRADING PROGRAMS IN GENERAL ARE ALSO
SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT
OF HINDSIGHT. NO REPRESENTATION IS BEING MADE THAT ANY
ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFITS OR LOSSES SIMILAR
TO THOSE SHOWN.

COMMON METASTOCK BAR PATTERNS

BAR - 3 Higher Highs


H>Ref(H,-1) AND Ref(H,-1)>Ref(H,-2) AND Ref(H,-2)>Ref(H,-3)

BAR - 3 Lower Lows & Reversal H


L>Ref(L,-1) AND Ref(L,-1)<Ref(L,-2) AND Ref(L,-2)<Ref(L,-3) AND
Ref(L,-3)<Ref(L,-4)

BAR - 3 Lower Lows


L<Ref(L,-1) AND Ref(L,-1)<Ref(L,-2) AND Ref(L,-2)<Ref(L,-3)

BAR - 5 Lower Lows


L<Ref(L,-1) AND Ref(L,-1)<Ref(L,-2) AND Ref(L,-2)<Ref(L,-3) AND
Ref(L,-3)<Ref(L,-4) AND Ref(L,-4)<Ref(L,-5)

BAR - Expansion Buy


If(C > Ref(HHV(C,42),-1) AND H-L >= Ref(HHV((H-L),9),-1),1,0)

BAR - Expansion Sell


If(C < Ref(LLV(C,42),-1) AND (H-L) >= Ref(HHV((H-L),9),-1),1,0)

BAR - Fractal-down
If(LOW < Ref(LOW, -1),1,0) AND If(LOW < Ref(LOW, -2),1,0) AND If(LOW <
Ref(LOW,+1),1,0) AND If(LOW < Ref(LOW,+2),1,0)

BAR - Fractal-up
(If(HIGH > Ref(HIGH, -1),1,0) AND If(HIGH > Ref(HIGH, -2),1,0) AND If(HIGH
> Ref(HIGH, +1),1 ,0)AND If(HIGH > Ref(HIGH,+2),1,0))

BAR - Gap Down


GapDown()

BAR - Gap Up
GapUp()

BAR - H > Yesterday's H


H>Ref(H,-1)

132
BAR - Highest Bars Ago
HighestBars(CLOSE)

BAR - Highest High Value Bars Ago


HHVBars(CLOSE,50)

BAR - Inside Day + Day 3


Ref(Fml("BAR - Inside Day"),-3)

BAR - Inside Day


HIGH < Ref(HIGH,-1) AND LOW > Ref(LOW,-1)

BAR - Lizard Buy


If(O >= L + ((H-L) * .75) AND C >= L + ((H-L) * .75) AND L <
Ref(LLV(L,9),-1),1,0)

BAR - Lizard Sell


If(O <= L + ((H-L) * .25) AND C <= L + ((H-L) * .25) AND H >
Ref(HHV(H,9),-1),1,0)

BAR - Narrow Range 4


HIGH - LOW < Ref(LLV(H-L,3),-1)

BAR - Narrow Range 7


HIGH - LOW < Ref(LLV(H-L,6),-1)

BAR - O > Yesterday's C


O>Ref(C,-1)

BAR - Outside Day & > C


Outside() AND C>Ref(C,-1)

BAR - Outside Day


HIGH > Ref(HIGH,-1) AND LOW < Ref(LOW,-1)

BAR - Pivot Buy


If(H-L > Ref(HHV((H-L),9),-1) AND ((L <= Mov(C,50,S)) OR Ref(L,-1) <=
Ref(Mov(C,50,S),-1))
AND C > Mov(C,50,S),1,0)

BAR - Pivot Sell


If(H-L > Ref(HHV((H-L),9),-1) AND ((H >= Mov(C,50,S)) OR Ref(H,-1) >=
Ref(Mov(C,50,S),-1))
AND C < Mov(C,50,S),1,0)

BAR - Reaction Day with Volume


ReactionWithVol()

133
BAR - Reaction Day

Reaction()

BAR - Surprise Day Down


O<Ref(C,-1) AND C>O AND C<Ref(C,-1)

BAR - Surprise Day Up


O>Ref(C,-1) AND C<O AND C>Ref(C,-1)

BAR - Trough Value - 5


Trough(1,CLOSE,5)

BAR - Typical Price


Typical()

(from Walter Lake}

METASTOCK FORMULA FOR THE MIESAL INDICATOR

"It's a short term timing tool. It's not worth using for long term
investors. Some have also suggested using periods of 25 or 50 days, though I
use only 10 days. Others have suggested it's very useful when used
in conjunction with Welles Wilder's RSI."

Sum(If(C > Ref(C,-1), +1, If(C < Ref(C,-1), -1, 0)),10)

Entry/Exit signal
buy:
Fml("CCIF-P")>Ref(Fml("CCIF-P"),-1) AND
Cross(Fml("CCIF-P"),-100) OR
Cross(Fml("CCIF-P"),100)

sell:
Fml("CCIF-P")<Ref(Fml("CCIF-P"),-1) AND
Cross(100,Fml("CCIF-P")) OR
Cross(-100,Fml("CCIF-P"))
{horizontal lines @ -100 & +100}

where:
{"CCIF-P" is}
(CCI(8)+CCI(13)+CCI(21))/3

{from Mike Arnoldi}

UPDATE MIXED BALANCE POINT KRAUSE

I have updated some of the code since my last post concerning the TASC
articles written by Robert Krausz. The code now plots on the proper days

134
(instead of 1 day ahead) and they should also be more efficient to
calculate. These are named different so you should delete the old code after

you have installed the new. I will


also post a follow up with a graphic to show how these plot. Note: the
formulas on the Equis web page WILL NOT calculate for missing days
(Holidays).

from Adam Hefner.


VonHef@email.msn.com

---------------------------------------
MTF - FIXED BALANCE POINT
name: MTF-Fixed Balance Point

{Multiple Time Frame


"Fixed Balance Point" 4/23/99}

Dw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
Wt:=If(Dw=1,
{then}(Ref(HighestSince(1,Dw=1,H),-1)+
Ref(LowestSince(1,Dw=1,L),-1) +
Ref(C,-1))/3,
{else}0);
DwP:=ValueWhen(1,Wt>0,Wt);
Dwp
--------------------------------------------

MTF-Fixed Balance Point Step

{Multiple Time Frame


"Fixed Balance Point Step" 4/23/99}

Dw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
Wt:=If(Dw=1,
{then}(Ref(HighestSince(1,Dw=1,H),-1)+
Ref(LowestSince(1,Dw=1,L),-1) +
Ref(C,-1))/3,
{else}0);
DwPs:=(ValueWhen(1,Wt>0,Wt)+
ValueWhen(2,Wt>0,Wt)+
ValueWhen(3,Wt>0,Wt)+
ValueWhen(4,Wt>0,Wt)+
ValueWhen(5,Wt>0,Wt))/5;
Dwps
------------------------------------------------

MTF-Dynamic Balance Point

{Multiple Time Frame

135
Dynamic Balance Point 4/23/99}
dt:=DayOfWeek();
dc:=If(Dt=1,BarsSince(Ref(dt,-1)=1)+1,

If(Dt=2,BarsSince(Ref(dt,-1)=2)+1,
If(Dt=3,BarsSince(Ref(dt,-1)=3)+1,
If(Dt=4,BarsSince(Ref(dt,-1)=4)+1,
BarsSince(Ref(dt,-1)=5)+1))));
DBC:=If(dc=5,
{then}(Ref(HighestSince(5,dt,H),-1)+
Ref(LowestSince(5,dt,L),-1)+
Ref(CLOSE,-1))/3,
{else}(Ref(HighestSince(4,dt,H),-1)+
Ref(LowestSince(4,dt,L),-1)+
Ref(CLOSE,-1))/3);
DBC
------------------------------------------------

MTF-Dynamic Balance Point Step

{Multiple Time Frame


Dynamic Balance Point Step 4/23/99}
Dr:= FmlVar("MTF-Dynamic Balance Point","DBC");
Dsc:=(ValueWhen(1,Dr,Dr)+
ValueWhen(5,Dr,Dr)+
ValueWhen(10,Dr,Dr)+
ValueWhen(15,Dr,Dr)+
ValueWhen(20,Dr,Dr))/5;
Dsc
--------------------------------------------------
Multiple Time Frame Weekly Support & Resistance
MTF-S&R

{Multiple Time Frame


"Weekly Support & Resistance" 4/23/99}

Dw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
Wt:=If(Dw=1,
{then}(Ref(HighestSince(1,Dw=1,H),-1)+
Ref(LowestSince(1,Dw=1,L),-1) +
Ref(C,-1))/3,
{else}0);
Wh:=If(Dw=1,
{then}Ref(HighestSince(1,Dw=1,H),-1),
{else}0);
Wl:=If(Dw=1,
{then}Ref(LowestSince(1,Dw=1,L),-1),
{else}0);
Wr:=ValueWhen(1,Wh>0,Wh)-ValueWhen(1,Wl>0,Wl);
DwP:=ValueWhen(1,Wt>0,Wt);

136
RR1:=DwP+(Wr*.5);
RR2:=DwP+(Wr*.618);
SR1:=DwP-(Wr*.5);
SR2:=DwP-(Wr*.618);

SR2;
SR1;
RR1;
RR2;

MTF-Tendency

Mt:=If(DayOfWeek()=1,
Ref(C,-1)- FmlVar("MTF-Fixed Balance Point","DWP"),
0);
If(Mt>0,1,If(Mt<0,-1,0))
---------------------------------------

WEEKLY INDICATORS

MetaStock Weekly Indicators

I had basically put the weekly indicators on daily charts thing on the back
burner for the time being, but someone mentioned the subject in an off list
e-mail, and I decided that maybe I should post these two
indicators. They look right to me, but double check them. Remember, they
plot the previous weeks value beginning the first trading day of the
following week, and that value remains constant throughout that
week. These are designed for backtesting.....so if you just gotta know on
this Friday evening what the weekly value of the indicator is going to be
for the following week, simply look a weekly chart.

Stochastic: The %K and %K slowing can be coded to accommodate more


parameters by using the user Input function, but when you do this the %D
always calculates using the default value of the %K slowing, giving
erroneous values. So I just left it as is. Youcan plug in your own
values...I just used the MetaStock default values as a starting point. I
made the %K D as two separate indicators so that you can plot the %D a
different color and/or dashed. The Momentum indicator uses the Input
function just fine.

{`Wkly Stoch 5 per %K, slowing=3, no %D}

{start week}
sw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
yestClo:=If(sw>0,Ref(C,-1),0);

{lowest low last 5 weeks}

137
LLow:=(ValueWhen(1,sw>0,
Ref(LowestSince(5,sw>0,L),-1)));

{highest high last 5 weeks}


HHigh:=(ValueWhen(1,sw>0,
Ref(HighestSince(5,sw>0,H),-1)));

{5 per %K, slowing=3}


y:=(ValueWhen(1,sw>0,(yestClo-LLow))+
ValueWhen(2,sw>0,(yestClo-LLow))+
ValueWhen(3,sw>0,(yestClo-LLow)))/

((ValueWhen(1,sw>0,HHigh)+
ValueWhen(2,sw>0,HHigh)+
ValueWhen(3,sw>0,HHigh))-

(ValueWhen(1,sw>0,LLow)+
ValueWhen(2,sw>0,LLow)+
ValueWhen(3,sw>0,LLow)))*100;
y;

=====================
{`Wkly Stoch 3 per %D of a 5 per %K, slowing=3}

{start week}
sw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
yestClo:=If(sw>0,Ref(C,-1),0);

{lowest low last 5 weeks}


LLow:=(ValueWhen(1,sw>0,
Ref(LowestSince(5,sw>0=1,L),-1)));

{highest high last 5 weeks}


HHigh:=(ValueWhen(1,sw>0,
Ref(HighestSince(5,sw>0,H),-1)));

{5 per %K, slowing=3}


y:=(ValueWhen(1,sw>0,(yestClo-LLow))+
ValueWhen(2,sw>0,(yestClo-LLow))+
ValueWhen(3,sw>0,(yestClo-LLow)))/

((ValueWhen(1,sw>0,HHigh)+
ValueWhen(2,sw>0,HHigh)+
ValueWhen(3,sw>0,HHigh))-

(ValueWhen(1,sw>0,LLow)+

138
ValueWhen(2,sw>0,LLow)+

ValueWhen(3,sw>0,LLow)))*100;

{This plots the 3 period %D (ma) of the above.}


z:=(ValueWhen(1,sw>0,y)+ValueWhen(2,sw>0,y)+
ValueWhen(3,sw>0,y))/3;
z
========================

{`Wkly Momentum for DAILY Chart }

{This plots WEEKLY Momentum on DAILY charts. -Ken 4/16/99}

n:=Input("Periods",1,20,10);
{start week}
sw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);

(ValueWhen(1,sw>0,Ref(C,-1))/
ValueWhen(n+1,sw>0,
Ref(C,-1)))*100

from Ken

MODIFIED WILLIAMS %R METATSOCK INDICATOR

by Rajat Bose}

Periods := Input("Time Period", 3,50,5);


NumDev := Input("No. of Standard Deviations", 1,5,2);

(100*(C-BBandBot(C, Periods, S, NumDev))/((( BBandTop(C, Periods, S,


NumDev))-(BBandBot(C, Periods, S, NumDev)))))

{All I have done here is to substitute High and Low of any bar with that of
Bollinger Band Top and Bollinger Band Bottom. I have tested it on various
time periods (for Bollinger Bands) using 2 standard deviations. It sometimes
gives an early indication of reversals than the Williams %R of the same
period. Divergences have also been somewhat better. However, the structure
shows that most of its properties are similar to those of the Williams %R
or, for that matter, of any other overbought-oversold indicator.}

GUPPY MMA INDICATORS


(Note this is not the same as the formula given in Trading Tactics. Daryl Guppy)

Try MMA (Multiple Moving Averages). The shorter ones are closer to the
action and the longer ones tell you about the trend. I use two indicators
like this:

139
Name: MMA Long Term
--------
Mov(C,40,E);
Mov(C,45,E);
Mov(C,50,E);
Mov(C,55,E);

Name: MMA Short Term


--------
Mov(C,5,E);
Mov(C,8,E);
Mov(C,11,E);
Mov(C,14,E);

In the current market I like taking short momentum trades where the MMA
Short is bouncing up off a slowly rising MMA Long Term. The exit at the top
of the bubble is indicated by MMA Short turning down after a good separation
from the underlying MMA Long.

from Jeff Lederman.

{Suggestion: Create a single TEMPLATE with all the above indicators, giving
SHORT and LONG MMAs separate colours; e.g., RED for the SHORTs and BLUE
for
the LONGs.}

GANN SWING UPDATE

This is an update to Gann-Swing indicators I had posted several months


back. Most of the code has been improved and I have modified the swing
definition slightly.

Gann Weekly Expert Instructions

1. First create a new expert and name it whatever you want.


2a. under "trends" tab put this code for bullish:
ut:=FmlVar("GANN-Trend","TDV");
uplot:=If(BarsSince(Ut=1)<
BarsSince(Ut=-1),1,0);
uplot=1;
2b. and this for bearish:
dt:=FmlVar("GANN-Trend","TDV");
dplot:=If(BarsSince(dt=1)>
BarsSince(dt=-1),1,0);
dplot=1;
Then click on the "ribbon" option and turn off "Display Vertical Lines", I
also turn off

140
the corner option.

3a. Under highlights tab create a new and call it "HiLo Change", choose
color, and enter this code:
HLd:=If(CLOSE>Ref(Mov(H,3,S),-1),
{then}1,
{else}If(CLOSE<Ref(Mov(L,3,S),-1),
{then}-1,
{else}0));
HLv:=ValueWhen(1,HLd<>0,HLd);
HLv<>Ref(HLv,-1);
3b. Create new and call it "Up-Trend", choose color, and enter this code:
ut:=FmlVar("GANN-Trend","TD");
uplot:=If(BarsSince(Ut=1)<
BarsSince(Ut=-1),1,0);
uplot=1;
3c. Create new and call it "Down-Trend", choose color, and enter this code:
dt:=FmlVar("GANN-Trend","TD");
dplot:=If(BarsSince(dt=1)>
BarsSince(dt=-1),1,0);
dplot=1;
4a. Under "Symbols" tab create new and call it " UpSwing", enter this code:
FmlVar("GANN-Swing","SD2")=1;
then under graphic choose "Buy Arrow", choose color (Dark Green), and small
size, then pick "Above Price Plot".
4b. Create new and call it "DownSwing", enter this code:
FmlVar("GANN-Swing","SD2")=-1;
then under graphic choose "sell arrow", choose color (Dark Red), and small
size, then pick "Below Price Plot".
As for the HiLo ....just plot it as a regular indicator and choose the last
"style" option under "color/style" tab.

Note: For daily bar charts ribbon use these formulas:

2a. ut:= FmlVar("GaW-Trend","TDV") ;


uplot:=If(BarsSince(Ut=1)<
BarsSince(Ut=-1),1,0);
uplot=1;

2b. dt:= FmlVar("GaW-Trend","TDV") ;


dplot:=If(BarsSince(dt=1)>
BarsSince(dt=-1),1,0);
dplot=1;

from Adam Hefner.

------------------------------------------------------
GANN-HiLo

{HiLo 4/27/99}

141
Lb:=Input("Look-Back Periods?",2,10,3);
HLd:=If(CLOSE>Ref(Mov(H,Lb,S),-1),

{then}1,
{else}If(CLOSE<Ref(Mov(L,Lb,S),-1),
{then}-1,
{else}0));
HLv:=ValueWhen(1,HLd<>0,HLd);
HiLo:=If(HLv=-1,
{then}Mov(H,Lb,S),
{else}Mov(L,Lb,S));
HiLo;
------------------------------------------

GANN-Swing

{Gann-Swing 4/27/99}
{Market swing is defined as:
Up = 2 higher highs,
Down = 2 lower lows.}
Us:=BarsSince(Sum(H>Ref(H,-1),2)=2);
Ds:=BarsSince(Sum(L<Ref(L,-1),2)=2);
Hc:=HighestSince(1,Us=0,H);
Lc:=LowestSince(1,Ds=0,L);
Sd1:=If(Us=0,
{then}If((L<>Lc) AND (Ref(L,-1)<>Lc),
{then}1,
{else}0),
{else}If(Ds=0,
{then}If((H<>HC) AND (Ref(H,-1)<>Hc),
{then}-1,
{else}0),
{else}0));
Sd2:=If(Sd1=1,
{then} If(Ref(BarsSince(Sd1=1),-1) >
Ref(BarsSince(Sd1=-1),-1),
{then}1,
{else}0),
{else} If(Sd1=-1,
{then}If(Ref(BarsSince(Sd1=1),-1) <
Ref(BarsSince(Sd1=-1),-1),
{then}-1,
{else}0),
{else}0));
TD1:=ValueWhen(1,Sd2<>0,Sd2);
Td1;
--------------------------------------------
GANN-Trend

{Gann-Trend 4/27/99}

142
{Swing Direction}
Sd:= FmlVar("GANN-Swing","TD1") ;
{Swing Change High}
Sch:=If(Sd=1 AND Ref(sd,-1)=-1,
{then}1,
{else}0);
{Swing Change Low}
Scl:=If(Sd=-1 AND Ref(Sd,-1)=1,
{then}1,
{else}0);
{Peak Value}
Pv:=If(Scl=1,
{then}HighestSince(1,Sch=1,H),
{else}0);
{Trough Value}
Tv:=If(Sch=1,
{then}LowestSince(1,Scl=1,L),
{else}0);
{Trend Direction}
Td:=If(H>ValueWhen(1,Pv>0,Pv),
{then}1,
{else}If(L<ValueWhen(1,Tv>0,Tv),
{then}-1,
{else}0));
{UpTrend=1 DownTrend =-1}
Tdv:=ValueWhen(1,Td<>0,Td);
Tdv
------------------------------------------
GaW-Swing

{Weekly Swing 4/27/99}


{Market swing is defined as:
Up = 2 higher highs,
Down = 2 lower highs }
{Weekly High/Low}
Dw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
Wh:=If(Dw=1,
{then}Ref(HighestSince(1,Dw=1,H),-1),
{else}0);
Wl:=If(Dw=1,
{then}Ref(LowestSince(1,Dw=1,L),-1),
{else}0);
Hv1:=ValueWhen(1,Wh>0,Wh);
Hv2:=ValueWhen(2,Wh>0,Wh);
Hv3:=ValueWhen(3,Wh>0,Wh);
Lv1:=ValueWhen(1,Wl>0,Wl);
Lv2:=ValueWhen(2,Wl>0,Wl);
Lv3:=ValueWhen(3,Wl>0,Wl);
Us:=BarsSince((Hv1 > Hv2) AND (Hv2 > Hv3));

143
Ds:=BarsSince((Lv1 < Lv2) AND (Lv2 < Lv3));

Hc:=Ref(HighestSince(1,Us=0 AND Ref(Us,-1)>0,H),


-1);
Lc:=Ref(LowestSince(1,Ds=0 AND Ref(Ds,-1)>0,L),
-1);
{Swing direction Calculation}
Sd1:=If(Us=0 AND Dw=1,
{then}If((Lv1<>Lc) AND (Lv2<>Lc),
{then}1,
{else}0),
{else}If(Ds=0,
{then}If((Hv1<>Hc) AND (Hv2<>Hc),
{then}-1,
{else}0),
{else}0));
Sd2:=If(Sd1=1,
{then} If(Ref(BarsSince(Sd1=1),-1) >
Ref(BarsSince(Sd1=-1),-1),
{then}1,
{else}0),
{else} If(Sd1=-1,
{then}If(Ref(BarsSince(Sd1=1),-1) <
Ref(BarsSince(Sd1=-1),-1),
{then}-1,
{else}0),
{else}0));
TD1:=ValueWhen(1,Sd2<>0,Sd2);
TD1
-------------------------------------------
GaW-Trend

{Weekly Trend 4/27/99}


{Swing Direction}
Sd:= FmlVar("GaW-Swing","TD1") ;
{Swing Change High}
Sch:=If(Sd=1 AND Ref(sd,-1)=-1,
{then}1,
{else}0);
{Swing Change Low}
Scl:=If(Sd=-1 AND Ref(Sd,-1)=1,
{then}1,
{else}0);
{Peak Value}
Pv:=If(Scl=1,
{then}HighestSince(1,Sch=1,H),
{else}0);
{Trough Value}
Tv:=If(Sch=1,
{then}LowestSince(1,Scl=1,L),

144
{else}0);
{Trend Direction}

Td:=If(H>ValueWhen(1,Pv>0,Pv),
{then}1,
{else}If(L<ValueWhen(1,Tv>0,Tv),
{then}-1,
{else}0));
{UpTrend=1 DownTrend =-1}
Tdv:=ValueWhen(1,Td<>0,Td);
Tdv

STOP LOSS INDICATOR

periodsshort:=Input("periods if short",1,50,10); periodslong:=input("periods


if long",1,50,10);

HHV(H,periodsshort)-atr(periodsshort);{stop loss level for short positions}


LLV(L,periodslong)+ATR(periodslong);{stop loss level for long positions}

{by Eric Kendall}

METASTOCK GAP UP FORMULAS

The MetaStock formulas to calculate these percentages are shown below. The
first input is the minimum gap (e.g., 1%), and the second input is the gap
increment (e.g., 1%, which would give you a range of 1-2%). To calculate
gaps down, change the percentage to a negative.

Formula to determine whether the closing price is equal to or exceeds the


opening price on a gap day:

MinGap := Input("Minimum gap to consider (%)",-10000,10000,1);


GapIncrement := Input("Gap Increment (%)",0,100,1);

LookingForGapUp := MinGap >= 0; LookingForGapDown := MinGap < 0;

{ Gap percentage }
Gap := (OPEN - Ref(CLOSE,-1))/Ref(CLOSE,-1)*100;

NumGaps := If(LookingForGapUp, Cum(Gap >= MinGap AND Gap < MinGap +


GapIncrement), If(LookingForGapDown, Cum(Gap <= MinGap AND Gap > MinGap
-
GapIncrement),0));

If(LookingForGapUp, Cum(If(Gap >= MinGap AND Gap < MinGap +


GapIncrement,

145
If(CLOSE >= OPEN, +1,0),0)),

If(LookingForGapDown, Cum(If(Gap <= MinGap AND Gap > MinGap -


GapIncrement,
If(CLOSE <= OPEN, +1, 0),0)), 0))/NumGaps*100;

Formula to determine whether the daily range crosses the previous day’s
close on a gap day:

MinGap := Input("Minimum gap to consider (%)",-10000,10000,1);


GapIncrement := Input("Gap Increment (%)",0,100,1);

LookingForGapUp := MinGap >= 0; LookingForGapDown := MinGap < 0;

{ Gap percentage }
Gap := (OPEN - Ref(CLOSE,-1))/Ref(CLOSE,-1)*100;

NumGaps := If(LookingForGapUp, Cum(Gap >= MinGap AND Gap < MinGap +


GapIncrement), If(LookingForGapDown, Cum(Gap <= MinGap AND Gap > MinGap
-
GapIncrement),0));

If(LookingForGapUp, Cum(If(Gap >= MinGap AND Gap < MinGap +


GapIncrement,
If(LOW <= Ref(CLOSE,-1), +1,0),0)),

If(LookingForGapDown, Cum(If(Gap <= MinGap AND Gap > MinGap -


GapIncrement,
If(HIGH >= Ref(CLOSE,-1), +1, 0),0)), 0))/NumGaps*100;

Formula to determine whether the following day’s open continues the gap
trend:

MinGap := Input("Minimum gap to consider (%)",-10000,10000,1);


GapIncrement := Input("Gap Increment (%)",0,100,1);

LookingForGapUp := MinGap >= 0; LookingForGapDown := MinGap < 0;

GapYesterday := (Ref(OPEN,-1) - Ref(CLOSE,-2))/Ref(CLOSE,-2)*100;

NumGapsthruYesterday := If(LookingForGapUp, Cum(GapYesterday >= MinGap


AND
GapYesterday < MinGap + GapIncrement), If(LookingForGapDown,
Cum(GapYesterday <= MinGap AND GapYesterday > MinGap - GapIncrement),0));

If(LookingForGapUp, Cum(If(GapYesterday >= MinGap AND GapYesterday <


MinGap
+ GapIncrement, If(OPEN > Ref(CLOSE,-1), +1,0),0)),

If(LookingForGapDown, Cum(If(GapYesterday <= MinGap AND GapYesterday >

146
MinGap - GapIncrement, If(OPEN < Ref(CLOSE,-1), +1, 0),0)),
0))/NumGapsthruYesterday*100;

{by Jon DeBry}

Sideways Channels Exploration

Periodicity: Daily

Formulas

ColumnA: Top
Mov(Peak(1,H,1),45,S)-Ref(Mov(Peak(1,H,1),45,S),-45)

ColumnB: Bottom
Mov(Trough(1,L,1),45,S)-Ref(Mov(Trough(1,L,1),45,S),-45)

Filter:
ColA < 1 AND ColA > -1 AND ColB < 1 AND ColB > -1

Congestion Index
((HHV(C,80)-LLV(C,80))/LLV(C,80))*100

Consolidation breakout (upside)

If(Ref(Fml("congestion index"),-5),<,10, {and} If(Fml("congestion index"),>=,10,


{and} If(CLOSE,>,Ref(HHV(C,80),-5), {and}
If(Mov(V,5,S),>=,1.5*(Ref(Mov(V,60,S),-5)), +1,0),0),0),0)

Consolidation breakout (downside)

If(Ref(Fml("congestion index"),-5),<,10{%},{and} If(Fml("congestion


index"),>=,10{%},

{and} If(CLOSE,<,Ref(LLV(C,80),-5),{and}
If(Mov(V,5,S),>=,1.5*(Ref(Mov(V,60,S),-5)),+1,0),0),0),0)

from Richard Estes

STOCHASTIC AND RSI SYSTEM


Mov((RSI(8)-LLV(RSI(8),8))/(HHV(RSI(8),8)-(LLV(RSI(8),8))),5,w)*100

A formula like this works best with confirming indicators. If the MACD 13-34-89 is
above the zero line (purple line in window 2 above), it confirms and uptrend and the
indicator is usually more accurate. If the MACD 13-34-89 is below the zero line, then
a "short" indication from the StochRSI may give better results.StochRSI 13 also gives
excellent indicators- in this index it had 4 out of 5 winning signals in two year period.

147
The time between signals is of course longer. Check this method out on your favorite
issues.

from Andy G. andyg@megsinet.net

BPDL TREND FILTER

cum ((if ((mov((C-ref(C,-1)),21,s))>0,1,-1) * pwr(((mov((pwr(C-ref(C,-


1),2)),21,s))+1),.5)) + ((pwr(((pwr(C-ref(C,-1),2))+1),.5))) * if ((C>ref(C,-1)),1,-1))

(fml(" BPDL Trend Filter") - (ref((fml(" BPDL Trend Filter")),-21))) / ((hhv(fml("


BPDL Trend Filter"),21)) - (llv(fml("BPDL Trend Filter"),21)))

BUY -1 SELL 1

PFE Indicator:

Mov(If(C > Ref(C,-9), Sqr( Pwr( ROC(C,9,$),2) + Pwr(10,2))


/ Sum( Sqr( Pwr( ROC(C,1,$),2) +1), 9),-Sqr( Pwr(
ROC(C,9,$),2) + Pwr( 10,2)) / Sum(Sqr(Pwr(ROC(C,1,$),2)
+1),9)) * 100,5,E)

I use a 80, -80 trendline. I have stuck it in different things at different times. Right
now I have it crossing -80 with MACD 4, 35,5, crossing, RSI(9) up one day, and
selling pressure down one day.

from Stephen Zodkov

21 Day trigger

Look at these two oscillators in MSWIN, and compare them to Dahl. Put a 21 day
EMA on each, think of the 21 day ema as a trigger. See what they tell you -- Dahl is
long term, Ian is shortest term.

Raschke Oscillator = Mov(Fml( "Raschke 3-10" ),16,E)


where "Raschke 3-10" = Mov(C,3,S) - Mov(C,10,S)
Ian Oscillator = (Mov(C,4,S)-Mov(C,9,S)) + (Mov(C,9,S)-Mov(C,17,S))

from Alton Stephens

FibboGatto

FG1:
((c+ref(c,-1)+ref(c,-2)+ref(c,-3)+ref(c,-5)+ref(c,-8)+ref(c,-13)+ref(c,-21)+ref(c,-
34)+ref(c,-55)+ref(c,-89)+ref(c,-144))/c)*-1

{{{adding closing price only on fib days 1,2,3,5,8,13,21,34,55,89 and 144 and then
dividing by today's close}}}

FG2:

148
mov(((c+ref(c,-1)+ref(c,-2)+ref(c,-3)+ref(c,-5)+ref(c,-8)+ref(c,-13)+ref(c,-21)+ref(c,-
34)+ref(c,-55)+ref(c,-89)+ref(c,-144))/c)*-1,34,e)

{{{ 34 period mov avg of above indicator}}}

Look for crosses of the two indicators for positive or negatives.

Now, there are many whipsaws. I don't recommend this as a *system* at all, just as an
indicator. It really highlights some big moves but measuring it with the system test is
useless. You must use this as ONE of the tools -- not THE tool.

Regards, Jerry Gatto

Dynamic Zones

{Zamansky&Stendahl's Dynamic Zones for MS6.5 (From the TASC July1997


article). First, for the Lookback Periods plot a 9-day RSI along with StDev adjusted
rolling 70-day SMAs; e.g., as can be seen in the article's S&P500-example}

PR:=Input("Enter Periods for RSI",1,100,9);


PB:=Input("Enter Periods for BUY",1,100,70);
PS:=Input("Enter Periods for SELL",1,100,70);
UpZone:=Mov(RSI(PR),PS,S)+(1.3185 *Stdev(RSI(PR),PS));
LwZone:=Mov(RSI(PR),PB,S)-(1.3185 *Stdev(RSI(PR),PB));
UpZone;
LwZone;

Most indicators use a fixed zone for buy and sell signals. Here's a concept based on
zones that are responsive to past levels of the indicator.

One approach to active investing employs the use of oscillators to exploit tradable
market trends. This investing style follows a very simple form of logic: Enter the
market only when an oscillator has moved far above or below traditional trading
levels. However, these oscillator-driven systems lack the ability to evolve with the
market because they use fixed buy and sell zones. Traders typically use one set of buy
and sell zones for a bull market and substantially different zones for a bear market.
And therein lies the problem.

Once traders begin introducing their market opinions into trading equations, by
changing the zones, they negate the system's mechanical nature. The objective is to
have a system automatically define its own buy and sell zones and thereby profitably
trade in any market -- bull or bear. Dynamic zones offer a solution to the problem of
fixed buy and sell zones for any oscillator-driven system.

149
The algorithm for the dynamic zones is a series of steps. First, decide the value of the
lookback period t. Next, decide the value of the probability Pbuy for buy zone and
value of the probability Psell for the sell zone.

The area above and below the dynamic zones constitute the upper and lower 10%
boundaries. The zones appear to evolve with the market because they use a rolling 70-
day period of indicator values in their construction.

DAHL VARIATIONS

Dahl Volume Trend


Mov(C,55,VOL)-Ref(Mov(C,55,VOL),-15)

PVT Dahl Trend:


Mov((PVT()-Ref( PVT(),-15)),55,E)

Smoothed OBV Vol 88:


Mov((OBV()-Mov(OBV(),88,VOL)),55,E)

OBV Dahl Trend:


Mov((OBV()-Ref(OBV(),-15)),55,E)

Compare each to ordinary Dahl or some other trend indicator. Remember, I put a 21
EMA trigger on each.

from Alton Stephens

Dahl oscillator
I came up with the following to put Dahl into an oscillator format. It is the
STOCHRSI formula, replacing RSI with a 55 day Dahl. Does this reflect your
thinking on the indicator? It seems to lead changes in Dahl by a period or two, but
doesn't seem as fast as the STOCHRSI indicator. Checking a few stocks in my
database, there are very few times that it goes below zero, but it will 'peg out' at 100
for significant periods. Perhaps the 14 day smoothing is too short in relation to the 55
period primary indicator. A longer MA period seems to smooth it out significantly,
which would seem to defeat the purpose of using an oscillator.

Mov((mov(c,55,simp) - ref(mov(c,55,simp),-15)- LLV(mov(c,55,simp) -


ref(mov(c,55,simp),-15),14))/(HHV(mov(c,55,simp) - ref(mov(c,55,simp),-15),14)-
(LLV(mov(c,55,simp) - ref(mov(c,55,simp),-15),14))),14,E)*100

from Jim O'Donnell

FULL FORMULA FOR RSI

{The following is copied from the Formula Field of my *RSI


canonical_12_day_for_P_I indicator. Change m if you choose another # of periods n

150
for rsi.}

{I wrote my own "canonical" RSI(12) which coincides with MetaStock's RSI(12) if


m=2*n-1 where m is used below in Mov( ,m,E); n - a number of periods in rsi(n).
Mind that since I didn't use those particular tricks from the standard rsi(n) to shorten
the initial transitional period, this function and standard rsi(n) differ for about month
or so from the day 1. It was not that important for me, so I used this shortcut.}

100 - 100/
(1.+ If(Mov(If(P-Ref(P,-1)<0,-(P-Ref(P,-1)),0),23,E)=0,1000000,

Mov(If(P-Ref(P,-1)>0, P-Ref(P,-1), 0),23,E)


/Mov(If(P-Ref(P,-1)<0,-(P-Ref(P,-1)),0),23,E)
))
From: Vitaly Larichev vitaly@superlink.com

2 Day Hammer Exploration


Here is an exploration that pattern traders may find useful. It tends to pick up two
patterns: a two day hammer, that is if you combined the open for day 1 and close for
day 2, the resulting bar would be a hammer, and a pattern similar to a Ross Hook, as I
understand a Ross Hook.

Ref((C-L)/(H-L),-1)<=.30 AND

((C-L)/(H-L)) >= .70 AND

Ref(ATR(1),-1) >ATR(10) AND

ATR(1) >= ATR(10)

from Styk

ATR TRAILING STOP LOSS

For Long:
HHV(H - 2.5*ATR(5),10)

For Short:
LLV(L + 2.5*ATR(5),10)

Furthermore, it may be beneficial to dynamically adjust the number of lookback


periods in the HHV() or the LLV() function.
Yngvi Hardarson

Sine-Weighted Moving Average

Formula:
PI:=3.1415926;

151
SD:=180/6;
S1:=Sin(1*180/6)*C;
S2:=Sin(2*180/6)*Ref(C,-1);
S3:=Sin(3*180/6)*Ref(C,-2);
S4:=Sin(4*180/6)*Ref(C,-3);
S5:=Sin(5*180/6)*Ref(C,-4);
Num:=S1+S2+S3+S4+S5;
Den:=Sin(SD)+Sin(2*SD)+Sin(3*SD)+Sin(4*SD)+Sin(5*SD);
Num/Den
%%%%%%%%%%%%%

WRO AND WSO INDICATORS

MetaStock Formulas -- WRO and WSO Indicators

In the May 1998 issue of STOCKS & COMMODITIES, a Traders' Tip provided
MetaStock formulas for calculating support and resistance levels and the WRO
and WSO support and resistance oscillators. The Traders' Tip was based on my
article, "Automated Support And Resistance," also in that issue. Since then,
I've received many E-mail messages from STOCKS & COMMODITIES readers
about
it.
While the method was well received, the formulas provided were a bit
confusing and could use some clarification. Further, execution was slow and
screening of large numbers of stocks was difficult. Since then, I have
developed a faster and improved method for computing these indicators.

To begin, the support levels S1 through S6 and the resistance levels R1


through R6 are separate indicators (12 in all), and each should be entered
using the custom indicator option in the indicator builder.

S1 Indicator:
ValueWhen(1, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S2 Indicator:
ValueWhen(2, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S3 Indicator:
ValueWhen(3, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S4 Indicator:
ValueWhen(4, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S5 Indicator:
ValueWhen(5, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S6 Indicator:

152
ValueWhen(6, Ref(L,-4) = LLV(L,9), Ref(L,-4))

R1 Indicator:
ValueWhen(1, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R2 Indicator:
ValueWhen(2, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R3 Indicator:
ValueWhen(3, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R4 Indicator:
ValueWhen(4, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R5 Indicator:
ValueWhen(5, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R6 Indicator:
ValueWhen(6, Ref(H,-4) = HHV(H,9), Ref(H,-4))

These 12 indicators should be individually plotted with the price data as


points, not lines (click on each and change the style to the one on the
bottom of the style menu). The color red is recommended for the support
levels S1 through S6 and the color blue for the resistance levels R1 through
R6. Entering these formulas and changing the style takes a bit of time, but
once done, they can be saved as a template and easily applied to another
stock.

If you are interested only in computing the WRO and WSO indicators, then
these formulas can be entered as shown here. It is not necessary to compute
S1 through S6 or R1 through R6, since the new formulas are now
self-contained. The new WRO and WSO formulas also contain max and min
functions to ensure that the change for each level is either zero or 1. This
avoids a rare but occasional error when the price change is very large over
a short period.

WSO Indicator:
L1:=ValueWhen(1,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L2:=ValueWhen(2,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L3:=ValueWhen(3,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L4:=ValueWhen(4,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L5:=ValueWhen(5,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L6:=ValueWhen(6,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L1M:= Max(0,Min(1,Int(L1/C)));
L2M:= Max(0,Min(1,Int(L2/C)));
L3M:= Max(0,Min(1,Int(L3/C)));
L4M:= Max(0,Min(1,Int(L4/C)));
L5M:= Max(0,Min(1,Int(L5/C)));

153
L6M:= Max(0,Min(1,Int(L6/C)));

100*(1-(L1M+L2M+L3M+L4M+L5M+L6M)/6)

WRO Indicator:
L1:=ValueWhen(1,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L2:=ValueWhen(2,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L3:=ValueWhen(3,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L4:=ValueWhen(4,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L5:=ValueWhen(5,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L6:=ValueWhen(6,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L1M:= Max(0,Min(1,Int(L1/C)));
L2M:= Max(0,Min(1,Int(L2/C)));
L3M:= Max(0,Min(1,Int(L3/C)));
L4M:= Max(0,Min(1,Int(L4/C)));
L5M:= Max(0,Min(1,Int(L5/C)));
L6M:= Max(0,Min(1,Int(L6/C)));
100*(1-(L1M+L2M+L3M+L4M+L5M+L6M)/6)

The WRO and WSO oscillators are generally plotted together on a separate
scale from the price plot. It is helpful to add horizontal lines at zero and
100 on this same scale. Horizontal lines can be added by clicking on the
indicator and selecting "horizontal lines" from the Indicator Properties
menu.

These formulas run much faster (by 40 times) than the earlier formulas, and
theyÕve been tested successfully with both end-of-day data and real-time
data using MetaStock Professional Version 6.51.

-- Mel Widner, Ph.D., 703 791-5910

%%%%%%%%%%%%%
Gap1 System
===========
{BUY}
L>Ref(H,-1) OR
Cum(1)=LastValue(Cum(1))

{SELL}
H<Ref(L,-1) OR
Cum(1)=LastValue(Cum(1))

Gap2 System
===========
{BUY}
N1:=5;
L>Ref(HHV(H,N1),-1) OR
Cum(1)=LastValue(Cum(1))

154
{SELL}
N1:=5;

H<Ref(LLV(L,N1),-1) OR
Cum(1)=LastValue(Cum(1))

Gap3 System
===========
{Enter Long}
N1:=5;
L>Ref(HHV(H,N1),-1) OR
Cum(1)=LastValue(Cum(1))

{Exit Long}
N2:=3;
C<Ref(LLV(L,N2),-1) OR
Cum(1)=LastValue(Cum(1))

{Enter Short}
N1:=5;
H<Ref(LLV(L,N1),-1) OR
Cum(1)=LastValue(Cum(1))

{Exit Short}
N2:=3;
C>Ref(HHV(H,N2),-1) OR
Cum(1)=LastValue(Cum(1))

{from Ton Maas}

%%%%%%%%
TSI AND TSI MOVING AVERAGE
100*(Mov(Mov(Roc(C,1,$),25,E),13,E)/Mov(Mov(Abs(Roc(c,1,$)),25,E),13,E))

Mov(Fml("TSI"),20,E)

%%%%%%%%%
RSI DIVERGENCE EXPLORATION
{A simple exploration filter formula for finding a bullish divergence
between the RSI and the price is shown below. To find a bearish divergence,
replace > with <. The differences in the trough function was found through
an optimization routine and they may not be the best values for your
application.}

Ref(RSI(14),-1)>Trough(1,RSI(14),.8)
AND
Ref(CLOSE,-1)<Trough(1,CLOSE,.2)

{from Dan in Pocatello, ID}

155
%%%%%%%%%
Candle - Hanging Man/Hammer & CCI Trading System

enter long:
(Fml("Candle - Hammer")=1) AND
(CCI(11)<-50)

close long:
((CCI(11)<80) AND
(Ref(CCI(11),-1)>80)) OR
((CCI(11)<-80) AND
Ref(CCI(11)>-80,-1))

enter short:
(Fml("Candle - Hanging Man'")=-1) AND
(CCI(11)>50)

close short:
((CCI(11)>-80) AND
(Ref(CCI(11),-1)<-80)) OR
((CCI(11)<80) AND
Ref(CCI(11)>80,-1))

%%%%%%%%%%%
STIX INDICATOR
Mov((H+L)/2,5,S)-Mov((H+L)/2,35,S)

%%%%%%%%%%%
rsi dIVERGENCE
{RSI(9) DIVERGENCE BUY:}
If(RSI(9) >= HHV(RSI(9),19) AND CLOSE <HHV(CLOSE,19), 1,0) OR
If(CLOSE <= LLV(CLOSE,19) AND RSI(9) > LLV(RSI(9),19), 1,0)

{RSI(9) DIVERGENCE SELL:}


If(CLOSE >= HHV(CLOSE,19) AND RSI(9)<HHV(RSI(9),19),1,0) OR
If(RSI(9) <= LLV(RSI(9),19) AND CLOSE > LLV(CLOSE,19),1,0)

{You can substitute any formula for the "RSI(9)"}

{from Mike Arnoldi}

%%%%%%%%%%%
Denvelope (RSI)}

pds:=Input("Periods",2,200,14);
sd:=Input("Standard Deviations",.01,10,2);
D1:= RSI(pds);
alpha:=2/(pds+1);
mt:=alpha*D1+(1-alpha)*(If(Cum(1)<pds,D1,PREV));

156
ut:=alpha*mt+(1-alpha)*(If(Cum(1)<pds,D1,PREV));
dt:=((2-alpha)*mt-ut)/(1-alpha);
mt2:=alpha*Abs(D1-dt)+(1-alpha)*PREV;
ut2:=alpha*mt2+(1-alpha)*PREV;

dt2:=((2-alpha)*mt2-ut2)/(1-alpha);
but:=dt+sd*dt2;
blt:=dt-sd*dt2;
blt;
dt;
but;

{from Adam Hefner


VonHef@email.msn.com }
%%%%%%%%%%
HIGH LOW
Len:=Input("Periods",1,400,89);
(Mov((H - L + Abs(H - Ref(C,-1)) + Abs(L - Ref(C,-1)) ),len,E))/2

{ from Bob bjagow@jps.net }

%%%%%%%%%%%%%
CYLICAL SYSTEM
from Ton Maas ms-irb@wxs.nl

=============================================================
=
"Trading Stocks With A Cyclical System" by Jeffrey Owen Katz (TASC-Feb1999).
(Translated for MetaStock 6.5 by Ton Maas -The Netherlands - June1999).
----------------------------------------------------------------------------
(The system's original Easy Language formulas+system were derived from
theabove mentioned TASC article). My guess is that Equis (Alan McNichol) was
not in the possession of them when he wrote the Equis version of the system,
back in the Feb99 Trader's Tips section of TASC).

Cyclical System

- J O Katz

Formula:
{TASC Feb99}
thresh:= {omit whipsaw} 4;
k:= {roc comparison period} 3;
m:= {cycle period} 63;
hld:= {maximum period holding position} 10;
Value1:= {volatility}
Stdev(Mov(C,m,S)-Mov(C,m+k,S),20);
Value2:= {roc, relative comparison ratio}
Mov(C,m,S)-Mov(C,m+k,S);

157
tv1:= thresh*Value1;
EL:={Enter Long} Value2>tv1;
CL:={Close Long} Ref(Cross(Value2,tv1),-hld);
ES:={Enter Short} Value2<tv1;
CS:={Close Short} Ref(Cross(tv1,Value2),-hld);
JKcycl:=If((EL>0)=1,+10,
If((ES>0)=1,-10,0));
JKcycl

Name:
Jeffrey Owen Katz - Cyclical System
Notes:
{February 1999 - TASC-article (see also TRADERS' TIPS)}

Formulas:
{copy-repeat all that is printed below when applying for the right rule}
thresh:= {omit whipsaw} 4;
k:= {roc comparison period} 3;
m:= {cycle period} 63;
hld:= {maximum period holding position} 10;
Value1:= {volatility}
Stdev(Mov(C,m,S)-Mov(C,m+k,S),20);
Value2:= {roc, relative comparison ratio}
Mov(C,m,S)-Mov(C,m+k,S);
tv1:= thresh*Value1;

Rules:
{Enter Long} Value2>tv1
{Close Long} Ref(Cross(Value2,tv1),-hld)
{Enter Short} Value2<tv1
{Close Short} Ref(Cross(tv1,Value2),-hld)

{After entering the formulas, click OK. Then click Options. On the Testing
page, set the Trade Delay to zero, set Positions to "both", and then set any
other desired options (apart from Optimizing, which is not advisable; leave
the factory default settings). Click OK to save the changes, and then open a
chart and run the system.}

%%%%%%%%%%%%

BODY MOMENTUM

{I was reading in Perry Kaufman's latest book and he described a little


oscillator he called "Body Momentum". This simply calculates the momentum of
the closes above the opens versus the closes below the opens. The theory is
that as prices move up, closing prices will be higher than opening prices

158
and vice-versa for down. If this oscillator is above 70 then the whites
(Candle-sticks) dominate and below 30 the blacks are dominant.}

{I also added a 3 day moving average to the calculation (for smoothing).}

{Here is the code:}

Lb:=Input("Look-Back Period?",3,60,14);
B:=CLOSE - OPEN;
Bup:= Sum(B > 0, Lb);
Bdn:= Sum(B < 0, Lb);
BM:=(Bup/(Bup+Bdn))*100;
Mov(Bm,3,S)

{from Adam Hefner}


%%%%%%%%%%%%

ST OSCILLATOR

{The StTO is really nothing unique. It is basically a momentum indicator and


plots very similar to the "Chande Momentum Oscillator" with the main
difference being the "StTO" doesn't seem to swing as far as the CMO.
I am not sure how the math is calculated for the CMO, but the (basic) math
for the StTO is: (Close- Yesterday's Close) /
(H-L)}

{Here is the MetaStock code I use:}

{name: StTO}

{Short-term Trend Oscillator}

Lb:=Input("Smoothing Period?",1,60,5);
Num:=C-Ref(C,-1);
Den:=H-L;
Mn:=If(Mov(Num,Lb,S)=0,.01,Mov(Num,Lb,S));
Md:=If(Mov(Den,Lb,S)=0,.01,Mov(Den,Lb,S));
(Mn/Md)*100

{Adam Hefner}
%%%%%%%%%%%%%

CCI SPIKE TRADING SYSTEM

{This system uses the momentum Commodity Channel Index (CCI) indicator to
find short-term bottoms in the market. The CCI indicator is extremely

159
volatile and is generally difficult to use when trading the S&P 500 Index.
We, however, have turned this volatility into a trading advantage by using
the spread or gap between the CCI index and its moving average as a reversal
signal. Specifically if the gap is larger then a certain percentage and CCI
indicator crosses above its moving average we buy the market. The system
remains in the market for a short period of time, exiting the trade as the
indicators cross to the downside. As designed, this system only trades long
the market; it can however be altered to short the market. It is best used
in choppy bullish markets similar to the 1995 bull market.}

{Trading Tactics: This short-term bullish trading system exploits over


extended markets. Futures, options, and mutual fund traders should take full
advantage of this high probability trading system, either by taking outright
positions or avoiding declining markets. The code for this system can be
reversed to trade short positions. This system should be used in place of
longer-term momentum systems in strong bullish choppy type markets. This
system rarely exits at the market intermediate peak, so other exiting
signals may be used in place of our indicator crossover technique.}

Enter long:

Ref(CCI(13)/(Mov(CCI(13),3,S)),-1)>1.5 AND
Cross(CCI(13),(Mov(CCI(13),3,S))) AND
Ref(CCI(13),-1)<-25

Exit long:

Cross((Mov(CCI(13),3,S)),CCI(13)) AND
Ref(CCI(13),-1)>200

{from Craig Monroe}


%%%%%%%%%%%

LOOKBACK

Formula: X := Stdev(C, 30);


Y := Ref(X, -1);
Z := 1+((X-Y)/X);
If(Cum(1)=1, 20, Min(Max(Prev*Z, 20), 60))

BuyBreak

Formula: HHV(H, LastValue(Fml("LookBack")+Prev-Prev))

BuyExit

Formula: LLV(L, LastValue(Fml("LookBack")/2+Prev-Prev))

160
SellBreak

Formula: LLV(L, LastValue(Fml("LookBack")+Prev-Prev))

SellExit

Formula: HHV(H, LastValue(Fml("LookBack")/2+Prev-Prev))

BreakWhere
Formula: TopB := Ref(Fml("BuyBreak"), -1);
LowB := Ref(Fml("SellBreak"), -1);
((O+H+L+C)/4 - LowB)*100/(TopB-LowB);

DBS-System

Enter Long: H > Ref(Fml("BuyBreak"), -1)


Close Long: L < Ref(Fml("BuyExit"), -1)
Enter Short: L < Ref(Fml("SellBreak"), -1)
Close Short: H > Ref(Fml("SellExit"), -1)

This is George Pruitt's ("Futures Truth") basic system. It is also the basic
system used as the basis for Thomas Stridsman's year-long series of articles
about system development and tweaking.
%%%%%%%%%%%
STOCHASTIC MOMENTUM
SMI-Plex:=
StochMomentum(2,1,2)+StochMomentum(3,2,1)+StochMomentum(4,2,3)+StochMo
mentum
(5,3,5)+StochMomentum(8,21,13)+StochMomentum(13,25,2)

SMI13E-Plex:=
Mov(StochMomentum(2,1,2)+StochMomentum(3,2,1)+StochMomentum(4,2,3)+Stoc
hMome
ntum(5,3,5)+StochMomentum(8,21,13)+StochMomentum(13,25,2),13,E)

{from Craig DeHaan}


%%%%%%%%%%%%
BradCCI

BradCCI: From Bill S.

Plot 1: BradCCI Line 1: (((H+L+C)/3)-Mov(C,28,S))/(.015*Std(C,28))

Plot 2: BradCCI Line 2: Std(((h+l+c)/3),28)

To Line 1, you can also add trend lines, if you wish:

Plot 1:

161
1. BradCCI Line 1: (((H+L+C)/3)-Mov(C,28,S))/(.015*Std(C,28))
2. trend(100,100)
3. trend(-100,-100)
4. trend(0,0)

%%%%%%%%%%%%%%
McClellan Oscillator
rev. 01/06/97
The McClellan Oscillator, developed by Sherman and Marian McClellan, is a
market breadth indicator that is based on the smoothed difference between
the number of advancing and declining issues on the New York Stock Exchange.
The McClellan Oscillator is one of the most popular breadth indicators. Buy
signals are typically generated when the McClellan Oscillator falls into the
oversold area of -70 to -100 and turns up. Sell signals are generated when
the oscillator rises into the overbought area of +70 to +100 and then turns
down.
Extensive coverage of the McClellan Oscillator is provided in their book
Patterns for Profit .

To plot the McClellan Oscillator, create a composite security in The


DownLoader™ of Advancing Issues minus Declining Issues. Open a chart of the
composite in MetaStock™ and plot this custom indicator.

Mov(CLOSE,19,EXPONENTIAL) - Mov(CLOSE,39,EXPONENTIAL)

McClellan Summation Index


rev. 01/06/97
The McClellan Summation Index is a market breadth indicator developed by
Sherman and Marian McClellan. It is a long-term version of the McClellan
Oscillator and its interpretation is similar to that of the McClellan
Oscillator except that it is more suited to major trend reversals.

For more extensive coverage of the index refer to the book Patterns for
Profit, by Sherman and
Marian McClellan.

McClellan suggests the following rules for use with the summation Index:

Look for major bottoms when the Summation Index falls below -1300.

Look for major tops to occur when a divergence with the market occurs above
a Summation Index level of +1600.

The beginning of a significant bull market is indicated when the Summation


Index crosses above +1900 after moving upward more than 3600 points from its

162
prior low (e.g. the index moves from -1600 to +2000).

The summation index is plotted by adding the Cum function to the McCllellan
Oscillator. The formula is Cum(Mov(C,19,E) - Mov(C,39,E)).

%%%%%%%%%%%%%%%%%%%

JACK LANDIS' WEIGHTED STOCHASTIC (SHORTENED TO LANDIS)

((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16)+(S
toch(21,5)*.10))

LANDIS 3 WEEK S M A

mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),15,s)

landis multiple time periods


formula #1
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),15,s)
formula #2
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),10,s)
formula #3
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),5,s)
formula #4
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),2,s)

multiple slopes of landis


formula #1
slope(mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,
8)*.16)+(Stoch(21,5)*.10)),15,s),2)
formula #2
slope(mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,
8)*.16)+(Stoch(21,5)*.10)),10,s),2)
formula #3
slope(mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,

163
8)*.16)+(Stoch(21,5)*.10)),5,s),2)

%%%%%%%%%%%%%%%
Barnes' Acceleration

The Barnes' Acceleration measures rate of price change as opposed to price


levels

If the Barnes' Acceleration sustains the value of -1 for many days then the
security may be ready to show strong trend or it may already be trending.
Examine the chart for prolonged values at -1. This may indicate an upcoming
stall or turnaround. The number of days needed may be different depending on
the type of issue. A utility stock may need to sustain the -1 level for 10
days whereas a highly volatile technology stock may need to sustain the -1
trend for as little as 5 days.

From the 1981 Technical Commodity Yearbook, Robert M. Barnes


formula 1: if(mov(fml("Barnes' acceleration",2) - ref(fml("Barnes'
acceleration",2),-1),20,e)>0.0001,1, if(mov(fml("Barnes' acceleration",2) -
ref(fml("Barnes'
acceleration",2),-1),20,e)<-0.0001,-1,0))
formula 2: mov((c-ref(c,-1))/ref(c,-1),daysm,e)

Barnes' Adaptive Forecast

Based on the premise that closing price may be predictable based on previous
closes

See (1981 Technical Commodity Yearbook Robert M. Barnes Van Nostrand


Reinhold 1981) for theory and applications.

formula 1: if(fml("Barnes' adaptive forecast",2)>0.05,1,if(fml("Barnes'


adaptive forecast",2)<-0.05,-1,0))
formula 2: mov(c,dayf,e) - ref(mov(c,dayf,e),-1)

Barnes' Moving Average

See (1981 Technical Commodity Yearbook Robert M. Barnes Van Nostrand


Reinhold 1981) for theory and applications.

if (c - mov( c, dayf, e) > pf,


{ Then Action } 1,
{ Else Action } if ( mov( c, dayf, e) - c > pf, { Then } -1, { Else } 0))

{ Notice that comments may be placed within braces }

%%%%%%%%%%%%%%%%

164
CHANDE & KROLL'S R2 INDICATOR

rev. 01/06/97

In their book "The New Technical Trader," Chande & Kroll introduce the r2
indicator. They state that
"the primary use of r2 is as a confirming indicator" and that "it is a
lagging indicator that shows
the strength of the trend."

In MetaStock the r2 formula is:

Pwr(Corr(Cum( 1 ),C,14,0),2)

They also present a smoothed r2 which would be:

Mov(Pwr(Corr(Cum( 1 ),C,14,0),2)*100,14,S)

For interpretation refer to Chande & Kroll's book, as stated above.


%%%%%%%%%%%%%%%

PRICE ACTION INDICATOR (PAIN)

If you were only given today's open, high, low and


close, how could you make heads or tails of it?
The Price Action Indicator (PAIN) can help. The formula
returns a single value that weighs
intra-day momentum (C-O), Late Selling Pressure (LSP)
(C-L), and Late Buying Pressure
(LBP) (C-H). The formula is proven by constructing ideal
limit-up and limit down scenarios in bond
futures. The output is shown to be consistent with the
interpretation of Japanese candlestick
patterns. See Michael B. Geraty (1997). "Getting Better
Directions" Futures Vol. 26: Aug.

PAIN

((C-O)+(C-H)+(C-L))/2
%%%%%%%%%%%%%%%%%%%

Natenberg's Volatility
rev. 01/21/97

165
Historical volatility is defined by Sheldon Natenberg, as the standard
deviation of the logarithmic
price changes measured at regular intervals of time. In Mr. Natenberg's
book, "Option Volatility &
Pricing," he covers volatility in detail and gives the formula for computing
historical volatility. In
MetaStock, the equivalent formula would be:

Std( Log( C / Ref( C ,-1 ) ) ,10 ) * Sqrt( 365 / 7 )

The above assumes Weekly Data. To utilise this with Daily Data, the
MetaStock formula would be:

Std( Log( C / Ref( C,-1) ),10 ) * Sqrt( 365 )

For further interpretation refer to the book "Option Volatility & Pricing,"
by Sheldon Natenberg.

NAT'S VOLT

Std(log(c/ref(c,-1)),10)*sqr(365/7)

%%%%%%%%%%%%%%%
The Tema StochRSI formula I use is Tema smoothed and I subtract 0.5 so I
can plot it as a histogram. It's:}

Periods := Input("Enter Tema Smoothing Periods",5,233,13);


Tema(((RSI(Periods) - LLV(RSI(Periods),Periods)) /
((0.0001+HHV(RSI(Periods),Periods)) -
LLV(RSI(Periods),Periods))) -0.5,Periods)

{from Jim Greening}

%%%%%%%%%%%%%%%%%5
DEVSTOP
Here's what I think a DEVSTOP is in MetaStock language, described in Kase's
"Trading with the Odds", and better described in Kaufman's "Trading Systems
and Methods". It uses a 2-day range, calculates an average range and SD of
the range, and then draws 4 lines below the high, at 1 range and 0,1,2, and
3 SD's. "2.2" and "3.6" are corrections for skew of the distribution.

AVTR:=Mov(HHV(H,2) - LLV(L,2),20, S);


SD:=Stdev(HHV(H,2) - LLV(L,2),20);
HHV(H-AVTR-3.6*SD, 20);
HHV(H-AVTR-2.2*SD,20);

166
HHV(H-AVTR-SD,20);
HHV(H-AVTR,20);

from Mikelu

%%%%%%%%%%%%

WEEKLY PIVOT POINT

{Weekly Pivot Point Projection 8/4/99}

Dw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
{Weekly Typical Price}
PP1:=If(Dw=1,
{then}(Ref(HighestSince(1,Dw=1,H),-1)+
Ref(LowestSince(1,Dw=1,L),-1) +
Ref(C,-1))/3,
{else}0);
{Weekly High}
Wh1:=If(Dw=1,
{then}Ref(HighestSince(1,Dw=1,H),-1),
{else}0);
{Weekly Low}
Wl1:=If(Dw=1,
{then}Ref(LowestSince(1,Dw=1,L),-1),
{else}0);
Wh:=ValueWhen(1,Wh1>0,Wh1);
Wl:=ValueWhen(1,Wl1>0,Wl1);
PP:=ValueWhen(1,PP1>0,PP1);
{Resistance 1}
R1:=(2*PP)-Wl;
{Support 1}
S1:=(2*PP)-Wh;
{Resistance 2}
R2:=(PP-S1)+R1;
{Support 2}
S2:=PP-(R1-S1);
R2;
R1;
S1;
S2;

%%%%%%
ATR MODIFIED

167
prd1:=input("enter ATR period",1,9999,7);
prd2:=(prd1*2)-1;
{max (absolute) of yesterday's close to today's high or today's low}
myatr1:=Max(Abs(Ref(C,-1)-H),Abs(Ref(C,-1)-L));
{max of yesterday's close to today's high or today's low or today's range}
myatr2:=Max(myatr1,H-L);

{
%%%%%%%%%%%%%%%%%

HIGHEST HIGH SINCE BUY SIGNAL

> Anyone know how to keep track of, for example, the highest high since a
buy signal was triggered? I want to > add this into a system test that I am
trying to run.

HighestSince(1, {Buy Signal-->}Cross(C,Mov(C,20,E))


,H)

from Ken

%%%%%%%%%%%%%%%%%%

FORECAST OSCILLATOR SYSTEM ALTERNATIVE

Enter long:
Cross(ForecastOsc(C,21),Mov(ForecastOsc(C,21),3,E)) AND
Cross(ForecastOsc(C,21),0)

Exit long:
Cross(Mov(ForecastOsc(C,21),3,E),ForecastOsc(C,21)) AND
Cross(6,ForecastOsc(C,21))

{You can use alert() function on either if you don't require both conditions
to fire on the same day.}

%%%%%%%%%%%%%%%%%%%%

FORECAST OSCILLATOR SYSTEM

Enter long:
Cross(ForecastOsc(C,21),Mov(C,3,E)) AND

168
Cross(ForecastOsc(C,21),0)

Exit long:
Cross(Mov(C,3,E),ForecastOsc(C,21)) AND
Cross(6,Mov(C,3,E))

%%%%%%%%%%%%%%%
EQUIVILANT TO WILDERS TR

Wilders(TR,periods) = Mov(TR,2*periods-1,E)

%%%%%%%%%%%%%%%%%%
TRUE RANGE FORMULA

TR = (H - L + Abs(H - Ref(C,-1)) + Abs(L - Ref(C,-1)) )/2

{from Bob Jagow}

CREATING DYMANIC VERTICAL LINES

from Ken
These are dynamic moving vertical lines. Each new bar causes the line to move
orward one bar.
How to Create a Vertical Line in MetaStock

{Plot in Stoch window}


{...you can change the 100 and 0 to 80/20 or ?}
n:=Input("Bars Before LastLoadedBar", 0,1000,89);
LastLoadedBarNum:=LastValue(Cum(1));
If(Cum(1)=(LastLoadedBarNum-n)+1,100,0)
------------------
....or

Create a new Expert.


Place the following in "Trends"/"Bullish".

n:=89;
LastLoadedBarNum:=LastValue(Cum(1));
Cum(1)=(LastLoadedBarNum-n)+1

In "Corner", UNcheck "Display symbol in Expert corner".


In "Ribbon", check Display Ribbon, Display Vertical Line, and "Ribbon's inner
window".
Delete or rename the "Neutral" label.
Choose Bullish color.

Plot Stochastic on chart, attach Expert, then drag Expert to Stochastic inner window

169
SUPPORT AND RESISTANCE

I wrote this MetaStock Expert for calculating the support 1 & 2 and resistance 1 & 2
as per Futures magazine, October 1999, page 52.

----------------------------- start --------------------------

FIRST RESISTANCE: WRITEVAL(-L+(2* (H+L+C)/3),1.2)


SECOND RESISTANCE: WRITEVAL(((H+L+C)/3) +((-L+(2*
(H+L+C)/3))-(-H+(2* (H+L+C)/3))),1.2)
FIRST SUPPORT:
WRITEVAL(-H+(2*(H+L+C)/3),1.2)
SECOND SUPPORT: WRITEVAL(((H+L+C)/3)
-((-L+(2* (H+L+C)/3))-(-H+(2* (H+L+C)/3))),1.2)

-------------------------------- end --------------------------

from Mike Arnoldi

VOLUME ACCUMULATION PERCENTAGE

I contacted David Vomund by e-mail and he was kind enough to mail me the
equations required to calculate the VAP. I've programmed them in MetaStock as
follows:

VOLUME ACCUMULATION PERCENTAGE

Periods:=Input("Time Periods",1,60,21);

X:=(2*C-H-L)/(H-L);

TVA:=Sum(V*x,Periods);

TV:=Sum(V,Periods);

VA:=100*TVA/TV;

VA

from Tom Strickland

170
ALLIGATOR INDICATORS

from Gary Randall -- Brunswick, Maine

Alligator Indicators - Bill William, "Trading Chaos"


----------------------------------------------

Chaos Blue BL

{Alligator Blue Balance Line - Jaw}


{13 bar smoothed average offset 8 bars}

Ref(Wilders(MP(),13),-8);
----------------------------------------------

Chaos Red BL

{Alligator Red Balance Line - Teeth}


{8 bar smoothed average offset 5 bars}

Ref(Wilders(MP(),8),-5);
----------------------------------------------

Chaos Green BL

{Alligator Green Balance Line - Lip}


{5 bar smoothed average offset 3 bars}

Ref(Wilders(MP(),5),-3);
----------------------------------------------

Chaos Gator

{ Chaos Alligator }
{ Plot as histogram }

green := Fml("Chaos Green");


red := Fml("Chaos Red");
blue := Fml("Chaos Blue");

171
If(green > red AND red > blue, green - blue,
If(blue > red AND red > green, green - blue, 0));
----------------------------------------------

CHAOS AO

{ Chaos Awsome Oscillator - measures momentum }


( A very close approximation of MFI }
{ Plot as histogram }

Mov(MP(),5,S) - Mov(MP(),34,S);
----------------------------------------------

Chaos AO Signal Line

{ Chaos Awsome Oscillator Signal Line }


{ Plot as line over AO histogram }

Mov(Mov(MP(),5,S) - Mov(MP(),34,S),5,S)
----------------------------------------------

Chaos AC

{ Chaos Accelerator/Decelerator Oscillator }


{ Measures acceleration }
{ Plot as histogram }

Fml("Chaos AO") - Mov(Fml("Chaos AO"),5,S);


----------------------------------------------

Chaos Fractal

{ Chaos Fractal (simple version +1=Up, -1=Dn) }

High1 := Ref(HIGH,-2);
High2 := Ref(HIGH,-1);
High3 := Ref(HIGH,0);
High4 := Ref(HIGH,1);
High5 := Ref(HIGH,2);
Low1 := Ref(LOW,-2);
Low2 := Ref(LOW,-1);

172
Low3 := Ref(LOW,0);
Low4 := Ref(LOW,1);
Low5 := Ref(LOW,2);
Fractal :=
If((High3 > High1) AND (High3 > High2) AND (High3 > High4) AND (High3
>
High5), +1,0);

Fractal :=
If((Low3 < Low1) AND (Low3 < Low2) AND
(Low3 < Low4) AND (Low3 < Low5),
If(Fractal > 0, 0, -1), Fractal);

Fractal;

EXPERIMENTAL WILLIAMS TRADING SYSTEM

A trading system based on work of Bill Williams

from jcob3@prodigy.com

Enter Long:

Cross(C,Fml("chaos green bl")) AND Fml("chaos green bl") > Fml("chaos blue
bl")

Close Long:

Cross(Fml("chaos green bl"),C) AND Fml("chaos blue bl") > Fml("chaos green
bl")

I tested this on several different stocks and it shows potential. I really


haven't spent too much time on it yet so I'm not yet sure of the
significance of the other indicators. The above was just what I could throw together
based upon what my eyes on the chart with the indicators showed me.

Jeff

SHIFTED TSMA INDICATOR

You could use the Reference (Ref) function to shift your indicator back in time and
you could add or multiply by a constant or variable to give your indicator a vertical
shift. I've never used a time series moving average so

173
I'm kind of out of my league, but I guess it could look like this:

TSMA:= Mov(CLOSE,5,TIMESERIES);
ShiftedTSMA:= Ref(TSMA, -1) + 2;
ShiftedTSMA

from Ken Wallace gcwallace@home.com

DMTF TRADING SYSTEM

I know I'm a little slow, but I've just gotten around to working on the Dynamic
Multiple Time Frame indicators given by Robert Krausz in the 1999 Bonus Issue of
TASC.

The code for the actual indicators can be found at the Equis website (www.equis.com)
so I won't post them again here. I've been testing a system based on these indicators
on Best Buy (a stock that seems to be quite amenable to system trading) and getting
very good results. The system is currently for long trades only; I'll work on shorting
later. Here's what I've got so far

Enter Long:

day:=DayOfWeek();

Fml("dynamic balance")>Fml("dynamik balance point steps")

AND Fml("fixed balance point")>Ref(Fml("fixed balance Point"),-5)

OR Fml("tendency")>0 AND day=5

Close Long

Cross(Fml("dynamik balance point steps"),Fml("dynamic balance"))

AND Fml("fixed balance point")<Ref(Fml("fixed balance Point"),-5)

The problem is that the close is not defined, meaning that the two events which
initiate the close do not have to happen. The DBPS can cross the DB without the 2nd
condition occuring. Then, when later, the 2nd condition does occur, sell is not
triggered because the cross over has not happened simultaneously with the 2nd
condition. Theoretically, if we follow the system strictly, this can lead to a complete
loss. I understand that I can set arbitrary stops, but I prefer to let the system do the
work. Simply reversing the entry signal and other tries, such as support breakthoughs,
drastically reduce the result.

174
Regards,

Jeff jcob3@prodigy.net

CODING EXAMPLE

If yesterdays high is greater than the high of 2 days ago// and the low 5 days ago is
less than or equal to the high 4 days ago// and it is Wednesday
Try this:
Ref(H,-1)>Ref(H,-2) AND
Ref(L,-5)<=Ref(H,-4) AND
Dayofweek() = 3

from Paul Beattie

PERSISTENCE OF MONEY FLOW

Chaikin's Money Flow is a built-in MetaStock indicator, as follows: cmf(periods)

Persistence of Money Flow (PMF%)

Pds1:= Input("CMF Periods?",1,100,21);


Pds2:= Input("PMF Periods?",10,1000,120);
Sum((cmf(Pds1)>0),Pds2)/(Pds2/100)

{from HHP}

Persistence or (PMF%) is the percentage of days over 6 months that the Chaikin
Money Flow Oscillator is above 0. The Chaikin Money Flow Oscillator formula
default uses a 21 day money flow sum divided by the 21 day sum
of daily volume. HHP sent the correct indicator formula for persistence, tho you can
modify it by selecting 1 for "Pds1" if you prefer to create a 120 day cumulative
money flow indicator to do what you are suggesting. The cumulative money flow
indicator often uses a 90SMA trigger.

{from Craig DeHaan}

STOCHPVT INDICATORS

Though not directly related to the volume percent indicator, I have recently been

175
using a volume indicator that I wrote myself in MetaStock's formula language. It uses
the same idea that Chande used to turn RSI into the
StochRSI oscillator and the preprogrammed Price Volume Trend function. Price
Volume Trend is similar to On Balance Volume, except that as the volume is
accumulated, it is weighted according to the percent price change from the previous
close.

I use fast and slow "stochastic" lines to judge when either accumulation or
distribution is taking place. I used a look back period of 19 days which fits my style.
Signals are generated by the fast crossing above or below the slow lines. I have not
worked with it enough to say whether or not divergences offer signals too.

Formulas for the StochPVT are shown below:

{Fast line}

Mov((PVT()-LLV(PVT(),19))/
(HHV(PVT(),19)-LLV(PVT(),19)), 5, S)

{Slow Line}

Mov(Mov((PVT()-LLV(PVT(),19))/
(HHV(PVT(),19)-LLV(PVT(),19)), 5, S),3,S)

{from harelsdb@aol.com}

ONE DAY MONEY FLOW

The One Day Money Flow Indicator (some also call this indicator the One Day
Accumulation/Distribution Indicator) MetaStock formula is the following:

(((Close-Low) - (High-Close)) / (High-Low)) * Volume

{from Marcel Knechtle}

THE INSYNC INDEX

The formula from Equis: Insync Index (rev. 01/06/97)

The interpretation for the following formulas came from the article "The Insync
Index", by Norm North, in Technical Analysis of Stocks & Commodities Jan 1995.

176
All of these formulas are necessary for the last one, Insync Index to run properly.
They are listed in the order in which they should be copied and pasted into the
MetaStock Formula Builder

BOLInSLB
Mov( C ,20 ,S ) - 2 * ( Std( C ,20 ) )

BOLInSUB
Mov( C ,20 ,S ) + 2 * ( Std( C ,20 ) )

BOLInS2
( C - Fml( "BOLInSLB" ) ) / ( Fml( "BOLInSUB" ) - Fml( "BOLInSLB" ) )

BOLInSLL
If( Fml( "BOLInS2" ) ,< , .05 ,-5 ,If( Fml( "BOLInS2" ) ,> ,.95 ,5 ,0 ) )

CCIInS
If( CCI(14 ) ,> ,100 ,5 ,If ( CCI(14 ) ,< ,-100 ,-5 ,0 ) )

EMVInS2
EMV(10 ,S ) - Mov( EMV(10 ,S) ,10 ,S )

EMVInSB
If( Fml( "EMVInS2" ) ,< ,0 ,If( Mov( EMV(10 ,S ) ,10 ,S ) ,< ,0 ,-5 ,0 ) ,0 )

EMVInSS
If( Fml( "EMVInS2" ) ,> ,0 ,If( Mov( EMV(10 ,S ) ,10 ,S ) ,> ,0 ,5 ,0 ) ,0 )

MACDInS2
MACD( ) - Mov( MACD( ) ,10 ,S )

MACDinSB
If( Fml( "MACDInS2" ) ,< ,0 ,If( Mov( MACD( ) ,10 ,S ) ,< ,0 ,-5 ,0 ) ,0 )

MACDInSS
If( Fml( "MACDInS2" ) ,> ,0 ,If( Mov( MACD( ) ,10 ,S) ,> ,0 ,5 ,0 ) ,0 )

MFIInS
If( MFI( 20 ) ,> ,80 ,5 , If( MFI( 20 ) ,< ,20 ,-5 ,0 ) )

PDOInS2
DPO( 18 ) - Mov( DPO( 18 ) ,10 ,S )

PDOInSB
If( Fml( "PDOInS2" ) ,< ,0 ,If( Mov( DPO( 18 ) ,10 , S) ,< ,0 ,-5 ,0 ) ,0 )

PDOInSS
If( Fml( "PDOInS2" ) ,> ,0 ,If( Mov( DPO ( 18 ) ,10 ,S) ,> ,0 ,5 ,0 ) ,0 )

177
ROCInS2
ROC( C ,10 ,$ ) - Mov( ROC( C ,10 ,$ ) ,10 ,S )

ROCInSB
If( Fml( "ROCInS2" ) ,< ,0 ,If( Mov( ROC( C ,10 ,$ ) ,10 ,S ) ,< ,0 ,-5 ,0 ) ,0 )

ROCInSS Index
If( Fml( "ROCInS2" ) ,> ,0 ,If( Mov( ROC( C ,10 ,$ ) ,10 ,S ) ,> ,0 ,5 ,0 ) ,0 )

RSIInS
If( RSI(14 ) ,> ,70 ,5 ,If( RSI(14 ), < ,30 ,-5 ,0 ) )

STO%dInS
If( Stoch(14 ,3 ) ,> ,80 ,5 ,If( Stoch(14 ,3 ) ,< ,20 ,-5 ,0 ) )

STO%kInS
If( Stoch(14 ,1) ,> ,80 ,5 ,If( Stoch(14 ,1 ) ,< ,20 ,-5 ,0 ) )

InSync Index
50 + Fml( "CCIInS" ) + Fml( "BOLInSLL" ) + Fml( "RSIInS" ) + Fml( "STO%kInS "
) + Fml( "STO%dInS" ) + Fml( "MFIInS" ) + Fml( "EMVInSB" ) + Fml( "EMVInSS"
) + Fml( "ROCInSS" ) + Fml( "ROCInSB" ) + Ref (Fml( "PDOInSS" ) ,-10 ) + Ref
(Fml( "PDOInSB" ) ,-10 ) + Fml( "MACDInS S" ) + Fml( "MACDInSB" )

These formulas were provided by Barry Millman. All questions should be addressed
to him at 73374.1364@Compuserve.com.

Mr. Millman wrote these formulas using many Custom Formula slots for clarity and
ease of understanding. Please note that the final formula `InSync Index' requires all of
the previous formulas to be correct.

Multipart formulas
QUESTION:

I've got a specific question. I use WOW and MetaStock. Suppose I've got some
indicator that ranges from 0 to 100 and I have a system that says "buy when the
indicator goes above 90 and hold until it goes below 10 and then sell" or something.
Notice that if the indicator is between 10 and 90 that you don't know whether that's a
hold or a don't hold unless you know whether it last crossed 90 or 10. So far so good.
Now suppose I want to combine the signal from this system with another
indicator/system so that I can say something like "buy when system #2 says buy only
if system #1 is in "hold the stock" mode." This may take the form of another indicator
that is "1" when the system is in hold mode and "0" when it is in don't hold mode.
This seems like a general problem that must come up often but it is not obvious to me
how to code it. I'll bet other people could benefit from the answer as well.

178
Bob Anderton

ANSWER:

Thanks to all of you for the great help and input to the question of how to deal with
combining the indicators in a system when one of them gives a signal by crossing.
There were two responses, one can be seen in #3310 from Larry on the Yahoo!
MetaStock board (thanks Mike) which is answering a slightly different question. That
solution seems like what one would use if one wanted to look for system 2 signalling
a buy the same day as system 1 signalling a buy by crossing a value. What I actually
wanted to do was have a way of looking for system 2 signalling a buy during anytime
that system 1 was saying hold because its last signal had been a buy.
This was addressed very nicely by Paul in message #3311. I took his idea to make the
following indicator:
If(BarsSince(Cross(Fml("Indicator1"),90))<BarsSince(Cross(10,Fml("Indicator1"))),1
,0)

This makes a new indicator that is 1 when the last signal is a buy and 0 when the last
signal was a sell. Imagine that this is a really long term indicator. Now you can look
for your short term indicator #2 to signal a sell and just AND it with this new
indicator being = 1, meaning that the first indicator was in hold mode.

This is a big step forward for me. I'd never used this BARSSINCE function
before(which is PERIODSSINCE for WOW) and this was key to being able to do this
I think.

Bob Anderton

GAP TRADING

ere is the gap-trading system code for use in Equis International's MetaStock
software. For practical reasons, the system has been defined as an indicator rather
than a system, showing the cumulated profit.

dn:= 1.0;
up:= 1.0;
gap:= 100*(OPEN - Ref(CLOSE, -1))/Ref(CLOSE, -1);
prf:= If(gap>=up, OPEN-CLOSE, If(gap<=-dn, CLOSE-OPEN,0));
Cum(prf);
-- Stéphane Reverre

179
CHANDELIER EXIT

The exit system you use is at least as important as the entry system.

Below is the code for Chuck LeBeau's Chandelier Exit. The Chandelier Exit is a
volatility based exit (it uses average true range) that works quite well on trend
following systems. It lets "... profits run in the direction
of a trend while still offering some protection against any reversal in trend."

The theory is quite simple, but because of the awkwardness of defining the entry
price, its implementation in MetaStock takes some work. The theory is: exit a long
position at either the highest high since entry minus 3
ATRs, or at the highest close since entry minus 2.5 ATRs.

The exit is descibed more fully in the Trader's Toolkit section at Chuck LeBeau's site
-- http://traderclub.com/

Here is the MetaStock code:

{LONG EXIT}
LongEntry:= {this your entry system, eg. Cross(CLOSE, Mov(C,20,E))};
MoneyMgmtStop:= {this is your maximum loss, in points};

{DEFINE ENTRY PRICE, WITH EXIT BEING -ENTRY PRICE AND NO TRADE
BEING 0}
EntryPrice:= If(PREV <= 0,
{Trade entered today?}
If(LongEntry, CLOSE, 0),
{Trade entered before today. Stopped today?}
If(LOW <= PREV - MoneyMgmtStop, -PREV,
If(LOW <= HighestSince(1,PREV=0, HIGH) - 3 * ATR(10), -PREV,
If(LOW <= HighestSince(1,PREV=0, CLOSE) - 2.5 * ATR(10), -PREV,
PREV))));

{EXIT IF ENTRY PRICE < 0 (MEANING EXIT)}


EntryPrice < 0

{SHORT EXIT}
ShortEntry:= {this your entry system, eg. Cross(Mov(C,20,E), CLOSE)};
MoneyMgmtStop:= {this is your maximum loss, in points};

{DEFINE ENTRY PRICE, WITH EXIT BEING -ENTRY PRICE AND NO TRADE
BEING 0}
EntryPrice:= If(PREV <= 0,
{Trade entered today?}
If(ShortEntry, CLOSE, 0),
{Trade entered before today. Stopped today?}
If(HIGH >= PREV + MoneyMgmtStop, -PREV,

180
If(HIGH >= LowestSince(1,PREV=0, LOW) + 3 * ATR(10), -PREV,
If(HIGH >= LowestSince(1,PREV=0, CLOSE) + 2.5 * ATR(10), -PREV,
PREV))));

{EXIT IF ENTRY PRICE < 0 (MEANING EXIT)}


EntryPrice < 0

{from Glen Wallace}

PROJECTED RANGE
From "Lyn Maine"
This is
Tom DeMark's Projected Range:
TPH1:=(H+C+2*L)/2-L;
TPH2:=(2*H+L+C)/2-L;
TPH3:=(H+L+2*C)/2-L;
TPL1:=(H+C+2*L)/2-H;
TPL2:=(2*H+L+C)/2-H;
TPL3:=(H+L+2*C)/2-H;
PH:=If((C<O),TPH1,If((C>O),TPH2,If((C=O),TPH3,0)));
PL:=If((C<O),TPL1,If((C>O),TPL2,If((C=O),TPL3,0)));
PH;
PL;

This is my updated version of Tushar Chande's Vidya

Vidya:
K:=Stdev(P,5)/Mov(Stdev(P,5),20,S);
SC:=Input("SC",.1,.9,.1);
Vidya:=SC*K*P+(1-SC*K)*Ref(P,-1);
Vidya;
{the sc input is more responsive if you use a higher number}

This is Vidya with volatility bands:


K:=Stdev(C,5)/Mov(Stdev(C,5),20,S);
SC:=0.9;
Vidya:=SC*K*C+(1-SC*K)*Ref(C,-1);
UpperBand:=Vidya+2*.5*K;
LowerBand:=Vidya-2*.5*K;
UpperBand;
LowerBand;
Vidya;

This is Tushar Chande's target price:


A:=Mov(Abs(C-Ref(C,-1)),10,S);
TPH1:=C+A;

181
TPH2:=C+(2*A);

TPL1:=C-A;
TPL2:=C-(2*A);
TPH1;
TPH2;
TPL1;
TPL2;

This is ATR Ratio to Close:


ATRR:= ATR(5)/C;
MATRR:=Mov(ATRR,3,E);
ATRR;
MATRR;

This is a CMO Composite Average:


(((CMO(C,5))+(CMO(C,10))+(CMO(C,20)))/3)

This is CMO Volatility:


S1:= Stdev( CMO(C,5),5);
S2:= Stdev(CMO(C,10),10);
S3:= Stdev(CMO(C,20),20);
CMOV:=(S1*CMO(C,5))+(S2*CMO(C,10))+(S3*CMO(C,20))/(S1+S2+S3);
CMOV;

This is Rule of 7 down objective:


If((ROC(C,12,%)>-1.5),If((ROC(C,12,%)>-3),
If((ROC(C,12,%)>-4.5),((H-(H-L)*1.75)),((H-(H-L)*2.33))),((H-(H-L)*3.5))),(H-(H-
L)))

This is rule of 7 up objective:


If((ROC(C,12,%)>1.5),If((ROC(C,12,%)>3),
If((ROC(C,12,%)>4.5),(((H-L)*1.75)+L),(((H-L)*2.33)+L)),(((H-L)*3.5)+L)),((H-
L)+L))

This is rule of 7 Osc:


Fml("Rule of 7 UP Objective") -
Fml("Rule of 7 DOWN Objective")

This is %f Osc:
100*((C-Ref(TSF(C,5),-1))/C)

This is Chande's Trendscore:


If(C>=Ref(C,-11),1,-1)+If(C>=Ref(C,-12),1,-1)+If(C>=Ref(C,-13),1,-1)+
If(C>=Ref(C,-14),1,-1)+If(C>=Ref(C,-15),1,-1)+If(C>=Ref(C,-16),1,-1)+
If(C>=Ref(C,-17),1,-1)+If(C>=Ref(C,-18),1,-1)+If(C>=Ref(C,-19),1,-1)+
If(C>=Ref(C,-20),1,-1)

This is McGinley Dynamic:


Ref(Mov(C,12,E),-1)+((C-(Ref(Mov(C,12,E),-1))) / (C/(Ref(Mov(C,12,E),-1))*125))

182
This is Morris Double Momentum Osc:

Mov(((ROC(C,12.8,%))+(ROC(C,19.2,%))),10,W)

This is Volatility%:

Lookback := Input("Time Periods",1,1000,50);

HighVolatility := Input("High Volatility %",.01,100,3);

100 * Sum(100 * ATR(1)/CLOSE > HighVolatility, Lookback)/Lookback

This is Positive Volume Indicator:


Cum(If(V>Ref(V,-1),ROC(C,1,%),0))

This is negative volume indicator:


Cum(If(V<Ref(V,-1),ROC(C,1,%),0))

CANDLE CODE

From "Lyn Maine"


Here is the formula from this months TASC called Candle code
this is only using 1 formula not like the one in TASC which is broken up into several
smaller ones.

CandleCode
Bdy:=Abs(O-C);
Lshd:=If(C>=O,O-L,C-L);
Ushd:=If(C>=O,H-C,H-O);
ThBotB:=BBandBot(Bdy,55,E,0.5);
ThTopB:=BBandTop(Bdy,55,E,0.5);
ThBotL:=BBandBot(Lshd,55,E,0.5);
ThTopL:=BBandTop(Lshd,55,E,0.5);
ThBotU:=BBandBot(Ushd,55,E,0.5);
ThTopU:=BBandTop(Ushd,55,E,0.5);
CCode:=If(C=O,1,0)*If(Ushd>=Lshd,64,48)+If(C=O,0,1)*(If(C>O,1,0)*(If(Bdy<=T
hBotB,80,0)+If(Bdy>ThBotB AND Bdy<=ThTopB,96,0)+ If(Bdy>ThTopB,112,0))+
If(C<O,1,0)*(If(Bdy<=ThBotB,32,0)+ If(Bdy>ThBotB AND
Bdy<=ThTopB,16,0)))+(If(Lshd=0,3,0)+ If(Lshd<ThBotL AND Lshd>0,2,0)+
If(Lshd>ThBotL AND Lshd<=ThTopL AND Lshd>0,1,0))+(If(Ushd>0 AND
Ushd<=ThBotU,4,0)+ If(Ushd>ThbotU AND Ushd<=ThTopU,8,0)+
If(Ushd>ThTopU,12,0));
CCode;

CSI{Candle strength index}

183
Periods:=Input("Enter Periods",2,13,2);
Mov(Mov(Mov(Fml("Candlecode"),Periods,S),Periods,S),Periods,S)

Tushar Chande's Vidya using the P variable

Vidya{P}
Periods:=Input("length of MA",5,100,20);
K:=Stdev(P,5)/Mov(Stdev(P,5),20,S);
A:=(2/(Periods+1));
Vidya:=A*K*(P)+(1-A*K)*Ref(P,-1);
Vidya;

Tar(SZ)an Long
C-(((462*Mov(C,34,E))-(420*Mov(C,13,E))+(490*(Mov(Mov(C,13,E)-
Mov(C,34,E),89,E))))/42)

Tar(SZ)an Short
(C-(((325*Mov(C,26,E))-(297*Mov(C,12,E))+(351*Mov(Mov(C,13,E)-
Mov(C,26,E),9,E))))/28)*2

Tom Demark's Range expansion index

TDREI
TD1:= H-Ref(H,-2);
TD2:= L-Ref(L,-2);
TD3:= If((H>=Ref(L,-5) OR H>=Ref(L,-6)) AND (L<=Ref(H,-5) OR L<=Ref(H,-
6)),1,0);
TD4:= If((Ref(H,-2)>=Ref(C,-7) OR Ref(H,-2)>=Ref(C,-8)) AND (Ref(L,-
2)<=Ref(C,-7) OR Ref(L,-2)<=Ref(C,-8)),1,0);
TD6:= (TD1) + (TD2);
TD5:= If((TD3) + (TD4)>=1, (TD6), 0);
TD7:= Abs(TD1) + Abs(TD2);
TDREI:=((TD5) + Ref(TD5,-1) + Ref(TD5,-2) + Ref(TD5,-3) + Ref(TD5,-4))/ (TD7)
+ Ref(TD7,-1) + Ref(TD7,-2) + Ref(TD7,-3) + Ref(TD7,-4)*100;
TDREI;

From Henry Z Kaczmarczyk

TRADING THE TREND 2

Trading the Trend (TTT) -- by Andrew Abraham, TASC Magazine 9/1998, was about
one form of stoploss exit: subtract some manipulation of the true range from the
highest high (or add it to the lowest low) and exit when the close crosses that.

184
(Members of Chuck LeBeau's Traders Club will recognise the "Chandelier Exit".)

The Chandelier Exit:

The exit stop is placed at a multiple of average true range from the highest high or
highest close since the entry of the trade. As the highs get higher the stop moves up
but it never moves downward.

In MS 6.5 as a variable or custom indicator : DaysinTrade:= Barssince(previous


composite entry criteria = 1)

YO YO Exit

This exit is very similar to the Chandelier Exit except that the ATR stop is always
pegged to the most recent close instead of the highest high. Since the closes move
higher and lower, the stop also moves up and down (hence the Yo Yo name).

Trading the Trend

Pds:=21;
Mult:=3;
TruRan:=Mov(ATR(1),Pds,W)*Mult;
HiLimit:=HHV(H,Pds)-TruRan;
LoLimit:=LLV(L,Pds)+TruRan;
If(C>HiLimit,HiLimit,LoLimit)

1. After closing the Indicator Builder click on the Expert Advisor (the guy in the
bowler/derby hat).
2. Click on New, then the Name tab, type in Trading the Trend.
3. Click on the Highlights tab, select the first line so that it is highlighted, click Edit,
type in the name Uptrend, select Colour Blue, select Condition, type in
C>FmlVar("Trading the Trend","HiLimit"), and click OK,
4. Still on the Highlights tab, select the second line, click Edit, type in the name
Downtrend, select Color Red, select Condition, type in C<=FmlVar("Trading the
Trend","HiLimit"), click OK, and then click OK again.
5. If you have a chart open that you want to use this on, click Attach, otherwise click
Close. In the latter case, when you open a chart and plot the trendline, click on the
Expert Advisor, select Trading the Trend, and click on Attach.

I've given the Expert steps in detail for any who may not be familiar with its use. To
experiment with variations in the lookback periods and the multiplier you can do so in
either the Indicator Builder, or right-click the indicator on the chart, select Properties,
then the Formula tab, and make the changes (e.g. try a lookback period of 10, and a
multiplier of 2.5). As implemented above, the Expert should change accordingly. This
shows the trade-offs that have to be made
between near and distant stops. This is too rudimentary to be traded as a system - the
whipsaws would chop you to pieces - but the exits should help to limit drawdowns.

A very similar stoploss is given in Chande & Kroll "The New Technical Trader",

185
pp.167 - 169, "Volatility-Based Trailing Stops". My preference is to plot both the high
and the low exit lines in contrasting colours, dispensing with the switch between
them, and dispensing with the Expert. If anyone wants help with the code, just say so.

Assuming you entered everything exactly in both the Indicator Builder and the Expert
Advisor, one question comes to mind. Did you decide to adapt the formula to MS
v.6.5 and use an Input function for Pds and Mult? It seems like a logical thing to do,
and in fact I coded it that way at first. The problem is that the Expert Advisor always
reverts to the default value (the System Tester does the same thing).

Thus if you used something like:

Pds:=Input("Lookback Periods?",1,1000,20)

and then when you applied it you changed the periods to 15, the Expert Advisor will
still read 20. I hard-coded the Pds and Mult parameters for that reason.

From Harvey Pearce hhp@home.com

TRADING THE TREND 1

TTT--TREND TRAILING Indicator -- Andrew Abraham

Could have been called:


-STOP LOSS Indicator
-SUPPORT & RESISTANCE Indicator
-DYNAMIC SUPPORT & RESISTANCE Indicator
-BUY/SELL TRIGGER Indicator
-INVESTORS DREAM Indicator
-TRADING Indicator

fml("VOLAInd"): Mov(ATR(21),1,W)*3;

If(C>Ref(C,-21) AND C>fml("VOLAInd"),


HHV(H,21)-Ref(fml("VOLAInd"),-1), Ref(fml("VOLAInd"),-1)+LLV(L,21))

.or.

VOLAInd :=Mov(ATR(21),1,W)*3;
If(C>Ref(C,-21) AND C>VOLAInd, HHV(H,21)-Ref(VOLAInd,-1),
Ref(VOLAInd,-1)+LLV(L,21))

{CHANGE BAR COLORS: double click on the price plot in the chart, from the
Color/Style page click the UP drop-list and choose darkblue for upwards, and red for
downward price changes}

186
From Ian Burgoyne iburgy@one.net.au

BOLLINGER BAND WIDTH

John Bollinger describes BWI (Band Width Indicator) as the width of the bands
divided by the average of the price:

4*(std(C,20))/mov(C,20,S)

I don't know if adding the moving average changes the usefulness of the prospecting;
anyway, this is what Bollinger is suggesting.

I have written a MetaStock exploration to spot stocks whose BWI has reached
extreme low readings. This shows when the BWI is at lower than its highest level for
the last 250 days, divided by 3:

hhv(4*(std(C,20))/mov(C,20,S),250)/3

The stocks that pass this screening are usually in a non-trending mood, or rather in an
horizontal trend where the Bollinger Bands normally represent support and resistance
levels. Otherwise, there are cases where the stock is just pausing before resuming a
trend. In this second case the BWI doesn't remain under the trigger level for a long
time.

A further remark is that when the stock enters a low-BWI period, it is often retesting a
previous support or resistance level.

Although I think BWI extreme lows are an interesting way to find low risk / low
volatility stocks, they don't give any clue as of the direction of the following move.

from Alberto Torchio

BOLLINGER BAND HISTOGRAM KARNISH

Recently, the "group" was able to supply me with the formula for making a Histogram
out of the "bands". I find this the most useful application of Bollinger's formula. The
following is the picture I draw:

((C+2*Std(C,20) - Mov(C,20,S)) / (4*Std(C,20)))*4 - 2

Under "properties", I then drop in +2 and -2 (because I'm not bright enough to
program them in permanently). I think this is a much better view of the bands. As the
price moves up and down as a % of the band width, all the classic applications of

187
other "oscillator type" indicators work well (divergence, support/resistance, and
overbought/oversold conditions when the price exceeds the Standard Dev. of +/-2).

This is just one of ten indicators that I use ... but, for traders trying to understand
Bollinger's "envelopes", I think this reconfiguration gives a simpler, cleaner view
which allows the technician to analyse the underlying issue without the "squiggles".

from Steve Karnish

SYSTEM TEST EXAMPLES


from Glen Wallace

> "Buy at the open plus half the average true range of the last ten days?"

HIGH >= OPEN + 0.5*Ref(ATR(10), -1)

> "If these two moving averages cross today, buy on tomorrow's open."

MA1:= Mov(CLOSE, 10, SIMPLE);


MA2:= Mov(CLOSE, 20, SIMPLE);
Ref(Cross(MA1, MA2), -1)
(with System Testing Options | Testing tab | Entry Price set to "Open" and delay set to
zero)

> "Exit five bars after entry."

EntryCondition:= {your trade entry conditions};


BarsSince(EntryCondition >= 5)

BOLLINGER OPTIMISED SYNERGY SYSTEM


BOSS -- Synergy with Bollinger by John Lowe (March 1998 issue of TAM, a Dutch
TA mag)

In this article John Bollinger gets mentioned as insisting on using a Price/Close


indicator in conjunction with a combined Price/Volume indicator. For example, Price
as a moving or exponential average, the Typical Price(High+Low+Close/3) or one of
the other on this theme of existing varieties. Bollinger strives for synergy, which has
to be confirmed by two of three indicators based on:

Closing-price, price and volume, the Bollinger Optimised Synergy System (BOSS):

1st criteria -- Bollinger Bands are best used in conjunction with Wilders' RSI(9 or 14),
an indicator based on closing price.

2nd criteria -- Price and volume, combined in the Chaikin Oscillator, are the other part
of the BOSS.

188
According to most analysts, the Chaikin Oscillator, a diverse
accumulation/distribution line, is a very good alternative to the OBV indicator.
Chaikin Oscillators' basics are that a healthy trend will be confirmed by a healthy,
positive volume-development in the trend-direction. The Chaikin Oscillator can be
substituted for with the Money Flow Index (MFI).

Chaikin Oscillator formula:

Mov(cum(((C-L)-(H-C)/(H-L))*V),3,E)-Mov(cum(((C-L)-(H-C)/(H-L))*V),10,E)

from Ton Maas

BIANCHI APPROACH

enter long

When(Mov( Mid(C, opt1) ,opt1,E),>,Mov(Mid(C, opt1),opt2,E))AND


When(Ref(Mov(Mid(C,opt1),opt1,E),-1), <= ,(Ref(Mov((Mid(C,opt1)),opt2,E),-
1)))AND When(Mov(Abs((Mo(opt3))),opt4,E),>,Ref(Mov(Abs((Mo(opt3))),opt4,E),-
1))

enter short

When(Mov( Mid(C, opt1) ,opt1,E),<,Mov(Mid(C, opt1),opt2,E))AND


When(Ref(Mov(Mid(C,opt1),opt1,E),-1), >= ,(Ref(Mov((Mid(C,opt1)),opt2,E),-
1)))AND When(Mov(Abs((Mo(opt3))),opt4,E),>,Ref(Mov(Abs((Mo(opt3))),opt4,E),-
1))

OPT 1: 5 to 20 step 1
OPT 2:10 to 16 step1
OPT3:5 to 15 step 1
OPT4:20 to 29 step 1
but you are free to change any value of OPT!

STARC BAND

STARC BAND Formula = (Mov(Typical(),5,S))

Starc Upper Band:


Fml( "STARC BAND" )+ (ATR(15)*1.33)

Starc Lower Band:


Fml( "STARC BAND" )-(ATR(15)*1.33)

189
Any five day moving average will work.

Contributed by J. Seed

MONEY FLOW INDEX


The MFI (Money Flow Index) can be used in place of the OBV (On Balance Volume)
and Chaikin Oscillator to confirm Bollinger Bands.

From Stocks & Commodities magazine, v. 12:8 (321-324): SIDEBAR: The Money
Flow Index

"The money flow index (MFI) is a volume-weighted form of the relative strength
index (RSI). Instead of using up closes versus down closes, the MFI compares today's
average price to yesterday's average price and then weighs the average price by
volume to calculate money flow (MF). The ratio of the summed positive and negative
money flows are then normalized to be on a scale of zero to 100."

Here are the MetaStock formulas for the Money Flow Index:

Positive Money Flow:


sum ( if ( typ( ) ,> ,ref ( typ ( ) ,-1 ) ,V * typ ( ) ,0 ) , PERIODS)

Negative Money Flow:


sum ( if ( typ( ) ,< ,ref ( typ( ) ,-1) ,V * typ ( ) * -1 ,0 ) , PERIODS)

Money Flow Ratio:


fml ( "Positive Money Flow" ) / fml ( "Negative Money Flow" )

Money Flow Index:


100 - ( 100 / ( 1 + fml ( "Money Flow Ratio" ) ) )

NB:The time periods are controlled by PERIODS in the Positive & Negative Money
Flow formulas.

BOLLINGER BAND CONFIRMATION

From: Ton Maas

According to most analysts, the Chaikin Oscillator, a diverse


accumulation/distribution line, is a very good alternative to the OBV (On Balance
Volume) indicator. Chaikin Oscillator basics are that a healthy trend will be
confirmed by a healthy, positive volume development in the trend direction. The MFI
(Money Flow Index) can also substitute for the Chaikin Oscillator.

Chaikin Oscillator formula:

190
Mov(cum(((C-L)-(H-C)/(H-L))*V),3,E)-Mov(cum(((C-L)-(H-C)/(H-L))*V),10,E)

BOLLINGER BAND WIDTH

From: Philip Schmitz

MetaStock v6 does not appear to provide an indicator which shows the width of
Bollinger Bands, so I have concocted a simple one to suit my own needs:

"Band Width" = BBandTop(C, 70, E , 2) - BBandBot(C, 70, E , 2)

As a next step, I would like to devise an indicator which tells me how the current
value of
"Band Width" relates to the overall range of Band Widths for a specified period, or,
since my interest is commodities, the life of the contract -- in other words all data
loaded. Where, on a percentage basis, does it fall?

KARNISH BOLLINGER BAND HISTOGRAM TRADING SYSTEM

{EnterLong and Close Short}


BBHistogram:= (CLOSE + 2*Std(CLOSE,20) -
Mov(CLOSE,20,SIMPLE)) / (4*(Std(CLOSE,20)))
* 100;
Cross(0,BBHistogram)

{Enter Short and Close Long}


BBHistogram:= (CLOSE + 2*Std(CLOSE,20) -
Mov(CLOSE,20,SIMPLE)) / (4*(Std(CLOSE,20)))
* 100;
Cross(BBHistogram,100)

BB HISTOGRAM

((C+2*Std(C,20)-Mov(C,20,S))/(4*(Std(C,20)))*100)

Sell the opening days after the BB Histogram penetrates 100 and buy when it
penetrates zero. Add to positions when the BB Histo leaves "above 100" or "below
zero" and then "repenetrates" the trigger levels.

I believe this approach has recorded 11 straight S&P winners, with 700+ points. "But

191
Steve, this system must not be working any more because it is losing the last trade
you put on". Right!

My only disclaimer is that I guarantee that I will sell software, charting services and
anything else that I can think of to make a "buck" in 2000. In the meantime, suck all
the free stuff from me you can copy. And most of all, please note, the biggest
antagonists on the list provide absolutely "zero" when it comes to helping you trade.
Seek the answers from "within" (with some shortcutting help from people that are
willing to share).

Steve Karnish

CMA,

"1) Sell the opening (long or short) X-number of days(?) after the indicator above
moves from below 100 to
above 100. (Is this on a close-to-close basis?)"

Specifically, sell the opening the day after the BB Histo closes above 100.

"2) Buy or cover when the indicator goes from above 100 to below 100 or from above
0 to below 0 X-number
of days after that occurs."

Buy, when the BB Histo dips below zero (the following morning).

"a) how many days after the signal does one act;"

The following morning.

" b) Is this close-to-close or intra-day?"

close to close

"c) Is this to initiate or to go short or add to a position?"

Add to positions if the indicator "repenetrates" these levels ... otherwise, reverse when
it triggers.

Steve Karnish

BOLLINGER BANDS 2
I am sure Steve has done something better, but here is a simple (MetaStock) formula
allowing you to draw Bollinger Bands as an oscillator:

100*(C-Mov(C,20,S)+2*Stdev(C,20))/(4*Stdev(C,20))

192
Alberto Torchio
Torino, Italy

BULL FEAR/BEAR FEAR with DX system

enter long:
n :=opt2{Time periods};
BullFear := (HHV(HIGH,n) - LLV(HIGH,n))/2 + LLV(HIGH,n);
Cross(CLOSE,bullfear) AND
DX(10) > opt1

close long:
n :=opt2{Time periods};
BearFear := (HHV(LOW,n) - LLV(LOW,n))/2 + LLV(LOW,n);
CLOSE < bearfear

{Mike Arnoldi}

BULL FEAR/BEAR FEAR

The system is a trend follower that appears to get you in at the early in a trend. If the
trend breaks down for any reason, the system seems to take you out with relatively
little pain, and there is a relatively high
percentage of losing trades (usually around 50%). Therefore, the system seems to
perform best on issues that are prone to make prolonged moves. The trick is to find
those issues. I do admit that the system is not perfect;
for instance, it is my belief that the exit could be improved on winners to preserve
more profit. However, I've been unable to develop an alternative exit that improves
the system return.

I've been trading this system myself for about a year and have had good results. Even
in the April-September period when everything seemed to stall and move sideways, I
was, at least able to hold my own and maintain my capital until the October break-
always started to occur. For awhile, until I got bored with it, I phantom traded this
system in the Yahoo Investment Challenge. I typically made about 20% a month
using the system in that venue.

Buy
n :=opt2{Time periods};
BullFear := (HHV(HIGH,n) - LLV(HIGH,n))/2 + LLV(HIGH,n);
Cross(CLOSE,bullfear) AND
DX(10) > opt1

193
Sell
n :=opt2{Time periods};
BearFear := (HHV(LOW,n) - LLV(LOW,n))/2 + LLV(LOW,n);
CLOSE < bearfear

Optimize the time periods from 10 to 50 in increments of 1 while testing the DX from
5 to 30 in increments of 5 (you can do it in increments of 1 but it takes longer). Once
the Optimal time period is determined in this manner,
then retest with the determined optimal time period and the DX in increments of 1.
Note that this system is intended to be a stop and reverse system and you can use it to
go short as well if you'd like to.

Jeff

5 DAY HIGH

{"Today must make a five-day high and


today the close must be below the open."}

{Place the following in the MetaStock Explorer filter section.}

HIGH > Ref(HHV(HIGH,4),-1) AND CLOSE < OPEN

{or you can write it this way too ...}

HIGH > Ref(HIGH,-4)


AND HIGH > Ref(HIGH,-3)
AND HIGH > Ref(HIGH,-2)
AND HIGH > Ref(HIGH,-1)
AND CLOSE < OPEN

{from bdog}

STOCH RSI

Although I keep the best of the bunch as a "super secret" for friends, relatives, and
clients ... here is a smattering of formulae that might be useful. StoRSI's perform very
differently when you plug in various numbers.
Experiment and determine which are most suitable for your style and markets.
Substitute numbers, apply moving averages, get creative. These are just a few:

((RSI(21)-LLV(RSI(21),8))/((HHV(RSI(21),13))-LLV(RSI(21),13)))

((RSI(21)-LLV(RSI(21),21))/((HHV(RSI(21),21))-LLV(RSI(21),21)))

194
((RSI(14)-LLV(RSI(14),14))/((HHV(RSI(14),14))-LLV(RSI(14),14)))

Mov((RSI(21)-LLV(RSI(21),13))/(HHV(RSI(21),8)-
(LLV(RSI(21)+.00001,13))),8,E)
*100

Mov((RSI(5)-LLV(RSI(5),5))/(HHV(RSI(5),5)- (LLV(RSI(5),5))),3,E)*100

Mov((RSI(13)-LLV(RSI(13),13))/(HHV(RSI(13),13)- (LLV(RSI(13),13))),3,E)*100

from Steve Karnish


Cedar Creek Trading

ADX RAW

{MetaStock code written by Equis and published in the Oct99 TASC}

Periods:= Input("Enter time periods",1,100,14);

PlusDM:= If(HIGH>Ref(HIGH,-1) AND


LOW>=Ref(LOW,-1), HIGH-Ref(HIGH,-1),
If(HIGH>Ref(HIGH,-1) AND LOW<Ref(LOW,-1)
AND HIGH-Ref(HIGH,-1)>Ref(LOW,-1)-LOW,
HIGH-Ref(HIGH,-1), 0));
DIPlus:= 100 * Wilders(PlusDM,Periods) /
ATR(Periods);

MinusDM:= If(LOW<Ref(LOW,-1) AND


HIGH<=Ref(HIGH,-1), Ref(LOW,-1)-LOW,
If(HIGH>Ref(HIGH,-1) AND LOW<Ref(LOW,-1)
AND HIGH-Ref(HIGH,-1)<Ref(LOW,-1)-LOW,
Ref(LOW,-1)-LOW, 0));
DIMinus:= 100 * Wilders(MinusDM,Periods) /
ATR(Periods);

DIDif:= Abs(DIPlus - DIMinus);


DISum:= DIPlus + DIMinus;
ADXRaw:= 100 * Wilders(DIDif/DISum, Periods);

ADX WITH STOCHASTIC SIGNALS

Metastock users can reproduce the trend bars and entry signals shown on the CWO
chart using the Expert Advisor. Create a new expert and under Symbols add a new
entry with the following condition :

ADX(14) > 20 AND ( Mov(C,15,S) > Mov(C,30,S)) AND ( Mov(C,5,S) >


Mov(C,30,S)) AND Stoch(5,3) < 30 AND Ref(Stoch(5,3) ,-1) >=30

195
Under Trends add the Bullish formula :

ADX(14) > 20 AND ( Mov(C,15,S) > Mov(C,30,S)) AND ( Mov(C,5,S) >


Mov(C,30,S))

and the Bearish formula :

ADX(14) > 20 AND ( Mov(C,15,S) < Mov(C,30,S)) AND ( Mov(C,5,S) <


Mov(C,30,S))

C Miller

CHANDELIER EXIT, VERSION 2 METASTOCK CODE

Below is the MetaStock code I posted for the Chandelier exit back in October, 1999.
The trick is to define the entry date/price as the point at which your system triggered
the entry, not by using the date functions. A side benefit is that you can also use it to
implement a fixed dollar, or money management, stop.

The more time I spend with the Chandelier exit, the more I admire its strength as an
exit and its simplicity. Because exits tend to be the weakest part of a system, I would
urge everyone to spend some time with it.

And Chuck LeBeau gets credit for the MetaStock code, not me. I just took his
framework and applied it to his exit.

{LONG EXIT}
LongEntry:= {this your entry system, eg. Cross(CLOSE, Mov(C,20,E))};
MoneyMgmtStop:= {this is your maximum loss, in points};

{DEFINE ENTRY PRICE, WITH EXIT BEING -- ENTRY PRICE AND NO


TRADE BEING 0}
EntryPrice:= If(PREV <= 0,
{Trade entered today?}
If(LongEntry, CLOSE, 0),
{Trade entered before today. Stopped today?}
If(LOW <= PREV - MoneyMgmtStop, -PREV,
If(LOW <= HighestSince(1,PREV=0, HIGH) - 3 * ATR(10), -PREV,
If(LOW <= HighestSince(1,PREV=0, CLOSE) - 2.5 * ATR(10), -PREV,
PREV))));

{EXIT IF ENTRY PRICE < 0 (MEANING EXIT)}


EntryPrice < 0

196
{SHORT EXIT}
ShortEntry:= {this your entry system, eg. Cross(Mov(C,20,E), CLOSE)};
MoneyMgmtStop:= {this is your maximum loss, in points};

{DEFINE ENTRY PRICE, WITH EXIT BEING -ENTRY PRICE AND NO TRADE
BEING 0}
EntryPrice:= If(PREV <= 0,
{Trade entered today?}
If(ShortEntry, CLOSE, 0),
{Trade entered before today. Stopped today?}
If(HIGH >= PREV + MoneyMgmtStop, -PREV,
If(HIGH >= LowestSince(1,PREV=0, LOW) + 3 * ATR(10), -PREV,
If(HIGH >= LowestSince(1,PREV=0, CLOSE) + 2.5 * ATR(10), -PREV,
PREV))));

{EXIT IF ENTRY PRICE < 0 (MEANING EXIT)}


EntryPrice < 0

from Glen Wallace

MOVING AVERAGE CROSSOVERS

What follows is a simple example using a moving average crossover system for
MetaStock, employing 10 and 30 day exponential averages. These are just examples
and profitability is dubious.

Custom indicator which gives 1 for longs and -1 for shorts--

Indicator Name: Position


MASwitch:=If(Mov(C,10,E)>Mov(C,30,E),1,If(Mov(C,10,E)<Mov(C,30,E),-1,0));
If(BarsSince(MASwitch=1) <BarsSince(MASwitch=-1),1,-1)

Custom indicator for cumulative open Equity curve without trading costs--

Indicator name: Equity


Cum(If(Ref(Fml("Position"),-1)=1,C-Ref(C,-1),Ref(C,-1)-C))

You can make several such equity lines and then just add them by using a yet another
custom indicator, e.g.,

Indicator name: TotalEquity


Fml("Equity1")+Fml("Equity2")

from Yngvi

197
hardy@consulting.is

SETTING UP THE ADX TEMPLATE

This constructs the template mentioned in the ADX article of the October 1999 issue
of TASC by Paul Babbitt.

1. Chart your stock/index/whatever, using a "Clean" template, then do the same again,
so that the two overlapping charts are displayed.

2. On the menu bar, click Windows, then Columns. The two charts will then be
displayed side-by-side.

3. Change the left-hand chart from Daily to Weekly. Right click on the date scale and
select X-Axis. Set the displayed range of dates to what you want, e.g., 1996 to 1999.
Make sure the loaded dates range starts earlier. Click the Margin tab and set the
margin to 1.

4. From the Indicator drop-down list select Moving Average and drag it to the left-
hand chart. A 40 period on the weekly chart corresponds to a 200 day MA.

5. For the right-hand chart, leave it at a daily interval but set the X-Axis as in
paragraph 3 above to, say, a 3-month display.

6. Drag the Bollinger Band indicator to the right-hand chart.

7. Drag the Directional Movement ADX indicator to the top of the right-hand chart
until the cursor changes to a box, then release. Set the horizontal lines as desired.

8. Similarly drag the RSI indicator to the bottom of the right-hand chart.

from HHP

WRITING METASTOCK EXPLORATIONS


MetaStock is a marvellous program for traders, but can appear complicated and
intimidating at first. In reality, it's easy and fun, if you take it slowly, step by step.
Let's consider a common trader's question: "How can MetaStock help me find all
the stocks where the 3 day moving average has just crossed above the 10 day
moving average?"
MetaStock's Explorer tool allows you to search all the stocks in the ASX, and within a
minute or two (depending on your computer's speed!) generate a list of all stocks
meeting this particular criteria.
Here's a step by step guide for beginners:
1. Open up your Explorer tool in MetaStock by clicking on the little "binoculars"
symbol in the upper right field of your screen, or find it under Tools in the drop-down
menu.
2. You will be presented with the Explorer screen showing a list of ready-made Equis
Explorations plus various options to view or edit them. More about these later. Look
instead at the list of options to the right.

198
3. Choose the "New" button and click. You've just starting writing your own
MetaStock Exploration! MetaStock gives it the name "<New Exploration>" but let's
rename it "Moving Average Crossover" for the sake of this exercise.
4. Note that the Explorer screen has an upper section labelled "Notes" and then, just
below, seven columns, with tabs, labelled "A" to "F," plus "Filter." For now we're just
going to work with the "Filter" column. Click on its tab and you're ready to write a
MetaStock formula in this column.
5. Enter the following without the quotation marks: "Cross( Mov(c,3,s) , Mov(c,10,s)
)" but don't worry about the *spaces* between letters and punctuations marks, nor
about capitalisation.
6. Here's a quick explanation to ponder, before we go further. What you've just
entered under MetaStock Explorer's Filter is a much more simple formula than you
realise! It means only "Crossover A over B" or "Crossover 3 over 10" in ordinary
English. MetaStock writes this as "Cross( A , B )" where A and B are other
MetaStock formulas, any formulas you like. In this case, we're putting two different
moving averages in the place of A and B. MetaStock writes the English language
phrase "Moving Average of the past 3 days" as "mov(c,3,s)" and the second moving
average is exactly the same, with the numeral 10 substituted for the 3.
7. Your first MetaStock Exploration is now finished. Click "OK" in the lower left of
the Explorer field to save it and you will quickly find your own "Moving Average
Crossover" Exploration added to those already on MetaStock's ready-made list.
8. Next, click on the "Explore" button and MetaStock will prompt you for the path to
the place on your computer where you have all your ASX (or other) data. Choose
which securities you want to scan. I suggest that you choose them all to start with, and
save this as a "List" named "All" so that when you make more Explorations you won't
have to go through this step again. You can just choose the "All" list whenever you
want to scan stocks. (Take note at this point that MetaStock has excellent assistance
for you under its "Help" tab as well as one of the best software manuals ever written.)
9. MetaStock will quickly verify that your stocks are where you say they are, and
prompt you for an "OK". Once you do this, you can watch a nifty screen where
MetaStock outlines its search for all the stocks that match your search (Filter) criteria.
How long this process takes depends once again on the speed of your computer!
10. When Explorer is finished you should choose the "Report" option to find a filtered
list of all the stocks which *today* have their 3 day moving average rising above their
10 day moving average. MetaStock allows you to open each or all of these stocks in
full screen pages for further analysis.
Patrick McDonald

BACKDATING METASTOCK EXPLORATIONS

Perhaps the above is enough for many traders, but a few further MetaStock nuances
can add to the value of the information you've uncovered. For example, wouldn't
you like to know which stocks have met the chosen crossover criteria in the past,
say, five days? And wouldn't it be handy to be able to sort your newly discovered
stocks in order of price or volume? If so, read on for a few more simple tips.
1. Go back to the main Explorer tool section, highlight your "Moving Average
Crossover" Exploration, and hit the "edit" key this time. You can now make
alterations to your Exploration. Ignore the upper "Notes" section and click on Column
A first. You will see a large white field for entry of formulas and a small field in the

199
lower left, entitled "Col Name." Simply put a "c" in the large formula section and
"Close" in the column name section. Repeat these actions for Column B, with "v" and
"Volume" respectively. Now when your Exploration presents you with your data, you
can easily sort by price (c) or volume (v).
2. Finally, click on the "Filter" tab again to slightly modify your Exploration formula.
The way you have it set up initially tells MetaStock to find all stocks which meet the
criteria today. You now want it to find all stocks that have met these criteria over the
past five days. The answer is the MetaStock Alert function, which is written "Alert( A
, Number ) where "A" is any formula you care to choose, and "Number" is the number
of days. So now you put your original formula in the place of A. The result is: "Alert(
Cross( Mov(C,3,E) , Mov(C,10,E) ) ,5)" without the quotation marks. Save your new
Exploration with the "OK" button and you're ready to find all stocks whose 3 day
moving average passed above the 10 day moving average in the past five trading
days!
The above information should allow you to write further Explorations by simply
changing the numbers. If you prefer to use Exponential Moving Averages instead of
Simple Moving Averages, change "s" to "e" in the formulas. You can also open up the
ready made Equis Explorations, investigate how they're written, and change them
with the "Edit" command (then saving with a new name). A further step is to
investigate the hundreds of formulas available here on this web site and modify them
in the same way. This is the quick and easy way to learn how to program with
MetaStock. Follow the examples given by all the kind and clever MetaStock users
who have gone before you, and tweak, tweak, tweak.
Patrick McDonald

VIDYA 21, 5

This is the MetaStock code for VIDYA 21,5 which applies to the article "Breaking
Out Of Price Channels" by Gerald Marisch in the TASC January 1998 edition.

Length:=Input("Length",1,200,21);
Smooth:=Input("Smoothing",1,200,5);
AbsCMO:=(Abs(CMO(C,Length)))/100;
SC:=2/(Smooth+1);
VIDYA:=If(Cum(1)<=(Length+1),C,(SC*AbsCMO*CLOSE)+(1-
(SC*AbsCMO))*PREV);
VIDYA

from Ian Burgogyne

XXXXXXXXXX

VIDYA WITH P VARIABLE VERSION 2

My version of Tushar Chande's Vidya, using the P variable

Vidya{P}
Periods:=Input("length of MA",5,100,20);

200
K:=Stdev(P,5)/Mov(Stdev(P,5),20,S);
A:=(2/(Periods+1));
Vidya:=A*K*(P)+(1-A*K)*Ref(P,-1);
Vidya;

Tar(SZ)an Long
C-(((462*Mov(C,34,E))-(420*Mov(C,13,E))+(490*(Mov(Mov(C,13,E)-
Mov(C,34,E),89,E))))/42)

Tar(SZ)an Short
(C-(((325*Mov(C,26,E))-(297*Mov(C,12,E))+(351*Mov(Mov(C,13,E)-
Mov(C,26,E),9,E))))/28)*2

from Barry Marx

XXXXXXXXXX

VIDYA EXPLANATION

Vidya is a subject that comes up with some regularity. It's actually available in
MetaStock as the Variable Moving Average (Mov(C,n,V) but Equis, for their own
inscrutable reasons, choose not to identify it by name. If you refer to the MetaStock
manual, be aware that there is a typo in the formula (0.078 should read 0.78). Two or
three years ago I coded the version given in TAS&C and it overlaid the MetaStock
version precisely, except that at the time the MetaStock version was not correctly
initialised -- this has since been corrected. Equis acknowledged the typo at the time,
but have done nothing about it.

As far as the 'circular reference' is concerned, you are right that eventually you run out
of data. However adding a portion of yesterday's value to a portion of today's value is
common to several indicators, such as the Exponential Moving Average. If no
provision is made, then usually the indicator will start with a value of zero, rise
rapidly at first, then take some time to stabilise.

One answer is to initialise it. For a Vidya of the close, period N, you can initialise
with something like "If(Cum(1) < N, C,{else} ...)" with the Vidya formula as the
'else'. Then at day N the indicator uses the (N-1) close for yesterday's data and takes
much less time to stabilise.

from HHP

XXXXXXXXX

VIDYA USING A P VARIABLE VERSION 1


Here is a version of Vidya using a P variable that matches MetaStock's built-in
Variable Moving Average. You can overlay them in different colours on the same
chart to satisfy yourself that they are indeed the same (but remember to use the same

201
number of periods). There is a small difference at the start due to different
initialisation, after which they are identical. The coding is spelled out for the benefit
of anyone studying the book. It can be adapted by adding a variable input for the
CMO length (9), or made universal by replacing each C with a P, or the Abs(CMOsc)
can be replaced with a different volatility index that ranges between 0 and 1.

{Vidya (Chande)}

Pds:= Input("Number of Periods?",1,1000,20);


Alpha:= 2/(Pds+1);

{Chande Momentum Oscillator}


{UD = Up day}
{DD = Down day}
UD:= Sum((C-Ref(C,-1))*(C>Ref(C,-1)),9);
DD:= Sum((Ref(C,-1)-C)*(C<Ref(C,-1)),9);
CMOsc:= (UD-DD)/(UD+DD);

k:= Abs(CMOsc);

Vidya:= (Cum(1) < Pds) * C + (Cum(1)>=Pds) * ((Alpha * k * C) + (1-Alpha


* k) * PREV);
Vidya

{from HHP}

XXXXXXXXXXXXX
CHANNEL EXIT WITH STOP LOSS
As people have mentioned before, it is difficult to design exits in MetaStock because
of the awkwardness of defining your trade entry price. One exit system that requires
your trade entry price is the channel exit.

For those not familiar with it, the channel exit is quite a straight forward trailing stop.
Once you're in a trade (let's say, long), you maintain your stops at the lowest low of
the past number of days (optimized, in the code below) until you are taken out of the
market. This method attempts to let profits run in the direction of the trend, but takes
you out when price makes a significant reversal and you risk giving back profits on a
retracement or the end of the trend.

Below is the code for a channel exit. It also includes a money management stop to
limit losses to an acceptable level until the channel exit exceeds it. Work on variations
of this basic theme, such as moving the stop up faster where the market makes rapid
gains and your lowest low in, say, 10 or 20 days is just too far away to adequately
protect profits.

-- Glen Wallace

{LONG EXIT}
LongEntry:= {this your entry system, eg. Cross(CLOSE, Mov(C,20,E))};
MoneyMgmtStop:= {this is your maximum loss, in points};

202
{DEFINE ENTRY PRICE, WITH EXIT BEING -ENTRY PRICE AND NO TRADE
BEING 0}
EntryPrice:= If(PREV <= 0,
{Trade entered today?}
If(LongEntry, CLOSE, 0),
{Trade entered before today. Stopped today?}
If(LOW <= Max(PREV - MoneyMgmtStop, Ref(LLV(LOW,opt1),-1)), -PREV,
PREV));

{EXIT IF ENTRY PRICE < 0 (MEANING EXIT)}

EntryPrice < 0

{SHORT EXIT}
ShortEntry:= {this your entry system, eg. Cross(Mov(C,20,E), CLOSE)};
MoneyMgmtStop:= {this is your maximum loss, in points};

{DEFINE ENTRY PRICE, WITH EXIT BEING -ENTRY PRICE AND NO TRADE
BEING 0}
EntryPrice:= If(PREV <= 0,
{Trade entered today?}
If(ShortEntry, CLOSE, 0),
{Trade entered before today.Stopped today?}
If(HIGH >= Min(PREV + MoneyMgmtStop, Ref(HHV(HIGH,opt1),-1)), -PREV,
PREV));

{EXIT IF ENTRY PRICE < 0 (MEANING EXIT)}


EntryPrice < 0

XXXXXX
HIGHER VOLUME EXPLORATION
Required: today's volume to be greater than the highest high over the past 21 days.

MetaStock Explorer filter:

V>Ref(HHV(V,21),-1)

from HHP

XXXXXXXXXX
ENTER 20 DAYS AFTER MOV SIGNAL
I am trying to use the MetaStock Explorer to find all stocks with the following:

1. c - mov(c,60,s)<0
2. Above condition should be in place for 20 days/

I use c - Mov(c,60,s)<0 but how do I write the Exploration?

203
from wsb

========================================================

Use (C - Mov(C,60,S))<0 AND Ref((C - Mov(C,60,S))<0),-1) AND ... Ref((C -


Mov(C,60,S))<0),-19)

where ... stands for all Ref( x,-i) with i between 2 and 18.

from Yngvi

========================================================

Under the MetaStock Explorer filter, use something like:

C>MOV(C,60,S) AND REF((C>MOV(C,60,S)),-1) AND


REF((C>MOV(C,60,S)),-2) AND REF((C>MOV(C,60,S)),-3) AND
REF((C>MOV(C,60,S)),-4) AND REF((C>MOV(C,60,S)),-5) AND
REF((C>MOV(C,60,S)),-6) AND REF((C>MOV(C,60,S)),-7) AND
REF((C>MOV(C,60,S)),-8) AND REF((C>MOV(C,60,S)),-9) AND
REF((C>MOV(C,60,S)),-10) AND REF((C>MOV(C,60,S)),-11) AND
REF((C>MOV(C,60,S)),-12) AND REF((C>MOV(C,60,S)),-13) AND
REF((C>MOV(C,60,S)),-14) AND REF((C>MOV(C,60,S)),-15) AND
REF((C>MOV(C,60,S)),-16) AND REF((C>MOV(C,60,S)),-17) AND
REF((C>MOV(C,60,S)),-18) AND REF((C>MOV(C,60,S)),-19)

That should work ... theoretically. The only thing I'm concerned about is the REF
format. However, I think it's correct. The Close is always above (or greater than '>')
the MOV. The parentheses always match. Because a 60 day MOV is rather slow, you
probably could shorten the formula by leaving out all of the even numbered
REFerences:

C>MOV(C,60,S) AND REF((C>MOV(C,60,S)),-1) AND


REF((C>MOV(C,60,S)),-3) AND REF((C>MOV(C,60,S)),-5) AND
REF((C>MOV(C,60,S)),-7) AND REF((C>MOV(C,60,S)),-9) AND
REF((C>MOV(C,60,S)),-11) AND REF((C>MOV(C,60,S)),-13) AND
REF((C>MOV(C,60,S)),-15) AND REF((C>MOV(C,60,S)),-17) AND
REF((C>MOV(C,60,S)),-19)

from Daniel Martinez

XXXXXXXXXX

VOLUME BASED EXPLORATION


1. Stocks with volume > 10x the previous day's volume

2. Stocks where the above situation hasn't occurred during the previous 60 days.

204
ColA = if(V > 10*ref(V,-1),1,0)

ColB = ref(barssince(V>10*ref(V,-1)),-1)

Filter: ColA=1 and ColB>60

from warthog

LSS OSCILLATOR AND PIVOT POINT


Here are a few formula's that I picked up from a
mailing from George Angell

LSS 5 day Osc


X:=HHV(H,5)-Ref(O,-5);
Y:=C-LLV(L,5);
LSS:=100*(X+Y)/(HHV(H,5)-LLV(L,5))*2;
LSS;

LLS 5 DAY Osc Diff from 3 day osc


X:=HHV(H,5)-Ref(O,-5);
Y:=C-LLV(L,5);
LSS:=100*(X+Y)/(HHV(H,5)-LLV(L,5))*2;
Diff:=LSS-Ref(LSS,-3);
Diff;

LLS Strength Index(1 day)


100*(Ref(C,-1)-Ref(L,-1))/(Ref(H,-1)-Ref(L,-1))

LLS Pivot Breakout Buy Number


X:=(H+L+C)/3;
BBN:=2*X-L;
BSN:=2*X-H;
BBN;
BSN;

From Henry Kaczmarczyk

Volatility % Indicator
Create the Volatility% Indicator from William Brower’s S&C article in MetaStock for
Windows.

Volatility%

Lookback := Input("Time Periods",1,1000,50);

HighVolatility := Input("High Volatility %",.01,100,3);

205
100 * Sum(100 * ATR(1)/CLOSE > HighVolatility, Lookback)/Lookback
From Henry Kaczmarczyk

Instantaneous Trendline and Sinewave Indicator as described by John Ehlers

Here are a few formula's that I picked up from a


mailing from George Angell

LSS 5 day Osc


X:=HHV(H,5)-Ref(O,-5);
Y:=C-LLV(L,5);
LSS:=100*(X+Y)/(HHV(H,5)-LLV(L,5))*2;
LSS;

LLS 5 DAY Osc Diff from 3 day osc


X:=HHV(H,5)-Ref(O,-5);
Y:=C-LLV(L,5);
LSS:=100*(X+Y)/(HHV(H,5)-LLV(L,5))*2;
Diff:=LSS-Ref(LSS,-3);
Diff;

LLS Strength Index(1 day)


100*(Ref(C,-1)-Ref(L,-1))/(Ref(H,-1)-Ref(L,-1))

LLS Pivot Breakout Buy Number


X:=(H+L+C)/3;
BBN:=2*X-L;
BSN:=2*X-H;
BBN;
BSN;

XXXXXXXXXX
1997 December TASC Trader's Tip - Volatility % Indicator
You can easily create the Volatility% Indicator from William Brower’s article in
MetaStock for Windows. First choose Indicator Builder from the Tools menu in
MetaStock. Next choose New and enter one of the following formulas:

Formula for MetaStock 6.5

Volatility%

Lookback := Input("Time Periods",1,1000,50);

HighVolatility := Input("High Volatility %",.01,100,3);

100 * Sum(100 * ATR(1)/CLOSE > HighVolatility, Lookback)/Lookback

206
Instantaneous Trendline and Sinewave Indicator as described by John Ehlers

Here is the MetaStock 6.52 or higher formula code for the Instantaneous Trendline
and Sinewave Indicator as described by John Ehlers in his article “At Last! A Trend-
Friendly Oscillator”. To implement them the following formulas must be created in
MetaStock’s Indicator Builder. Each formula must be created separately and must be
named exactly as it appears below. Only the last two formulas are plotted, so you may
wish to prevent the others from being displayed in the Indicator QuickList by
unchecking the “Display In QuickList” option when creating the formula.

To download and install the formulas use the following steps

Download the MS65FORM.DTA file into a temp folder

To Download the file for this formula click MS65FORM.DTA

Use the following instructions to Import the MS65FORM.DTA file from the temp file
it was downloaded to.

1. Run MetaStock.

2. Choose Indicator Builder from the Tools menu.

3. Click the Organize button to launch the Formula Organizer Wizard.

4. Follow the on-screen instructions.

Name: H cycle count 1a

value:= Fml("Hilbert cycle period - 1a");

If(Sum(value,6)>=360 AND Sum(value,5)<360 ,6,0) +

If(Sum(value,7)>=360 AND Sum(value,6)<360 ,7,0) +

If(Sum(value,8)>=360 AND Sum(value,7)<360 ,8,0) +

If(Sum(value,9)>=360 AND Sum(value,8)<360 ,9,0) +

If(Sum(value,10)>=360 AND Sum(value,9)<360 ,10,0) +

If(Sum(value,11)>=360 AND Sum(value,10)<360 ,11,0) +

If(Sum(value,12)>=360 AND Sum(value,11)<360 ,12,0) +

If(Sum(value,13)>=360 AND Sum(value,12)<360 ,13,0) +

207
If(Sum(value,14)>=360 AND Sum(value,13)<360 ,14,0) +

If(Sum(value,15)>=360 AND Sum(value,14)<360 ,15,0)

Name: H cycle count 2a

value:= Fml("Hilbert cycle period - 1a");

If(Sum(value,16)>=360 AND Sum(value,15)<360 ,16,0) +

If(Sum(value,17)>=360 AND Sum(value,16)<360 ,17,0) +

If(Sum(value,18)>=360 AND Sum(value,17)<360 ,18,0) +

If(Sum(value,19)>=360 AND Sum(value,18)<360 ,19,0) +

If(Sum(value,20)>=360 AND Sum(value,19)<360 ,20,0) +

If(Sum(value,21)>=360 AND Sum(value,20)<360 ,21,0) +

If(Sum(value,22)>=360 AND Sum(value,21)<360 ,22,0) +

If(Sum(value,23)>=360 AND Sum(value,22)<360 ,23,0) +

If(Sum(value,24)>=360 AND Sum(value,23)<360 ,24,0) +

If(Sum(value,25)>=360 AND Sum(value,24)<360 ,25,0)

Name: H cycle count 3a

value:= Fml("Hilbert cycle period - 1a");

If(Sum(value,26)>=360 AND Sum(value,25)<360 ,26,0) +

If(Sum(value,27)>=360 AND Sum(value,26)<360 ,27,0) +

If(Sum(value,28)>=360 AND Sum(value,27)<360 ,28,0) +

If(Sum(value,29)>=360 AND Sum(value,28)<360 ,29,0) +

If(Sum(value,30)>=360 AND Sum(value,29)<360 ,30,0) +

If(Sum(value,31)>=360 AND Sum(value,30)<360 ,31,0) +

208
If(Sum(value,32)>=360 AND Sum(value,31)<360 ,32,0) +

If(Sum(value,33)>=360 AND Sum(value,32)<360 ,33,0) +

If(Sum(value,34)>=360 AND Sum(value,33)<360 ,34,0) +

If(Sum(value,35)>=360 AND Sum(value,34)<360 ,35,0)

Name: H ip sum 1

pd:=Int(Fml("Hilbert cycle period - final-a"));

pr:=(H+L)/2;

(Cos(0)*pr)+

(Cos(360*(1/pd))*Ref(pr,-1))+

(Cos(360*(2/pd))*Ref(pr,-2))+

(Cos(360*(3/pd))*Ref(pr,-3))+

(Cos(360*(4/pd))*Ref(pr,-4))+

(Cos(360*(5/pd))*Ref(pr,-5))+

If(pd>6, Cos(360*(6/pd))*Ref(pr,-6), 0)+

If(pd>7, Cos(360*(7/pd))*Ref(pr,-7), 0)+

If(pd>8, Cos(360*(8/pd))*Ref(pr,-8), 0)+

If(pd>9, Cos(360*(9/pd))*Ref(pr,-9), 0)+

If(pd>10, Cos(360*(10/pd))*Ref(pr,-10), 0)+

If(pd>11, Cos(360*(11/pd))*Ref(pr,-11), 0)+

If(pd>12, Cos(360*(12/pd))*Ref(pr,-12), 0)+

If(pd>13, Cos(360*(13/pd))*Ref(pr,-13), 0)+

If(pd>14, Cos(360*(14/pd))*Ref(pr,-14), 0)

Name: H ip sum 2

209
pd:=Int(Fml("Hilbert cycle period - final-a"));

pr:=(H+L)/2;

If(pd>15, Cos(360*(15/pd))*Ref(pr,-15), 0)+

If(pd>16, Cos(360*(16/pd))*Ref(pr,-16), 0)+

If(pd>17, Cos(360*(17/pd))*Ref(pr,-17), 0)+

If(pd>18, Cos(360*(18/pd))*Ref(pr,-18), 0)+

If(pd>19, Cos(360*(19/pd))*Ref(pr,-19), 0)+

If(pd>20, Cos(360*(20/pd))*Ref(pr,-20), 0)+

If(pd>21, Cos(360*(21/pd))*Ref(pr,-21), 0)+

If(pd>22, Cos(360*(22/pd))*Ref(pr,-22), 0)+

If(pd>23, Cos(360*(23/pd))*Ref(pr,-23), 0)+

If(pd>24, Cos(360*(24/pd))*Ref(pr,-24), 0)

Name: H ip sum 3

pd:=Int(Fml("Hilbert cycle period - final-a"));

pr:=(H+L)/2;

If(pd>25, Cos(360*(25/pd))*Ref(pr,-25), 0)+

If(pd>26, Cos(360*(26/pd))*Ref(pr,-26), 0)+

If(pd>27, Cos(360*(27/pd))*Ref(pr,-27), 0)+

If(pd>28, Cos(360*(28/pd))*Ref(pr,-28), 0)+

If(pd>29, Cos(360*(29/pd))*Ref(pr,-29), 0)+

If(pd>30, Cos(360*(30/pd))*Ref(pr,-30), 0)+

If(pd>31, Cos(360*(31/pd))*Ref(pr,-31), 0)+

If(pd>32, Cos(360*(32/pd))*Ref(pr,-32), 0)+

210
If(pd>33, Cos(360*(33/pd))*Ref(pr,-33), 0)+

If(pd>34, Cos(360*(34/pd))*Ref(pr,-34), 0)

Name: H rp sum 1

pd:=Int(Fml("Hilbert cycle period - final-a"));

pr:=(H+L)/2;

(Sin(0)*pr)+

(Sin(360*(1/pd))*Ref(pr,-1))+

(Sin(360*(2/pd))*Ref(pr,-2))+

(Sin(360*(3/pd))*Ref(pr,-3))+

(Sin(360*(4/pd))*Ref(pr,-4))+

(Sin(360*(5/pd))*Ref(pr,-5))+

If(pd>6, Sin(360*(6/pd))*Ref(pr,-6), 0)+

If(pd>7, Sin(360*(7/pd))*Ref(pr,-7), 0)+

If(pd>8, Sin(360*(8/pd))*Ref(pr,-8), 0)+

If(pd>9, Sin(360*(9/pd))*Ref(pr,-9), 0)+

If(pd>10, Sin(360*(10/pd))*Ref(pr,-10), 0)+

If(pd>11, Sin(360*(11/pd))*Ref(pr,-11), 0)+

If(pd>12, Sin(360*(12/pd))*Ref(pr,-12), 0)+

If(pd>13, Sin(360*(13/pd))*Ref(pr,-13), 0)+

If(pd>14, Sin(360*(14/pd))*Ref(pr,-14), 0)

Name: H rp sum 2

pd:=Int(Fml("Hilbert cycle period - final-a"));

pr:=(H+L)/2;

211
If(pd>15, Sin(360*(15/pd))*Ref(pr,-15), 0)+

If(pd>16, Sin(360*(16/pd))*Ref(pr,-16), 0)+

If(pd>17, Sin(360*(17/pd))*Ref(pr,-17), 0)+

If(pd>18, Sin(360*(18/pd))*Ref(pr,-18), 0)+

If(pd>19, Sin(360*(19/pd))*Ref(pr,-19), 0)+

If(pd>20, Sin(360*(20/pd))*Ref(pr,-20), 0)+

If(pd>21, Sin(360*(21/pd))*Ref(pr,-21), 0)+

If(pd>22, Sin(360*(22/pd))*Ref(pr,-22), 0)+

If(pd>23, Sin(360*(23/pd))*Ref(pr,-23), 0)+

If(pd>24, Sin(360*(24/pd))*Ref(pr,-24), 0)

Name: H rp sum 3

pd:=Int(Fml("Hilbert cycle period - final-a"));

pr:=(H+L)/2;

If(pd>25, Sin(360*(25/pd))*Ref(pr,-25), 0)+

If(pd>26, Sin(360*(26/pd))*Ref(pr,-26), 0)+

If(pd>27, Sin(360*(27/pd))*Ref(pr,-27), 0)+

If(pd>28, Sin(360*(28/pd))*Ref(pr,-28), 0)+

If(pd>29, Sin(360*(29/pd))*Ref(pr,-29), 0)+

If(pd>30, Sin(360*(30/pd))*Ref(pr,-30), 0)+

If(pd>31, Sin(360*(31/pd))*Ref(pr,-31), 0)+

If(pd>32, Sin(360*(32/pd))*Ref(pr,-32), 0)+

If(pd>33, Sin(360*(33/pd))*Ref(pr,-33), 0)+

If(pd>34, Sin(360*(34/pd))*Ref(pr,-34), 0)

212
Name: H TL sum 1

value:=Int(Fml("Hilbert cycle period - final-a"));

If(value=6, Mov((H+L)/2,8,S),0) +

If(value=7, Mov((H+L)/2,9,S),0) +

If(value=8, Mov((H+L)/2,10,S),0) +

If(value=9, Mov((H+L)/2,11,S),0) +

If(value=10, Mov((H+L)/2,12,S),0) +

If(value=11, Mov((H+L)/2,13,S),0) +

If(value=12, Mov((H+L)/2,14,S),0) +

If(value=13, Mov((H+L)/2,15,S),0) +

If(value=14, Mov((H+L)/2,16,S),0) +

If(value=15, Mov((H+L)/2,17,S),0)

Name: H TL sum 2

value:=Int(Fml("Hilbert cycle period - final-a"));

If(value=16, Mov((H+L)/2,18,S),0) +

If(value=17, Mov((H+L)/2,19,S),0) +

If(value=18, Mov((H+L)/2,20,S),0) +

If(value=19, Mov((H+L)/2,21,S),0) +

If(value=20, Mov((H+L)/2,22,S),0) +

If(value=21, Mov((H+L)/2,23,S),0) +

If(value=22, Mov((H+L)/2,24,S),0) +

If(value=23, Mov((H+L)/2,25,S),0) +

If(value=24, Mov((H+L)/2,26,S),0) +

213
If(value=25, Mov((H+L)/2,27,S),0)

Name: H TL sum 3

value:=Int(Fml("Hilbert cycle period - final-a"));

If(value=26, Mov((H+L)/2,28,S),0) +

If(value=27, Mov((H+L)/2,29,S),0) +

If(value=28, Mov((H+L)/2,30,S),0) +

If(value=29, Mov((H+L)/2,31,S),0) +

If(value=30, Mov((H+L)/2,32,S),0) +

If(value=31, Mov((H+L)/2,33,S),0) +

If(value=32, Mov((H+L)/2,34,S),0) +

If(value=33, Mov((H+L)/2,35,S),0) +

If(value=34, Mov((H+L)/2,36,S),0) +

If(value=35, Mov((H+L)/2,37,S),0)

Name: Hilbert cycle period - 1a

value1:=((H+L)/2) - Ref(((H+L)/2),-6);

value2:= Ref(value1,-3);

value3:=0.75*(value1-Ref(value1,-6)) + 0.25*(Ref(value1,-2)-Ref(value1,-4));

inphase:= 0.33 * value2 + (0.67 * PREV);

quad:= 0.2 * value3 + ( 0.8 * PREV);

p1:=Atan(Abs(quad+Ref(quad,-1)),Abs(inphase+Ref(inphase,-1)));

phase:=If(inphase<0 AND quad>0, 180-p1,

214
If(inphase<0 AND quad<0, 180+p1,

If(inphase>0 AND quad<0, 360-p1,p1)));

dp:=If(Ref(phase,-1)<90 AND phase>270, 360+Ref(phase,-1)-phase,Ref(phase,-1)-


phase);

dp2:=If(dp < 1, 1,

If(dp > 60, 60, dp));

dp2

Name: Hilbert cycle period - final-a

c1:= Fml( "H cycle count 1a") + Fml( "H cycle count 2a") + Fml( "H cycle count 3a")
;

c2:=If(c1=0,PREV,c1);

(0.25*c2) + (0.75*PREV)

Name: Instantaneous Trend Line

pr:=(H+L)/2;

(Fml("H TL sum 1") + Fml("H TL sum 2") + Fml("H TL sum 3"));

0.33*(pr + (0.5*(pr-Ref(pr,-3)))) + (0.67*PREV)

Name: Sinewave Indicator

pd:=Int(Fml("Hilbert cycle period - final-a"));

cp:=Fml("Hilbert cycle period - final-a");

ip:=Fml( "H ip sum 1") + Fml( "H ip sum 2") +

215
Fml( "H ip sum 3");

rp:=Fml( "H rp sum 1") + Fml( "H rp sum 2") +

Fml( "H rp sum 3");

dc1:=If(Abs(ip)>0.001, Atan(rp/ip,1), 90*If(rp>=0,1,-1));

dc2:=If(pd<30 AND cp>0,dc1+((6.818/cp - 0.227)*360),dc1);

dc3:=If(ip<0, dc2+270, dc2+90);

dcp:=If(dc3>315, dc3-360, dc3);

Sin(dcp);

Sin(dcp+45)
from Henry Kaczmarczyk
Zero Lag EMA
Here's my Metastock 6.2 coded version of the Zero Lag Moving Average, as
described in the April, 2000, issue of Technical Analysis of Stocks and Commodities.
I've also used it to construct a Zero Lag MACD and a Zero Lag MACD trigger signal.

Period:= Input("What Period",1,250,10);


EMA1:= Mov(CLOSE,Period,E);
EMA2:= Mov(EMA1,Period,E);
Difference:= EMA1 - EMA2;
ZeroLagEMA:= EMA1 + Difference;
ZeroLagEMA

Peter Martin
alakazam@bigpond.com

IZero Lag MACD

EMA1:= Mov(CLOSE,13,E);
EMA2:= Mov(EMA1,13,E);
Difference:= EMA1 - EMA2;
ZeroLagEMA13:= EMA1 + Difference;
EMA1:= Mov(CLOSE,21,E);
EMA2:= Mov(EMA1,21,E);
Difference:= EMA1 - EMA2;
ZeroLagEMA21:= EMA1 + Difference;
ZeroLagMACD:=ZeroLagEMA13 - ZeroLagEMA21;
ZeroLagMACD

Peter Martin

216
alakazam@bigpond.com

Zero Lag MACD Trigger Signal


(To be used with the ZeroLag MACD above)

EMA1:= Mov(CLOSE,13,E);
EMA2:= Mov(EMA1,13,E);
Difference:= EMA1 - EMA2;
ZeroLagEMA13:= EMA1 + Difference;
EMA1:= Mov(CLOSE,21,E);
EMA2:= Mov(EMA1,21,E);
Difference:= EMA1 - EMA2;
ZeroLagEMA21:= EMA1 + Difference;
ZeroLagMACD:=ZeroLagEMA13 - ZeroLagEMA21;
EMA1:= Mov(ZeroLagMACD,8,E);
EMA2:= Mov(EMA1,8,E);
Difference:= EMA1 - EMA2;
ZeroLagTRIG:= EMA1 + Difference;
ZeroLagTRIG

Regards

Peter Martin
alakazam@bigpond.com

IMPROVED CHANDELIER EXIT

A few weeks ago when the Chandelier Exit was posted to on our board board, I
asked if there was a faster version of it. On my (slowpoke) 200 Mhz PC at
home, it took about 1 to 2 minutes to calculate the formula on a single
stock.

Anyway, I did not hear of any feasible solutions. Last night, upon reading
about the 25X25 system on this site , it struck me that the original
Chandelier Exit (see below) had a whole bunch of PREV statements in it. I'm
sure everyone knows where I'm going with this by now.

Anyway, here is how the code (at least this iteration) should be modified to
speed up the calculation by a factor of 5. Basically, we move PREV into a
variable vPREV prior to using it (so that it is only calculate once) in the
long and short exits. Here is the code for the long exit. I tested it with
the sample Entry Rule and receive the same results in 1/5th the time. Just
modify the SHORT exit in the same way. Hope this helps everyone using it.

217
{DEFINE ENTRY PRICE, WITH EXIT BEING -- ENTRY PRICE AND NO
TRADE BEING 0}
{Move PREV into a variable to speed things up - DB 2/17/00}
vPREV:=PREV;
EntryPrice:= If(vPREV <= 0,
{Trade entered today?}
If(LongEntry, CLOSE, 0),
{Trade entered before today. Stopped today?}
If(LOW <= vPREV - MoneyMgmtStop, -vPREV,
If(LOW <= HighestSince(1,vPREV=0, HIGH) - 3 * ATR(10), -vPREV,
If(LOW <= HighestSince(1,vPREV=0, CLOSE) - 2.5 * ATR(10), -vPREV,
vPREV))));

David Bozkurtian 2/17/00


VARIABLE MA FORMULA - UPDATED
periods:=Input("periods",1,244,89);
VariableMA511( mp() , periods)

Equis put this function in for me. It uses VHF rather than CMO. Unlike the present
version, this is better.

Richard

RSI OFFSET

RSI(13) - 50 {offset the RSI to +-50}

{from Warthog}

MACD OFFSET

(MACD()*10 +50) {offset the MACD to 50}

{from Warthog}
Jeff Cooper 180's Buy
A:Close
B:{MA}Ref(C,-1)<Mov(C,10,S) AND Ref(C,-1)<Mov(C,50,S)
AND C>Mov(c,10,S) AND C>Mov(C,50,S)
C:{Breakout}Ref(C,-1)<=((Ref(H,-1)-Ref(L,-1))*.25)+Ref(L,-1)
AND C>=H-(H-L)*.25
D:{Entry}HHV(H,2)+.125
E:{Stop}HHV(H,2)+.125-1

Jeff Cooper 180's Sell


A:Close

218
B:{MA}Ref(C,-1)>Mov(C,10,S) AND Ref(C,-1)>Mov(C,50,S)
AND C<Mov(c,10,S) AND C<Mov(C,50,S)
C:{Breakout}Ref(C,-1)>=((Ref(H,-1)-Ref(L,-1))*.25)+Ref(H,-1)
AND C<=L+((H-L)*.25)
D:{Entry}LLV(L,2)-.125
E:{Stop}LLV(L,2)-.125+1

Jeff Cooper Lizards Buy


A:close
B:{Signal}O>H-(H-L)*.25 AND C>H-(H-L)*.25 AND
L<Ref(LLV(L,10),-1)
C:{entry}H+.125
D:{Stop}H+1.125
Filter:O>H-(H-L)*.25 AND C>H-(H-L)*.25 AND
L<Ref(LLV(L,10),-1)

Jeff Cooper Lizards Sell


A:close
B:{Signal}O<L+(H-L)*.25 AND C<L+(H-L)*.25 AND
H>Ref(HHV(H,10),-1)
C:{entry}L-.125
D:{Stop}L-1.125
Filter:O<L+(H-L)*.25 AND C<L+(H-L)*.25 AND
H>Ref(HHV(H,10),-1)

Jeff Cooper Slingshots Buy


A:Close
B:{Range breakout}Ref(H,-1)>=Ref(HHV(H,40),-1)
AND L<Ref(L,-1)-.125
C:{entry}If(O>Ref(H,-1)+.125,O,0)
D:{Stop}If(If(O>Ref(H,-1)+.125,O,0)=O,Ref(O,-1)-2,0)
Filter:Ref(H,-1)>=Ref(HHV(H,40),-1)
AND L<Ref(L,-1)-.125

Jeff Cooper Slingshots Sell


A:Close
B:{Range breakout}Ref(L,-1)<=Ref(LLV(L,40),-1)
AND H>Ref(H,-1)+.125
C:{entry}If(O<Ref(L,-1)-.125,O,0)
D:{Stop}If(If(O<Ref(L,-1)-.125,O,0),Ref(O,-1)+2,0)
Filter:Ref(L,-1)<=Ref(LLV(L,40),-1)
AND H>Ref(H,-1)+.125

219
Jeff Cooper Whoops Sell

A:close
B:C<Mov(C,10,S) AND C<Mov(C,50,S) AND
O>Ref(C,-1)+.25
C:{Entry}Ref(C,-1)-.125
D:{Stop}Ref(C,-1)-.125+1
Filter:C<Mov(C,10,S) AND C<Mov(C,50,S) AND
O>Ref(C,-1)+.25

A:Close
B:ADX(14){The higher the better}
C: PDI(14)>MDI(14)
D:If(L<Ref(L,-1) and Ref(L,-1)<Ref(L,-2) and
Ref(L,-2)<Ref(L,-3),1,0)
E:{Entry}HHV(H,3)+.125
F:{stop}LLV(L,3)
Filter:ColB>30 and ColC and ColD=1

1234's Sell
A:Close
B:ADX(14){The higher the better}
C: PDI(14)<MDI(14)
D:If(H>Ref(H,-1) and Ref(H,-1)>Ref(H,-2) and
Ref(H,-2)>Ref(H,-3),1,0)
E:{Entry}LLV(L,3)-.125
F:{stop}HHV(H,3)
Filter:ColB>30 and ColC and ColD=1

Boomers buy&Sell
A:Close
B:{Signal Buy=-1,Sell=1}
If(ADX(14)>30 and PDI(14)>MDI(14),-1,If(ADX(14)>30
and PDI(14)<MDI(14),1,0))
C:{setup}Ref(H,-2)>=Ref(H,-1) and Ref(H,-1)>=H and
Ref(L,-2)<=Ref(L,-1) and Ref(L,-1)<=L
D:{Entry}If(ADX(14)>30 and PDI(14)>MDI(14) and
Ref(H,-2)>=Ref(H,-1) and Ref(H,-1)>=H and
Ref(L,-2)<=Ref(L,-1) and
Ref(L,-1)<=L,HHV(H,3)+.125,IF(ADX(14)>30 and
PDI(14)<MDI(14) and Ref(H,-2)>=Ref(H,-1) and
Ref(H,-1)>=H and Ref(L,-2)<=Ref(L,-1) and
Ref(L,-1)<=L,LLV(L,3)-.125,0))
E:{Stop}If(ADX(14)>30 and PDI(14)>MDI(14) and
Ref(H,-2)>=Ref(H,-1) and Ref(H,-1)>=H and

220
Ref(L,-2)<=Ref(L,-1) and
Ref(L,-1)<=L,LLV(L,3)-.125,IF(ADX(14)>30 and

PDI(14)<MDI(14) and Ref(H,-2)>=Ref(H,-1) and


Ref(H,-1)>=H and Ref(L,-2)<=Ref(L,-1) and
Ref(L,-1)<=L,HHV(H,3)+.125,0))
F:ADX(14){Higher the better}
Filter:ColB and ColC

Expansion pivots buy


A:=Close
B:{Breakout}(H-L)>ATR(9)
C:{Signal}Ref(C,-2)<=Mov(C,50,S) and
Ref(C,-1)>Mov(C,50,S) OR Ref(C,-1)<=Mov(C,50,S) and
C>Mov(C,50,S)
D:{entry}HHV(H,2)+.125
E:{Stop}If(Ref(C,-2)<=Mov(C,50,S) and
Ref(C,-1)>Mov(C,50,S),Ref(C,-1)-1,If(Ref(C,-1)<=Mov(C,50,S)
and C>Mov(C,50,S),C-1,0))
Filter:ColB and ColC

expansion pivots sell


A:=Close
B:{Breakout}(H-L)>ATR(9)
C:{Signal}Ref(C,-2)>=Mov(C,50,S) and
Ref(C,-1)<Mov(C,50,S) OR Ref(C,-1)>=Mov(C,50,S) and
C<Mov(C,50,S)
D:{entry}LLV(L,2)-.125
E:{Stop}If(Ref(C,-2)>=Mov(C,50,S) and
Ref(C,-1)<Mov(C,50,S),Ref(C,-1)-1,If(Ref(C,-1)>=Mov(C,50,S)
and C<Mov(C,50,S),C-1,0))
Filter:ColB and ColC

Gilligan's island buy


A:Close
B:GapDown()<=Ref(LLV(L,40),-1) and C>=O and
C>=((H-L)*.50)+L
C:{entry}H+.125
D:{stop}H+.125-1
Filter: GapDown()<=Ref(LLV(L,40),-1) and C>=O and
C>=((H-L)*.50)+L

Gilligan's island sell


A:Close
B:GapUp()>=Ref(HHV(H,40),-1) and C<=O and
C<=((H-L)*.50)+L
C:{entry}L-.125

221
D:{stop}L-.125+1
Filter: GapUp()>=Ref(HHV(H,40),-1) and C<=O and C<=((H-L)*.50)+L

SIROC indicator from Elder

ROC(Mov(C,13,E),21,%)

MOVING AVERAGE VIOLATED BY %

200 dma violated by 100%


enter short
c>=(mov(c,200,s)*2)

200 dma violated by 50%


enter short
c>=(mov(c,200,s)*1.5)

200 dma w/i 1 pt


enter long
c>=mov(c,200,s)+1
exit long
((if ((c<=prev(llv(c,15)-.5, 1)),1,0)) + (if
((c<=.75*hhv(c,10)),1,0)))>=1
enter short
c<=mov(c,200,s)-1
exit short
c>=hhv(llv(c,15), 15)+.5

200 dma w/i 3pts


enter short
c<=mov(c,200,s)-3
exit short
c>=hhv(llv(c,15), 15)+.5

21 d reversal w di
enter long
c>prev(hhv(c,21),1) and adx(1)>adx(14) and
(pdi(9)>mdi(14))
exit long
c<prev(llv(c,21),1) and (pdi(14)<mdi(9))
enter short
c<prev(llv(c,21),1) and adx(1)>adx(14) and
(pdi(9)<mdi(14))
exit short
c>prev(hhv(c,21),1) and (pdi(9)>mdi(14))

222
Stochastic MA system
enter long
mov(stoch(55,21),5,w)>ref(mov(stoch(55,21),5,w),-1)
and mov(stoch(55,21),5,w)<75 and
mov(stoch(55,21),5,w)>20
exit long
(mov(stoch(55,21),5,w)<75 and
ref(mov(stoch(55,21),5,w),-1)>75)
enter short
(mov(stoch(55,21),5,w)<70 and
ref(mov(stoch(55,21),5,w),-1)>70) and
mov(stoch(55,21),5,w)<ref(mov(stoch(55,21),5,w),-1)
exit short
mov(stoch(55,21),5,w)>ref(mov(stoch(55,21),5,w),-1)
and mov(stoch(55,21),5,w)<75 and
mov(stoch(55,21),5,w)>20

Bollinger Bands formula 7 day


enter long
high>(mov(Close,20,S)-std(Close,20,2)) and
ref(low,-7)<ref((mov(Close,20,S)-std(Close,20,2)),-7)
exit long
close<(mov(Close,20,S)+std(Close,20,2)) and
ref(close,-7)>ref((mov(Close,20,S)+std(Close,20,2)),-7)
and
Mov((RSI(14)- LLV(RSI(14),14))
/(HHV(RSI(14),14)-(LLV(RSI(14),14))),14,E)*100<70 and
ref((Mov((RSI(14)- LLV(RSI(14),14))
/(HHV(RSI(14),14)-(LLV(RSI(14),14))),14,E)*100),-3)>70
and
(mov(Close,20,S)+std(Close,20,2))>(mov(c,89,s)+(.062*(mov(c,89,s))))

EMA Cross system


avoid using when the market has no clear direction --
enter long
mov(c,5,e)>mov(c,21,e) and
ref(mov(c,5,e),-1)<=ref(mov(c,21,e),-1)
exit long
mov(c,5,e)<mov(c,21,e) and
ref(mov(c,5,e),-1)>=ref(mov(c,21,e),-1)

223
BOOMERS TRADING SIGNALS

Boomers buysig

enter long
((adx(14)+adx(27))/2)>30 and pdi(27)>mdi(27)
exit long
c<=prev(llv(c,15)-.5, 1) or c<=.75*hhv(c,10)

Boomers watchsig **
enter long
prev(h,1)<=prev(h,2) and prev(l,1)>=prev(l,2) and
BullHarami()
exit long
c<=prev(llv(c,15)-.5, 1) or c<=.75*hhv(c,10)

Boomer's watchsig 2** (ref not prev)


enter long
ref(h,-1)<=ref(h,-2) and ref(l,-1)>=ref(l,-2) and
BullHarami()
exit long
c<=ref(llv(c,15)-.5,-1) or c<=.75*hhv(c,10)

Resistance and Support * F


PrCnt:=Input("Percentage",0,100,10);
LookBack:= Input("Look Back Periods",1,1000,10);
Resistance:=ValueWhen(1,Cross(Mov(C,LookBack,S),C),HHV(H,LookBack));

Support:=ValueWhen(1,Cross(C,Mov(C,LookBack,S)),LLV(L,LookBack));
Resistance * ((100-prcnt)/100);
Support * ((prcnt/100)+1);

Resistance and Support


LookBack := Input("Look Back Periods",1,1000,10);
Resistance :=ValueWhen(1,Cross(Mov(C, LookBack,
S),C),HHV(H, LookBack));
Support :=ValueWhen(1,Cross(C,Mov(C, LookBack,
S)),LLV(L, LookBack));
Resistance;
Support;

Guppy's MMA Short


{short-term}
Mov(C,3,E);Mov(C,5,E);Mov(C,7,E);
Mov(C,10,E);Mov(C,12,E);Mov(C,15,E);

Guppy's MMA Long

224
{long-term}
Mov(C,30,E);Mov(C,35,E);Mov(C,40,E);
Mov(C,45,E);Mov(C,50,E);Mov(C,60,E)

From superform@hotmail.com

Average Dollar price Volatility exploration - Deel


This exploration is designed to provide the
average dollar price volatility figure in column F.
This will find this figure for all stocks scanned.
It is most useful to apply this just to an exploration
of a small group of stocks. It matches the steps in
Deels book The Strategic Electronic Day Trader.

Col A: day 1 HIGH - LOW


Col B: day 2 Ref((HIGH-LOW),-1)
Col C: Ref((HIGH-LOW),-2)
Col D: Ref((HIGH-LOW),-3)
Col E: Ref((HIGH-LOW),-4)
Col F: (H - L + (Ref(H,-1) - Ref(L,-1)) + (Ref(H,-2) - Ref(L,-2))+(Ref(H,-3) - Ref(L,-
3)) + (Ref(H,-4) - Ref(L,-4))) / 5

Average Dollar price Volatility indicator - Deel


This indicator plots the value on the chart display.
It is useful only as a quick method of attaching the volatility
value to the stock. Apply this with caution and make sure that
the new scale display is also included.
(H - L + (Ref(H,-1) - Ref(L,-1)) + (Ref(H,-2) - Ref(L,-2))+(Ref(H,-3) - Ref(L,-3)) +
(Ref(H,-4) - Ref(L,-4))) / 5

7 day rate of change ported from Super Charts


((C-Ref(CLOSE,-7))/Ref(CLOSE,-7)*100)
CLOSE ABOVE MEDIAN PRICE
This exploration is designed to find those stocks where the close is above the median
price over the past five days. It matches the steps in Dels bvook The Strategic
Electronic Day Trader.
col a = CLOSE - MP()
col b = (Ref(CLOSE,-1))-(Ref( MP() ,-1))
Col c = (Ref(CLOSE,-2))-(Ref( MP() ,-2))
col d = (Ref(CLOSE,-3))-(Ref( MP() ,-3))
col e = (Ref(CLOSE,-4))-(Ref( MP() ,-4))
filter = colA>=0 AND colB>=0 AND colC>=0 AND colD>=0 AND colE>=0
The filter in the exploration only shows those stiocks that have the strongest bullish
bias over all 5 days. By removing the filter all stocks will be shown. Ranking the first
colum will then allow you to estaboish the overall score for each stock.

MACDcustom

225
The Input() Function(MSK-man. p.271-273) cannot be used directly in the Explorer
(MSK-man. p.351). It is reserved to be used in a custom indicator. However, the
custom indicator's default value can be used in an exploration.

Since you have created a {faulty} custom indicator, than just re-code it. By
referencing the Input() Function using the fml() CALL Function
(MSK-man.p.226-227 and 208-209 and 212), you can still use its {by you at design
time} assigned Default value.

Custom Indicator :
Name: MACDcustom
Formula:
MAprd:=Input( "Periods", 5 {Minimum}, 30 {Maximum}, 14 {Default} );
YourTrig:=Mov( MACD(), MAprd, E );
MACD();
YourTrig

When creating the exploration just click the function button and look under the
Custom Indicators heading for both of the above custom indicator functions, and
"Open" each of them one by one, to paste them into your column TABs (MSK-man.
p.347-348) .

Exploration:
Name: MACD crosses my Trigger
Columns:
Cola:
Name: Close
Formula:
C
Colb:
Name: MACD
Formula:
FML( "MACDcustom , MACD" )
Colc:
Name: MACDTrigger
Formula:
FML( "MACDcustom , YourTrig" )
Filter:
Formula:
Colb > Colc
{or
FML( "MACDcustom , MACD" ) > FML( "MACDcustom , YourTrig" )
}

Ton Maas
Submitted by warrah@comcen.com.au

226
ADX AND TRENDLINES

if you want to identify directional movement by expressing that the ADX "is rising"
the most basic way to do it would be:

ADX(14) > Ref(ADX(14),-1) -- Today's ADX is greater than yesterday's ADX.

There is another aspect to the ADX that bears investigation, though; namely the level
of the ADX. There seems to be a general consensus that an ADX over, say, 30
indicates a stronger trend than lower ADX readings. So you could either write
ADX(14) > 30 -- or not, depending on your objectives. You can stipulate that both
conditions are true by joining them with the word "and."

Also, I have found the following helpful: try using the custom ADX formula posted
on the MetaStock website. Wilder wrote the original ADX in such a fashion that it
rounds the readings out to the nearest whole number. The "regular" canned MetaStock
ADX does this, while the custom ADX does not. The non-rounded readings are just a
shade more sensitive, which can be helpful.

from Philip pschmi02@sprynet.com


Submitted by warrah@comcen.com.au

Brown's Indicator.
----------------------------------------

Name: RSI derivative index (EL) - C. Brown {EasyLanguage}

Formula:
Base:=Mov(RSI(14),6,S);
ATRcustom:=HHV(
ValueWhen(1,RSI(14)>Ref(RSI(14),-1),ATR(1))OR
ValueWhen(2,RSI(14)>Ref(RSI(14),-1),ATR(1))OR
ValueWhen(3,RSI(14)>Ref(RSI(14),-1),ATR(1)),14);
Part1:=
{up coefficient is a factor 2.3 and added}
(2.3*(Mov(ATRcustom, 15,S)));
Part2:=
{down coefficient is factor 2.1 and subtracted}
(2.1*(Mov(ATRcustom, 15,S)));
{Part3=if RSI closes up or equal to, than part1,
else, if RSI closes down, part2}
If( Base>=Ref(Base,-1),
{RSI up=TRUE, then} Base+Part1,{else}
{RSI up=FALSE,then} Base-Part2)
Submitted by warrah@comcen.com.au

FINDING TRENDINESS
A remark by Chuck LeBeau about trading with the trend has stayed with me. He

227
speaks of the actual strength of a trend as opposed to merely its direction. Entry
strategies (pullbacks in his view) should be tailored to both direction and strength, he
says. This makes perfect sense to me.

Here are some initial thoughts. Perhaps you can help me to arrive at some kind of
"hierarchy" of trendiness, or call it a classification, or a taxonomy,
consisting of both direction and strength. For convenience, I'll describe only long
trades.

I. General direction, long term:


EMA(21) > EMA(55)

II. Trend picks up steam:


EMA(13) > EMA(21) > EMA(55)

III. Strong:
EMA(8) >EMA(13) > EMA(21) > EMA(55)

IV. Somewhere between II. and III. the ADX(13/14) usually starts rising. From what
I've seen, a rising ADX at any level generally means business:
ADX(13) > Ref(ADX(13),-1)

V. Very strong trend: (this is where Linda Bradford's "Holy Grail" and such kick in)
ADX(13) > Ref(ADX(13) and
ADX(13) > 30

Almost forgot . . . very little direction (but don't fall asleep at the wheel):
ADX(13) < say, 12-15 and has been bumbling along down there for a while (hard to
quantify for me to date)

from Philip pschmi02@sprynet.com


Submitted by warrah@comcen.com.au

Weakness in a strong trend


In an up trend, three or four successive lower CLOSES and the EMA(21) is rising.

SimpleX LONG:

C <= Ref(C,-1) AND


Ref(C, -1) <= Ref(C, -2) AND
Ref(C, -2) <= Ref(C, -3) AND
Mov(C, 21, E) > Ref(Mov(C, 21, E), -1)
OR
C <= Ref(C,-1) AND
Ref(C, -1) <= Ref(C, -2) AND
Ref(C, -2) <= Ref(C, -3) AND
Ref(C, -3) <= Ref(C, -4) AND
Mov(C, 21, E) > Ref(Mov(C, 21, E), -1)

SimpleX SHORT:

228
C >= Ref(C,-1) AND
Ref(C, -1) >= Ref(C, -2) AND
Ref(C, -2) >= Ref(C, -3) AND
Mov(C, 21, E) < Ref(Mov(C, 21, E), -1)
OR
C >= Ref(C,-1) AND
Ref(C, -1) >= Ref(C, -2) AND
Ref(C, -2) >= Ref(C, -3) AND
Ref(C, -3) >= Ref(C, -4) AND
Mov(C, 21, E) < Ref(Mov(C, 21, E), -1)

Rig this up with an OB/OS oscillator and you've got an entry that is, well, at least
worth considering.

Philip pschmi02@sprynet.com
Submitted by warrah@comcen.com.au

Double inside day


{For today is an inside day}
H < Ref(H,-1) and
L > Ref(L,-1) and
{For yesterday was an inside day}
Ref(H,-1) < Ref(H,-2) and
Ref(L,-1) > Ref(L,-2)
Submitted by warrah@comcen.com.au

Resistance and Support * F


PrCnt:=Input("Percentage",0,100,10);
LookBack:= Input("Look Back Periods",1,1000,10);
Resistance:=ValueWhen(1,Cross(Mov(C,LookBack,S),C),HHV(H,LookBack));

Support:=ValueWhen(1,Cross(C,Mov(C,LookBack,S)),LLV(L,LookBack));
Resistance * ((100-prcnt)/100);
Support * ((prcnt/100)+1);

Resistance and Support


LookBack := Input("Look Back Periods",1,1000,10);
Resistance :=ValueWhen(1,Cross(Mov(C, LookBack,
S),C),HHV(H, LookBack));
Support :=ValueWhen(1,Cross(C,Mov(C, LookBack,
S)),LLV(L, LookBack));
Resistance;
Support;

Guppy's MMA Short


{short-term}
Mov(C,3,E);Mov(C,5,E);Mov(C,7,E);

229
Mov(C,10,E);Mov(C,12,E);Mov(C,15,E);

Guppy's MMA Long


{long-term}
Mov(C,30,E);Mov(C,35,E);Mov(C,40,E);
Mov(C,45,E);Mov(C,50,E);Mov(C,60,E)

From superform@hotmail.com

Average Dollar price Volatility exploration - Deel


This exploration is designed to provide the
average dollar price volatility figure in column F.
This will find this figure for all stocks scanned.
It is most useful to apply this just to an exploration
of a small group of stocks. It matches the steps in
Deels book The Strategic Electronic Day Trader.

Col A: day 1 HIGH - LOW


Col B: day 2 Ref((HIGH-LOW),-1)
Col C: Ref((HIGH-LOW),-2)
Col D: Ref((HIGH-LOW),-3)
Col E: Ref((HIGH-LOW),-4)
Col F: (H - L + (Ref(H,-1) - Ref(L,-1)) + (Ref(H,-2) - Ref(L,-2))+(Ref(H,-3) - Ref(L,-
3)) + (Ref(H,-4) - Ref(L,-4))) / 5

Average Dollar price Volatility indicator - Deel


This indicator plots the value on the chart display.
It is useful only as a quick method of attaching the volatility
value to the stock. Apply this with caution and make sure that
the new scale display is also included.
(H - L + (Ref(H,-1) - Ref(L,-1)) + (Ref(H,-2) - Ref(L,-2))+(Ref(H,-3) - Ref(L,-3)) +
(Ref(H,-4) - Ref(L,-4))) / 5

7 day rate of change ported from Super Charts


((C-Ref(CLOSE,-7))/Ref(CLOSE,-7)*100)
CLOSE ABOVE MEDIAN PRICE
This exploration is designed to find those stocks where the close is above the median
price over the past five days. It matches the steps in Dels bvook The Strategic
Electronic Day Trader.
col a = CLOSE - MP()
col b = (Ref(CLOSE,-1))-(Ref( MP() ,-1))
Col c = (Ref(CLOSE,-2))-(Ref( MP() ,-2))
col d = (Ref(CLOSE,-3))-(Ref( MP() ,-3))
col e = (Ref(CLOSE,-4))-(Ref( MP() ,-4))
filter = colA>=0 AND colB>=0 AND colC>=0 AND colD>=0 AND colE>=0
The filter in the exploration only shows those stiocks that have the strongest bullish
bias over all 5 days. By removing the filter all stocks will be shown. Ranking the first

230
colum will then allow you to estaboish the overall score for each stock.

MACDcustom
The Input() Function(MSK-man. p.271-273) cannot be used directly in the Explorer
(MSK-man. p.351). It is reserved to be used in a custom indicator. However, the
custom indicator's default value can be used in an exploration.

Since you have created a {faulty} custom indicator, than just re-code it. By
referencing the Input() Function using the fml() CALL Function
(MSK-man.p.226-227 and 208-209 and 212), you can still use its {by you at design
time} assigned Default value.

Custom Indicator :
Name: MACDcustom
Formula:
MAprd:=Input( "Periods", 5 {Minimum}, 30 {Maximum}, 14 {Default} );
YourTrig:=Mov( MACD(), MAprd, E );
MACD();
YourTrig

When creating the exploration just click the function button and look under the
Custom Indicators heading for both of the above custom indicator functions, and
"Open" each of them one by one, to paste them into your column TABs (MSK-man.
p.347-348) .

Exploration:
Name: MACD crosses my Trigger
Columns:
Cola:
Name: Close
Formula:
C
Colb:
Name: MACD
Formula:
FML( "MACDcustom , MACD" )
Colc:
Name: MACDTrigger
Formula:
FML( "MACDcustom , YourTrig" )
Filter:
Formula:
Colb > Colc
{or
FML( "MACDcustom , MACD" ) > FML( "MACDcustom , YourTrig" )
}

Ton Maas
Submitted by warrah@comcen.com.au

231
ADX AND TRENDLINES
if you want to identify directional movement by expressing that the ADX "is rising"
the most basic way to do it would be:

ADX(14) > Ref(ADX(14),-1) -- Today's ADX is greater than yesterday's ADX.

There is another aspect to the ADX that bears investigation, though; namely the level
of the ADX. There seems to be a general consensus that an ADX over, say, 30
indicates a stronger trend than lower ADX readings. So you could either write
ADX(14) > 30 -- or not, depending on your objectives. You can stipulate that both
conditions are true by joining them with the word "and."

Also, I have found the following helpful: try using the custom ADX formula posted
on the MetaStock website. Wilder wrote the original ADX in such a fashion that it
rounds the readings out to the nearest whole number. The "regular" canned MetaStock
ADX does this, while the custom ADX does not. The non-rounded readings are just a
shade more sensitive, which can be helpful.

from Philip pschmi02@sprynet.com


Submitted by warrah@comcen.com.au

Brown's Indicator.
----------------------------------------

Name: RSI derivative index (EL) - C. Brown {EasyLanguage}

Formula:
Base:=Mov(RSI(14),6,S);
ATRcustom:=HHV(
ValueWhen(1,RSI(14)>Ref(RSI(14),-1),ATR(1))OR
ValueWhen(2,RSI(14)>Ref(RSI(14),-1),ATR(1))OR
ValueWhen(3,RSI(14)>Ref(RSI(14),-1),ATR(1)),14);
Part1:=
{up coefficient is a factor 2.3 and added}
(2.3*(Mov(ATRcustom, 15,S)));
Part2:=
{down coefficient is factor 2.1 and subtracted}
(2.1*(Mov(ATRcustom, 15,S)));
{Part3=if RSI closes up or equal to, than part1,
else, if RSI closes down, part2}
If( Base>=Ref(Base,-1),
{RSI up=TRUE, then} Base+Part1,{else}
{RSI up=FALSE,then} Base-Part2)
Submitted by warrah@comcen.com.au

FINDING TRENDINESS
A remark by Chuck LeBeau about trading with the trend has stayed with me. He
speaks of the actual strength of a trend as opposed to merely its direction. Entry

232
strategies (pullbacks in his view) should be tailored to both direction and strength, he
says. This makes perfect sense to me.

Here are some initial thoughts. Perhaps you can help me to arrive at some kind of
"hierarchy" of trendiness, or call it a classification, or a taxonomy,
consisting of both direction and strength. For convenience, I'll describe only long
trades.

I. General direction, long term:


EMA(21) > EMA(55)

II. Trend picks up steam:


EMA(13) > EMA(21) > EMA(55)

III. Strong:
EMA(8) >EMA(13) > EMA(21) > EMA(55)

IV. Somewhere between II. and III. the ADX(13/14) usually starts rising. From what
I've seen, a rising ADX at any level generally means business:
ADX(13) > Ref(ADX(13),-1)

V. Very strong trend: (this is where Linda Bradford's "Holy Grail" and such kick in)
ADX(13) > Ref(ADX(13) and
ADX(13) > 30

Almost forgot . . . very little direction (but don't fall asleep at the wheel):
ADX(13) < say, 12-15 and has been bumbling along down there for a while (hard to
quantify for me to date)

from Philip pschmi02@sprynet.com


Submitted by warrah@comcen.com.au

Weakness in a strong trend


In an up trend, three or four successive lower CLOSES and the EMA(21) is rising.

SimpleX LONG:

C <= Ref(C,-1) AND


Ref(C, -1) <= Ref(C, -2) AND
Ref(C, -2) <= Ref(C, -3) AND
Mov(C, 21, E) > Ref(Mov(C, 21, E), -1)
OR
C <= Ref(C,-1) AND
Ref(C, -1) <= Ref(C, -2) AND
Ref(C, -2) <= Ref(C, -3) AND
Ref(C, -3) <= Ref(C, -4) AND
Mov(C, 21, E) > Ref(Mov(C, 21, E), -1)

SimpleX SHORT:

233
C >= Ref(C,-1) AND

Ref(C, -1) >= Ref(C, -2) AND


Ref(C, -2) >= Ref(C, -3) AND
Mov(C, 21, E) < Ref(Mov(C, 21, E), -1)
OR
C >= Ref(C,-1) AND
Ref(C, -1) >= Ref(C, -2) AND
Ref(C, -2) >= Ref(C, -3) AND
Ref(C, -3) >= Ref(C, -4) AND
Mov(C, 21, E) < Ref(Mov(C, 21, E), -1)

Rig this up with an OB/OS oscillator and you've got an entry that is, well, at least
worth considering.

Philip pschmi02@sprynet.com
Submitted by warrah@comcen.com.au

Double inside day


{For today is an inside day}
H < Ref(H,-1) and
L > Ref(L,-1) and
{For yesterday was an inside day}
Ref(H,-1) < Ref(H,-2) and
Ref(L,-1) > Ref(L,-2)
Submitted by warrah@comcen.com.au
Micks breakout exploration
This is a MetaStock formula that I have had good success with. Copy and paste this
into the Explorer filter.
C>Ref(C,-1) AND C>Ref(C,-2) AND C>Ref(C,-3) AND C>Ref(C,-4) AND
Ref(C,-1)<=Ref(C,-2) AND
Ref(C,-1)<=Ref(C,-3) AND
Ref(C,-1)<=Ref(C,-4) AND
Ref(C,-2)<=Ref(C,-3) AND
ald and we thank him for his contributions. Formula writer Steve Karnish and Henry

Kaczmarczyk can also be contacted for additional information..


gup60.htmgup60.htm

gup78.htmgup78.htm

gup79.htmgup79.htm

gup80.htmgup80.htm

gup91.htmgup91.htm
gup96.htmgup96.htm

234
gup97.htmgup97.htm

gup103.htmgup103.htm

gup121.htmgup121.htm

gup128.htmgup128.htm

gup131.htmgup131.htm

gup142.htmgup142.htm

gup152.htmgup152.htm

gup153.htmgup153.htm

gup154.htmgup154.htm

gup77.htmgup77.htm

index.htmlindex.html
gup.23gup.23
gup65.htmgup65.htm
http://www.stockcentral.com.au/forum/http://www.stockcentral.com.au/forum/
gup64.htmgup64.htm
gup9.htmgup9.htm
gup59.htmgup59.htm
gup35.htmgup35.htm
asia1.htmasia1.htm
gup21.htmgup21.htm

235
Display notes
Columns are very wide so that each column can be copied and pasted directly into a
Metastock exploration.
A brief description of the indicator follows the name.
If you have Metastock Exploration formulas you would like to share, please email
them to 100035.406@compuserve.com We will include the name of the person who
submitted the formula unless you instruct us otherwise. These are only a starter list.
Feel free to add to them.

We welcome your feedback, comments about the site and news of new web sites.
Ask about reciprocal links.
We answer your email usually within 1 working day. Haven't got a reply?

Limited space is available on this site for your advertising message. Contact us
for details. 100035.406@compuserve.com

This site and the original material contained in it is copyright., Guppytraders.com Pty
Ltd ACN 089 941 560 1996,1997, 1998, 1999©

FORMULAS FROM SITE VISITORS

Ref(C,-2)<=Ref(C,-4) AND
Ref(C,-3)<=Ref(C,-4)

This formula will pick up all stocks that have closed up either the same as the
previous day or below the previous day for 3 days, then on the 4th day closes up
higher than the previous 3 days close. The reason that I specified that the first 3 days
close was the same as or less than the previous days close was that it would pick up
all stock in an up trend if it was just the 4th day closing higher than the 3 previous you
would get hundreds of returns on the search. It will pick up stock that was in a trading
range or consolidating, then breaking out of the range. The reason that I had the 4th
day higher than the 3 previous was because it would otherwise pick stock in a
downtrend with no significant increase in the close on day 4. Once I have a short list,
I check it with Daryl's 3 day countback line and sometimes run a 10/30 moving
average. If the stock breaches the previous day's close on the open, I will enter the
trade and put a trailing stop loss into play.

regards mick (wintom)


Displace indicator forward
To displace an indicator forward, you use Ref(myInd,-p). The median and typical
prices are built-in functions -- MP() is (H+L)/2 and typ() is (H+L+C)/3.

For MP, use

Period:= Input("What Period",1,250,10);


Disp:= Input("Forward Displacement",0,250,10);

236
EMA1:= Mov(MP(),Period,E);
EMA2:= Mov(EMA1,Period,E);
Difference:= EMA1 - EMA2;
ZeroLagEMA:= EMA1 + Difference;
Ref(ZeroLagEMA,-Disp)

from Bob Jagow

Gann hi-lo
colA
BUY
BarsSince(C< Fml("GANN-HiLo"))

colB
SELL
BarsSince(C> Fml("GANN-HiLo"))

filter
colA=1 OR colB=1

from Mike Arnoldi

Bollinger bank hook up and hook down


I use the following indicators to show the price reversal of Bollinger Band
penetration:

Name: Upper BB Hookdown


Formula:

UpperBB:= Mov(C,20,S) +(2*(Std(C,20)));


C < UpperBB AND Ref(C,-1) > Ref(UpperBB,-1);

Name: Lower BB Hookup


Formula:

LowerBB:= Mov(C,20,S) -(2*(Std(C,20)));


C > LowerBB AND Ref(C,-1) < Ref(LowerBB,-1);

from Jim Barone

MetaStock %Bands revised

I found a problem with the %Bands formulas posted yesterday. No matter what
optional parameters are entered for EMA length or % bandwidth, the
Expert appears to read only the default values. As a result, when using other than
default parameters, the coloured dots appear in inappropriate

237
places. If the coloured dots are considered unnecessary the Expert can simply be
detached.

Alternatively, below is a hard-coded version. There is no screen to enter optional


parameters. Instead, plot the %Bands formula,then right-click on one of the bands,
select '%Bands Properties', then the 'Formula' tab, and change the parameters in the
first two lines of the %Bands formula; click 'OK'. Or make the change in the Formula
Editor. The values need to be entered only once, in the %Bands formula; the
%BandsCount formula and the Expert will take their values from that. For regular
use, get the display to your liking, then create a template.

{NAME: %Bands}

Pds:= 21; {ENTER EMA LENGTH}

Pct:= 2.5; {ENTER PERCENT BANDWIDTH}

MA:= Mov(C,Pds,E);
TBnd:= MA*(1+Pct/100);
LBnd:= MA*(1-Pct/100);
MA; TBnd; LBnd;

{NAME: %BandsCount}

{USE WITH %BANDS FORMULA}

TBnd:= FmlVar("%Bands","TBND");
IUp:= (H > TBnd) * Ref((H <= TBnd),-1);
CntUp:= IUp + BarsSince(IUp=1) * (H > TBnd);

LBnd:= FmlVar("%Bands","LBND");
IDn:= (L < LBnd) * Ref((L >= LBnd),-1);
CntDn:= IDn + BarsSince(IDn=1) * (L < LBnd);
CntUp; -CntDn;

EXPERT

{Name: %Bands}

Symbols tab.
{NAME: %BandUp}
FmlVar("%BandsCount","CNTUP") >= 1
Graphic tab: Dot, Small, Green, Above price plot

Symbols tab.
{NAME: %BandDn}
FmlVar("%BandsCount","CNTDN") >= 1
Graphic tab: Dot, Small, Magenta, Below price plot

238
{from HHP}
Mark Brown Band2 Study

{Name: %Bands}
Pds:= Input("EMA Periods?",1,1000,21);
Pct:= Input("Percentage Bands?",0.1,10,5);
MA:= Mov(C,Pds,E);
TBnd:= MA*(1+Pct/100);
LBnd:= MA*(1-Pct/100);
MA;TBnd;LBnd;

{Name: %BandsCount}
Pds:= Input("EMA Periods?",1,1000,21);
Pct:= Input("Percentage Bands?",0.1,10,5);
MA:= Mov(C,Pds,E);
TBnd:= MA*(1+Pct/100);
LBnd:= MA*(1-Pct/100);

IUp:= (H > TBnd) * Ref((H <= TBnd),-1);


CntUp:= IUp + BarsSince(IUp=1) * (H > TBnd);

IDn:= (L < LBnd) * Ref((L >= LBnd),-1);


CntDn:= IDn + BarsSince(IDn=1) * (L < LBnd);
CntUp; -CntDn;

EXPERT
{Name: %Bands}

Symbols tab.
{Name: %BandUp}
FmlVar("% BandsCount","CNTUP") >= 1
{Graphic: Dot, Small, Green, Above price plot}

Symbols tab.
{Name: %BandDn}
FmlVar("% BandsCount","CNTDN") >= 1
{Graphic: Dot, Small, Magenta, Below price plot}

{created by HHP from a Mark Brown system}

Modified 50 Day Moving Average

N:=50;
TN:=Mov(C,N,S);
sOneA:=((n-1)/2)*C+
((n-3)/2)*Ref(C,-1)+
((n-5)/2)*Ref(C,-2)+
((n-7)/2)*Ref(C,-3)+

239
((n-9)/2)*Ref(C,-4)+
((n-11)/2)*Ref(C,-5)+
((n-13)/2)*Ref(C,-6)+
((n-15)/2)*Ref(C,-7)+
((n-17)/2)*Ref(C,-8)+
((n-19)/2)*Ref(C,-9);
sOneB:=((n-21)/2)*Ref(C,-10)+
((n-23)/2)*Ref(C,-11)+
((n-25)/2)*Ref(C,-12)+
((n-27)/2)*Ref(C,-13)+
((n-29)/2)*Ref(C,-14)+
((n-31)/2)*Ref(C,-15)+
((n-33)/2)*Ref(C,-16)+
((n-35)/2)*Ref(C,-17)+
((n-37)/2)*Ref(C,-18)+
((n-39)/2)*Ref(C,-19);
sOneC:=((n-41)/2)*Ref(C,-20)+
((n-43)/2)*Ref(C,-21)+
((n-45)/2)*Ref(C,-22)+
((n-47)/2)*Ref(C,-23)+
((n-49)/2)*Ref(C,-24)+
((n-51)/2)*Ref(C,-25)+
((n-53)/2)*Ref(C,-26)+
((n-55)/2)*Ref(C,-27)+
((n-57)/2)*Ref(C,-28)+
((n-59)/2)*Ref(C,-29);
sOneD:=((n-61)/2)*Ref(C,-30)+
((n-63)/2)*Ref(C,-31)+
((n-65)/2)*Ref(C,-32)+
((n-67)/2)*Ref(C,-33)+
((n-69)/2)*Ref(C,-34)+
((n-71)/2)*Ref(C,-35)+
((n-73)/2)*Ref(C,-36)+
((n-75)/2)*Ref(C,-37)+
((n-77)/2)*Ref(C,-38)+
((n-79)/2)*Ref(C,-39);
sOneE:=((n-81)/2)*Ref(C,-40)+
((n-83)/2)*Ref(C,-41)+
((n-85)/2)*Ref(C,-42)+
((n-87)/2)*Ref(C,-43)+
((n-89)/2)*Ref(C,-44)+
((n-91)/2)*Ref(C,-45)+
((n-93)/2)*Ref(C,-46)+
((n-95)/2)*Ref(C,-47)+
((n-97)/2)*Ref(C,-48)+
((n-99)/2)*Ref(C,-49);
sOne:=sOneA+sOneB+sOneC+sOneD+sOneE;
yTwo:=TN+(6*sOne)/((N+1)*N);
yTwo

240
from Ton Maas
ms-irb@planet.nl

ECO - R Krauz
The Robert Krauz article I read described the ECO as "a double smoothed ratio of the
difference between the close(C) and open(O) of each bar, and the difference between
the high(H) and low(L) prices for each bar" originally created by William Blau.

FWI my interpretation is:

{ECO[Ergodic Candlestick Oscillator]}


(MOV(MOV(C-O,5,E))26,E)/MOV(MOV(H-L,5,E))26,E))*100

J. Seed

Chandelier Exit 2
Here is the Fast Chandelier Exit in full as supplied to me. It is part of an exit strategy
which you can adjust to your own trading style and comfort levels. from Ian
Burgoyne

HHVDays:=Input("Days Since Trade Opened",1,300,1);

ATRDays:=Input("ATR Days",1,30,10);

ATRHighMult:=Input("ATR Multiplier From High",1,5,3.0);

ATRCloseMult:=Input("ATR Multiplier From Close",1,5,2.5);

HHVStop:= HHV(H,HHVDays) - ATRHighMult*ATR(ATRDays);

HighStop:= H - ATRHighMult*ATR(ATRDays);

CloseStop:= C - ATRCloseMult*ATR(ATRDays);

TodaysCalc:= If(HighStop > CloseStop, HighStop, CloseStop);

TodaysStop:= If(L <= PREV, TodaysCalc, If(HHVStop < PREV, PREV,


If(HHVStop >
C,PREV,HHVStop)));
HHVDays:=Input("Days Since Trade Opened",1,300,1);
ATRDays:=Input("ATR Days",1,30,10);
ATRHighMult:=Input("ATR Multiplier From High",1,5,3.0);
ATRCloseMult:=Input("ATR Multiplier From Close",1,5,2.5);
HHVStop:= HHV(H,HHVDays) - ATRHighMult*ATR(ATRDays);
HighStop:= H - ATRHighMult*ATR(ATRDays);
CloseStop:= C - ATRCloseMult*ATR(ATRDays);

241
TodaysCalc:= If(HighStop > CloseStop, HighStop, CloseStop);
TodaysStop:= If(L <= PREV, TodaysCalc, If(HHVStop < PREV, PREV,
If(HHVStop >C,PREV,HHVStop)));
TodaysStop

[from Ian Burgoyne}


FRACTAL UP AND FRACTAL DOWN EXPERT
The formula for Up Fractal is:
(If( HIGH > Ref( HIGH , -1 ), 1 ,0 ) AND If( HIGH > Ref( HIGH , -2 ),1 ,0 )
AND
If( HIGH > Ref( HIGH , +1 ), 1 ,0 ) AND If(HIGH>Ref( HIGH , +2 ), 1 ,0 ))
The formula for Down Fractal is:
(If( LOW < Ref( LOW , -1 ), 1 ,0 ) AND If( LOW < Ref( LOW , -2 ), 1 ,0) AND
If( LOW < Ref( LOW , +1 ), 1 ,0 )AND If( LOW < Ref( LOW , +2 ), 1 ,0 ))
Put the formulas in a new Expert with up arrows and down arrows in graphics with
appropriate colors. Hope this will be of help.
Manoj P Abraham
FRACTAL UP AND FRACTAL DOWN INDICATOR
Manoj Abraham manopab@hotmail.com
That formula was for the MetaStock Expert. Create a new Expert and put the same in
the symbols section and apply it. It will highlight the points where these occur. If you
want to plot the same as lines, check this out. Use the Indicator Builder to create these
two indicators.
Fractal Up
ValueWhen(1,(( HIGH > Ref( HIGH , -1 ) ) AND ( HIGH > Ref( HIGH , -2 ) ) AND
( HIGH > Ref( HIGH , +1 ) ) AND ( HIGH > Ref( HIGH , +2
))),C)
Fractal Down
ValueWhen(1,((( LOW < Ref( LOW , -1 )) AND ( LOW < Ref( LOW , -2 )) AND (
LOW < Ref( LOW , +1 ))AND ( LOW < Ref( LOW , +2 ) ))),C)
I use the fractals (we call them minor tops and minor bottoms) to add to my existing
positions. Hope this helps
Manoj P. Abraham
UP AND DOWN FRACTAL FORMULA CORRECTION
The formula for Up Fractal is:
If( HIGH > Ref( HIGH, -1 ), 1 ,0 ) AND
If( HIGH > Ref( HIGH, -2 ), 1 ,0 ) AND
If( HIGH > Ref( HIGH, +1 ), 1 ,0 ) AND
If( HIGH > Ref( HIGH, +2 ), 1 ,0 )
The formula for Down Fractal is:
If( LOW < Ref( LOW , -1 ), 1 ,0 ) AND
If( LOW < Ref( LOW , -2 ), 1 ,0) AND
If( LOW < Ref( LOW , +1 ), 1 ,0 ) AND
If( LOW < Ref( LOW , +2 ), 1 ,0 )
Put the formulas in a new Expert, in the Trends section, with up arrows and down
arrows in graphics with appropriate colours.
Hope this will be of help.
Manoj P Abraham

242
LINEAR REGRESSION TRADING SYSTEM
Here's a system that works. Its no Holy Grail but with a little common sense you'd be
hard pressed losing money with it. Steve posted it a while back (his "lumber.gif") so I
can hardly take credit for the idea, but I think the system is so profitable that I felt I
really ought to champion it a bit. I would characterise it as being a fairly aggressive
short term system, so it's not everyone's cup of tea.
I have added a stochastic crossover to its exit which gets it out just that little bit earlier
sometimes. I find that to get the best signals there is no point in optimising over too
long a time frame (yea, I know I'm going to get flamed -- heretic, unbeliever) so I pick
a period back where the security doesn't change character too much and re-optimise if
something dramatic happens.
Another trick is to initially optimise coarsely over a very wide range and then select
intermediate results that appear to be heading for the sort of trades that you'd like to
see (not always the most profitable). Often there are many profit peaks and if you
initially optimise over too small a range you won't see the best version for that
particular security.
I also attach the optimised formula as a MetaStock Expert to securities that I follow.
The Buy signal is uncanny and the first few times you really wonder about your
sanity.
{Enter Long}
Cross(opt2,ForecastOsc(O,opt1))
{Close Long}
Cross(ForecastOsc(O,opt1),opt3) OR
Cross(Mov(Stoch(opt4,3),opt5,S),Stoch(opt4,3))
Jeff Ledermann j.ledermann@uq.net.au

ADX RISING EXPOLORATION

For ADX > 25 and rising, you could do something like this in MS Explorer:
Column A: ADX(21)
Filter: ADX(21)>25 AND
ADX(21)>Ref(ADX(21),-1) AND
Ref(ADX(21),-1)>Ref(ADX(21),-2) AND
Ref(ADX(21),-2)>Ref(ADX(21),-3)
For ADX starting to move higher, you could try:
Column A: ADX(21)
Column B: Ref(ADX(21),-1)
Filter: ADX(21)>ADXR(21) AND Ref(ADX(21),-1)<=Ref(ADXR(21),-1

SWING TRADING EXPERT

Inside(), outside(), rally(), reaction(), reactionwithvol() and rallywithvol() are all


FUNCTIONS and described as such in the manual. These are not indicators, but can
be used in writing an indicator. If you want to see rallywithvol() as an indicator, hit

243
your formula button and call your new indicator rallywithvol. Then in the formula
window, click on FUNCTIONS, highlight rallywithvol() and paste it in. Voila, you
now have an indicator that reflects the rallywithvol() function. If you want to create a
short term swing type trading system with these functions getting insights to their use
which can be had by reading the description of these functions in the manual, create
an expert and type the following:
(RallyWithVol() OR Rally()) AND Ref(Inside() OR Outside(),-1)
This is for the long side. Looking for a fast point or two in the next few trading
sessions. Entry is just above the signal bar. Use a tight stop. If entry point was not hit,
there is no trade. This is for "Hit and Run" style trading.
from Steve Denk
REACTION FUNCTIONS
I can help with explanations of the Reaction() function and other associated functions
in the formula language. The functionality exist in the formula language ONLY and
are not implemented as standard, built-in indicators. In order to access their
capabilities, you must write a custom indicator or other formula-based calculation that
calls the appropriate function. These functions are used mainly for a type of pattern
similar to the functions used for candlestick patterns. The candlestick pattern
functionality can also only be accessed through formula functions and not as standard,
built-in indicators. Specifically, the following functions are related to the Reaction()
function:
Reaction()
ReactionWithVol()
Rally()
RallyWithVol()
Inside()
Outside()
The user's manual attempts to describe the functionality of these functions, but we
recently identified the fact that the user's manual did not correctly define how they
work. A correct explanation for these functions follows:
Reaction() : Identifies a "reaction day". A reaction day occurs if the current bar's high
is less than or equal to the previous rally or reaction day's high AND the current bar's
low is less than the previous rally or reaction day's low.
ReactionWithVol() : Identifies a "reaction with volume day". This occurs if the
current bar is identified as a reaction day AND the volume for the current bar is
greater than the volume for the previous rally or reaction day.
Rally() : Identifies a "rally day". A rally day occurs if the current bar's high is greater
than the previous rally or reaction day's high AND the current bar's low is greater than
or equal to the previous rally or reaction day's low.
RallyWithVol() : Identifies a "rally with volume day". This occurs if the current bar is
identified as a rally day AND the volume for the current bar is greater than the
volume for the previous rally or reaction day.
Inside() : Identifies an "inside day". This occurs if the current bar's high is less than or
equal to the high for the previous rally or reaction day AND the current bar's low is
greater than or equal to the previous rally or reaction day's low.
Outside() : Identifies an "outside day". This occurs if the current bar's high is greater
than the high for the previous rally or reaction day AND the current bar's low is less
than the previous rally or reaction day's low.
Ken Hunt
SUSTAINED SWING EXPLORATION

244
{Place in MetaStock Explorer filter section. Recommended to predict sustained
swings, contributed by from Rajat K. Bose.}
(ADX(14) < LLV(PDI(14),25) ) AND (ADX(14) < LLV(MDI(14), 25))
CCT LinReg OSC
{CCT LinRegOsc:}
(LinearReg(C,13)/Ref(LinearReg(C,13),-13))-1
{from Steve Karnish, Cedar Creek Trading (CCT)}
DOJI ALERT
I want to signal when a Doji occurs following a four-day consecutive increasing
CLOSE. I would like this to be an ALERT, signalling if this completed pattern has
occurred within the last five days.
from Barry Kales
ANSWER
Doji() AND
Alert((Ref(C,-1) > Ref(C,-2) > Ref(C,-3) > Ref(C,-4)),5)
from Richard Estes
DMI exploration version 2
QUESTION
I want to do a MetaStock Exploration with the Directional Movement Index. I want to
scan for the crossing of the two, i.e., yesterday +DX is less than -DX; today +DX is
greater than -DX; and visa versa.
from Dan
ANSWER
Although the names in the MetaStock quicklist drop down box are + or - DI, you will
need to use PDI or MDI in your formulas. That seems to be causing your problem.
PDI=Plus Directional Movement Index and MDI=Minus Directional Movement
Index. Instead, use the following:
DIRECT:=PDI(14)>MDI(14);
DIRECT AND Ref(DIRECT,-1)=0;
from Dave Nadeau

DMI EXPLORATION VERSION 3

QUESTION:
I want to do an exploration with Directional Movement Index. I want to scan for the
crossing of the two, i.e., yesterday +DX is less than -DX, today +DX is greater than -
DX and visa versa.
from Dan
ANSWER:
+DX(14) > -DX(14)
AND Ref(+DX(14),-1) < Ref(-DX(14),-1)
from Peter Gialames
EXCEL CONFIDENCE % INDICATOR
EXCEL CONFIDENCE % FOR METASTOCK
Simple Interpretation:
Excel Confidence % should oscillate between 0 and 100, usually at the extreme ends
of the scale. A value of 0 indicates no confidence in the market going up, whilst 100

245
indicates perfect confidence in the market going up. Although this obviously isn't the
holy grail of indicators, it does offer some insight into what the market is thinking and
how one can measure investor sentiment. You might like to add a slower version of
this (just increase the 3 day and 5 day calculations to something you believe to be
appropriate - try 7 & 15) and trade the crossovers, as with stochastics. You can also
just trade the values ie 90 or higher, buy, 10 or lower, sell.
Metastock code for Excel Confidence %:
(Sum(
Mov(C * (2.5/ Sqrt(50 * V)),10,S)-
LLV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5), 3 ) /
Sum(
HHV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5) -
LLV(Mov(C * (2.5/ Sqrt(50 * V)),10,S),5), 3) ) * 100
FRONT WEIGHTED MOVING AVERAGE
Simple Interpretation:
Front Weighted 36 Day Moving Average is similar to all other moving averages. The
interpretation is just as with all others, the trend is up when prices are above the
moving average and the trend is down when prices are below the moving averages.
This particular variation attempts to weight the data at the front more than that at the
back, with a sliding scale for each trading days value.
Metastock code for Front Weighted 36 Day Moving Average:
Fml( "1FrontWeighted36BarMA1" ) +
Fml( "2FrontWeighted36BarMA2" ) +
Fml( "3FrontWeighted36BarMA3" )
Where Fml( "1FrontWeighted36BarMA1" ) =
0.01 * Ref(P,-34) +
0.01 * Ref(P,-33) +
0.01 * Ref(P,-32) +
0.01 * Ref(P,-31) +
0.01 * Ref(P,-30) +
0.01 * Ref(P,-29) +
0.01 * Ref(P,-28) +
0.01 * Ref(P,-27) +
0.01 * Ref(P,-26) +
0.02 * Ref(P,-25) +
0.02 * Ref(P,-24) +
0.02 * Ref(P,-23) +
0.02 * Ref(P,-22) +
0.02 * Ref(P,-21) +
0.02 * Ref(P,-20) +
0.02 * Ref(P,-19) +
0.02 * Ref(P,-18)
Where Fml( "2FrontWeighted36BarMA2" ) =
0.03 * Ref(P,-17) +
0.031 * Ref(P,-16) +
0.031 * Ref(P,-15) +
0.031 * Ref(P,-14) +
0.031 * Ref(P,-13) +
0.031 * Ref(P,-12) +
0.031 * Ref(P,-11) +

246
0.031 * Ref(P,-10) +
0.031 * Ref(P,-9) +
0.031 * Ref(P,-8) +
0.006 * Ref(P,-7) +
0.006 * Ref(P,-6) +
0.07 * Ref(P,-5) +
0.07 * Ref(P,-4) +
0.07 * Ref(P,-3) +
0.07 * Ref(P,-2)
Where Fml( "3FrontWeighted36BarMA3" ) =
0.07 * Ref(P,-1) +
0.079 * P
SWING CHART
SWING CHART FOR METASTOCK
Among the single-handful of tech analysis indicators I've come to value in seeking out
potentially profitable trades is the good old swing chart. This is not present in the
standard MetaStock 6.5 armoury (at least my edition of it)but Equis derived the
following formula to me some time ago for the daily swing -
If( High > Ref(High,-1) AND Low > Ref(Low,-1), High, If( High <
Ref(High,-1) AND Low < Ref(Low,-1), Low, PREV))
Simple really! It certainly doesn't show up as a nice rectangular pattern, but you get
used to reading it just as fluently for just as correct interpretation. This formula is
easily adapted for any other time period by using Highest High Value and such-like
functions instead of the Ref function. Though with a little more tooling, it is also
readily adaptable to price swing charting rather than time swings.
How to filter out dead stocks
Here is how I do it (in the MetaStock Explorer filter):
y1:=2000;
m1:=7;
dt:=25;
test:=If(Year()<>y1,1,If(Month()<>m1,1,If(DayOfMonth()<>dt,1,0)));
Test=1
Since the Explorer does not allow the Input Function, you will need to enter the Year,
Month, and Day as the variables y1,m1,and dt, respectively.
from Michael
RSI of MACD
Q:=Input("Periods",1,1000,14);
Z:=Wilders(If(ROC(MACD(),1,$)>0,ROC(MACD(),1,$),0),LastValue(Q));
Y:=Wilders(If(ROC(MACD(),1,$)<0,Abs(ROC(MACD(),1,$)),0),LastValue(Q));
RS:=Z/Y;
100-(100/(1+RS))
from Pierre Tremblay
WRITING EXPERT COMMENTARY
Here's how to use MetaStock Expert function with the tab for commentary. For
example, I wrote this commentary that I can attach to any stock, and it will give me
the next day's projected high & low.
PRICES:
TODAY'S CLOSE WriteVal(CLOSE,2.3)
TOMMOROW's
PROJECTED HIGH

247
WriteIf(C<O, "WRITEVAL(-L+ (H+2*L+C)/2,25.2)")
WriteIf(C>O, "WRITEVAL(-L+ (2*H+L+C)/2,25.2)")
WriteIf(C=O, "WRITEVAL(-L+ (H+L+2*C)/2,25.2)")
PROJECTED LOW
WriteIf(C<O, "WRITEVAL(-H+ (H+2*L+C)/2,25.2)")
WriteIf(C>O, "WRITEVAL(-H+ (2*H+L+C)/2,25.2)")
WriteIf(C=O, "WRITEVAL(-H+ (H+L+2*C)/2,25.2)")
BOLLINGER BANDS
CLOSING PRICE:WRITEVAL(C,2.3)
BOLLINGERBAND TOP:
WRITEVAL( BBandTop(C,21,E,2),13.3)
21 DAY MOVING AVERAGE:
WRITEVAL(MOV(C,21,E),13.3)
BOLLINGERBAND BOTTOM:
WRITEVAL( BBandBOT(C,21,E,2),13.3)
FIRST RESISTANCE: WRITEVAL(-L+(2* (H+L+C)/3),1.2)
SECOND RESISTANCE: WRITEVAL(((H+L+C)/3) +((-L+(2*
(H+L+C)/3))-(-H+(2* (H+L+C)/3))),1.2)
FIRST SUPPORT:
WRITEVAL(-H+(2*(H+L+C)/3),1.2)
SECOND SUPPORT: WRITEVAL(((H+L+C)/3)
-((-L+(2* (H+L+C)/3))-(-H+(2* (H+L+C)/3))),1.2)
from Michael Arnoldi
VOLUME FLOAT INDICATOR
mp1:=Input("Days Volume Summed",1,377,30);
mf1:=Input("Float, in X million",.1,10000,10);
mf2:=mf1*1000000;
(Sum(V,mp1)/mf2)*100;
from Claud Baruch
EXAMPLE OF A TRADING SYSTEM
Enter Long if
1) today's five-day RSI is greater than yesterday's five-day RSI; and
2) today's close is below the close of five days ago; and
3) today's close is less then or equal to the average of the last five day's closes.
Long:=RSI(5)>Ref(RSI(5),-1) AND C<Ref(C,-5) AND C<=Mov(C,5,S);
Exit tomorrow at the market if:
1) today's close is higher than the average of the last five days' closes; or
2) you have been in the trade 10 days.
If(Long=1 AND (C>(Mov(C,5,S) OR (Ref(Long,-10)=1 AND Ref(Long,-
11)=0)),0,Long)
from Ton Maas
DIRECTIONAL MOVEMENT INDEX EXPLORATION
I want to do an MetaStock Exploration with Directional Movement Index (DMI) that
will scan for the crossing of the two: i.e., yesterday +DX is less than -DX, today +DX
is greater than -DX, and visa versa.
ANSWER
Ref(Cross(MDI(14) , PDI(14)),-1) AND
Cross(PDI(14) , MDI(14))
from Ton Maas
NORMALISING INDICATORS

248
In his article "Normalization", Brian Bell introduces some methods for normalizing
indicators. These methods can be easily created in MetaStock 6.52 or higher.
Select Indicator Builder from the Tools Menu, click New and enter the formula for
the desired method.
Name: Simple Moving Average Oscillator
OscP(4,8,S,$)
Name: Simple MA Osc norm to Std Dev
OscP(4,8,S,$)/Stdev(C,8)
Name: Simple MA Osc norm to Ave True Range
OscP(4,8,S,$)/ATR(8)
Name: Simple MA Osc norm to Historical Range
OscP(4,8,S,$)/WillR(200)
Note: To apply these methods to different indicators replace the Simple Moving
Average Oscillator portion with the desired indicator's formula.
Cheryl C. Abram, Equis International, Inc.
Custom Relative Momentum Index (RMI) Indicator for MetaStock
Q:=Input("RSI Time Periods",1,1000,14);
M:=Input("Momentum Time Periods",1,1000,5);
B:=Input("Field: 1=Close, 2=Open, 3=High, 4=Low, 5=Volume",1,5,1);
Bval:=If(B=1,C,If(B=2,O,If(B=3,H,If(B=4,L,V))));
Mom:=Bval-Ref(Bval,-M);
Z:=Wilders(If(ROC(Mom,1,$)>0,
ROC(Mom,1,$),0),LastValue(Q));
Y:=Wilders(If(ROC(Mom,1,$)<0,
Abs(ROC(Mom,1,$)),0),LastValue(Q));
RMS:=Z/Y;
RMIcust:=100-(100/(1+RMS));
Mov(RMIcust,M,S)
from Ton Maas
RSI OF THE MACD
In the indicator builder, you can create RSI of MACD (with MS 6.5 and later) :
Q:=Input("Periods",1,1000,14);
Z:=Wilders(If(ROC(MACD(),1,$)>0,ROC(MACD(),1,$),0),LastValue(Q));
Y:=Wilders(If(ROC(MACD(),1,$)<0,Abs(ROC(MACD(),1,$)),0),LastValue(Q));
RS:=Z/Y;
100-(100/(1+RS))
From Custom Relative Strength Index (RSI) from Equis site ...
http://www.equis.com/customer/support/formulas/cf00098.html
...I just put MACD in the formula.
I hope this helps...
Pierre Tremblay
How can we calculate the RSI of MACD?
Warmest regards,
Alex Spiroglou

VOLATILITY BREAKOUT

Create an indicator called 'System - Volatility Breakout'.

249
Then copy this crude code in:
*************************************************
{Volatility Breakout System - returns Profit}
Commission:=21; {for Buy+Sell+Stop}
TradeAmt:=10000;
Buy:=O+((Ref(H,-1)-Ref(C,-1))*.7);
Sell:=C;
Stop:=O;
Trade:= O<Ref(C,-1) AND H>Buy AND Ref(C,-1)<Ref(C,-2) AND
Ref(C,-2)<Ref(C,-3) AND Ref(C,-3)<Ref(C,-4); {Trigger for Trade}
HitStop:= If(Trade AND Stop>=Sell,TRUE,FALSE);
{Have we hit our Stop}
TradeSize:= TradeAmt/Buy;
Profit:=If(Trade,-Commission-TradeSize*Buy,0);{Purchase}
Profit:=If(HitStop=TRUE,{then}
Profit+Stop*TradeSize,
{else} If(Trade AND HitStop=FALSE, {then}
Profit+Sell*TradeSize,0)); {Sale}
Win:=If(Profit>0,1,0);
Loss:=If(Profit<0,1,0);
Cum(Profit)
*****************************************************
The indicator charts your profit. You just have to set the first 6 variables as per your
system. The MS If structures are a pain and I'm sure there must be easier ways to do
this. This is also my first attempt to prove if it works.
If you then create an Expert Advisor with the following in the Commentary definition,
you'll get some summary statistics for the system.
*****************************************************
Volatility Breakout System
Security Name: <Name>
Security Symbol: <Symbol>
Totals: Trades writeval( Cum( FmlVar("System - Volatility
reakout","trade") ),0.0 ), Wins writeval(cum( FmlVar("System - Volatility
Breakout","WIN") ),0.0), Losses Writeval(cum( FmlVar("System - Volatility
Breakout","LOSS") ),0.0)
Percentage Wins/Losses: writeval(cum( FmlVar("System - Volatility
Breakout","WIN") )/Cum( FmlVar("System - Volatility
reakout","trade") )*100,2.0)%
Profit: $Writeval(cum( FmlVar("System - Volatility
Breakout","PROFIT") ),0.0)
Commission: $Writeval( FmlVar("System - Volatility
Breakout","COMMISSION"),0.0 )
Trade Amount: $Writeval( FmlVar("System - Volatility Breakout","TRADEAMT"),
0.0)

If you want to Highlight the Winning days in one colour and the Losing days in
another, just use 'FmlVar("System - Volatility Breakout","WIN")' as the condition for
a WIN, etc.
The above is the only way I can see to test a system in MS that specifies the entry/exit
prices. I suppose the other alternative is Excel!

250
Sean Taylor

McClellan Oscillator:

1. Create a composite security in DownLoader consisting of NYSE


Advancing Issues minus NYSE Declining Issues. Name the new
security something like "Adv-Decl Issues."
2. Open the Adv-Decl Issues chart in MetaStock.
3. Create a new inner window.
4. Create two custom indicators in MetaStock:
a) First is the McClellan Oscillator:
Mov(CLOSE,19,EXPONENTIAL) -
Mov(CLOSE,39,EXPONENTIAL)
b) Second is the McClellan Summation Index:
Cum(Mov(CLOSE,19,EXPONENTIAL) -
Mov(CLOSE,39,EXPONENTIAL) )
5. Plot the McClellan Oscillator custom indicator in the main chart
window over top of the data plot and select "Display New Scale
on Right." This will eliminate the Adv-Decl Issues' scale.
6. Select the Adv-Decl Issues data plot by clicking on it, then right
click it and select "Adv-Decl Issues Properties" and change the
bar colours to the same colour as your background to make it
invisible. The raw data is needed for indicators, but need not be
displayed.
7. Plot the McClellan Summation Index in the inner window.
8. Add whatever base lines you want.
from Glen Wallace
ATR KELTNER BANDS

Pds1:= Input("EMA Periods?",1,100,20);


Pds2:= Input("ATR Periods?",1,100,10);
Mult:= Input("ATR Multiple?",1,10,2.5);
EMA:= Mov(C, Pds1, E);
Diff:= ATR(Pds2) * Mult;
UBand:= EMA + Diff;
LBand:= EMA - Diff;
Ema; UBand; LBand;
See also TAS&C Dec. 1999 p.45, 'Keltner Channels' by Stuart Evens.
Various STOCHASTIC RSI OPTIONS
Mov((RSI(14)-LLV(RSI(14),9))/(HHV(RSI(14),9)-
(LLV(RSI(14)+.00001,6))),4,E)*100

Equis' StochRSI
- Tushar Chande
(RSI(14)-LLV(RSI(14),14))/(HHV(RSI(14),14)-LLV(RSI(14),14))*100

Bell Ringer's StochRSI14


- John A. Yurko

251
(Sum(RSI(14)-LLV(RSI(14),14),3)/Sum(HHV(RSI(14),14)-
LLV(RSI(14),14),3))*100

StochRSI oscillator
- Craig DeHaan

{configurable formula for the StochRSI oscillator to quickly find what time
periods/method you prefer to work with. CDH's List-post.
(Sun, 15 Nov 1998 "Re: Finding the Stochastic of the Relative Strength")}
mp1:=Input("RSI Periods",1,377,13);
mp2:=Input("Stochastic Periods",1,377,13);
mp3:=Input("Smoothing Periods",1,377,8);
mat:=Input("MA Type: S, E, W",1,3,2); {1=S,2=E,3=W}
If(mat=1, Mov((RSI(mp1)-LLV(RSI(mp1),mp2))/(.0000001+
HHV(RSI(mp1),mp2)-LLV(RSI(mp1),mp2)),mp3,S)*100,
If(mat=2, Mov((RSI(mp1)-LLV(RSI(mp1),mp2))/(.0000001+
HHV(RSI(mp1),mp2)-LLV(RSI(mp1),mp2)),mp3,E)*100,
If(mat=3, Mov((RSI(mp1)-LLV(RSI(mp1),mp2))/(.0000001+
HHV(RSI(mp1),mp2)-LLV(RSI(mp1),mp2)),mp3,W)*100,0)))

Stochastic Relative Strength Index

{ from www.equis.com }
rev. 01/06/97
In his book The New Technical Trader, Tushar Chande defines the Stochastic RSI as:

StochRSI = (RSI - RSIL)/(RSIH -RSIL)


where RSIL and RSIH are the lowest and highest values of the RSI over a given
period.
In his book he uses 14 periods. The MetaStockT formula for the Stochastic RSI is:
( ( RSI ( 14 ) - LLV( RSI (14 ) ,14 ) ) / ( ( HHV( RSI (14 ) ,14 ) ) - LLV(RSI (14 ),14
)))
from Ton Maas

PSYCHOLOGICAL INDEX

There was an overbought/oversold indicator described in the June 2000 Futures


Magazine called the Psychological Index. It looked sort of interesting, so I wrote the
MetaStock code for it:
{Futures Magazine, Vol.29 No.6, June 2000, P.48}
LookBack:= Input("Number of lookback periods", 2, 100, 12);
UThreshold:= Input("Upper threshold (%)", 0, 100, 75);
LThreshold:= Input("Lower threshold (%)", 0, 100, 25);
UpDay:= If(CLOSE > Ref(CLOSE,-1), 1, 0);
PsychIndex:= Sum(UpDay,LookBack) / LookBack * 100;
PsychIndex; UThreshold; LThreshold
from Glenn Wallace

Buy and Hold Indicator

252
periods:=Cum(If(C>0,1,0));
dollars:=C-ValueWhen(1,periods=1,C);
percnt:=C/ValueWhen(1,periods=1,C);
percnt; [or] dollars;
You can quickly run an exploration and look at the buy and hold on everything in
dollars or in percentage terms.
Michael

PERSISTENCY OF MONEY FLOW

Period := Input("Period",10,200,20);
Mov(If( CMF(Period ) > 0, 1, -1),Period,S)/Period;
0;
from Bob Sims

Doji alert
I want to signal when a Doji occurs following a four-day consecutive increasing
CLOSE. I would like this to be an ALERT, signaling if this completed pattern has
occurred within the last five days. from Barry Kales
Alert(Doji() AND
Ref(C,-1) > Ref(C,-2) AND
Ref(C,-2) > Ref(C,-3) AND
Ref(C,-3) > Ref(C,-4) AND
Ref(C,-4) > Ref(C,-5),5)
from CatLady

Sine wave
This is a 28 period sine wave. The "flaw" is that it starts from the first period loaded
in the chart rather than an absolute date. Change the -12 to shift the wave right or left.
Ref(Sin( Cum(360/28) ), -12)
There's also MetaStock's built-in cycle lines drawing tool.
from CatLady
Displaced moving average system test
Here's an example of how to specify displaced moving average in the system tester . .
..
Buy:
Cross(C,Ref(Mov(C,50,e),-15)) {uses 50ema displaced by 15 days}
Sell:
Cross(Ref(Mov(C,50,e),-15),C)
from Paul Beattie

VOLATILITY EXPLORATION

ATR(20) / MOV(Close,20,Simple)
from Glen Wallace

253
RELATIVE VOLATILITY INDEX

Taken from Stocks & Commodities, V. 11:6 (253-256): The Relative Volatility
Index by Donald Dorsey
"The RVI is simply the relative strength index (RSI) with the standard
deviation over the past 10 days used in place of daily price change. Because
most indicators use price change for their calculations, we need a confirming
indicator that uses a different measurement to interpret market strength. The
RVI measures the direction of volatility on a scale of zero to 100. Readings
above 50 indicate that the volatility as measured by the 10-day standard
deviation of the closing prices is more to the upside. Readings below 50
indicate that the direction of volatility is to the downside. The initial testing
indicates that the RVI can be used wherever you might use the RSI and in the
same way, but the specific purpose of this study is to measure the RVI's
performance as a confirming indicator."
The RVI was designed to measure the direction of volatility. It calculates price
strength by measuring volatility rather than price change.
All of the following formulas are required:
@RVI Down
((PREV*13)+If(ROC(C,1,%)<0,Stdev(C,10),0))/14
@RVI Up
((PREV*13)+If(ROC(C,1,%)>0,Stdev(C,10),0))/14
@RVI
(100*Fml("@RVI Up"))/(Fml("@RVI Up")+Fml("@RVI Down"))

SMOOTHED ADAPATIVE STOCHASTIC OSCILLATOR

n:=Input("**Volatility** lookback length",1,50,20);


x:=Input("%K smoothing (exponential smoothing)",1,50,3);
y:=Input("%D smoothing (exponential smoothing)",1,50,3);
lenmax:=28;
lenmin:=7;
v1:=Stdev(C,n);
v2:=HHV(v1,n);
v3:=LLV(v1,n);
v4:=((v1-v3)/(v2-v3));
currlen:=(Int(lenmin+(lenmax-lenmin)*(1-v4)));
hh:=HHV(H,LastValue(currlen));
ll:=LLV(L,LastValue(currlen));
RawStochK:=((C-ll)/(hh-ll))*100;
SmoothedStochK:=Mov(RawStochK,x,E);
StochD:=Mov(SmoothedStochK,y,E);
20;
80;
StochD;

254
SmoothedStochK;
from iamken

GUPPY MULTIPLE MOVING AVERAGE EXPLORATION for Metatstock V7.


Exploration notes This uses the results of 6 custom indicators HINT When
constructing this exploration use the PASTE FUNCTIONS button to transfer the
exact formula name to the exploration.
Col A: close CLOSE
Col B: Ref(C,-1)
Col C: Ref(C,-2)
Col D: Fml( "MMA 3/30") + Fml( "MMA 5/35") + Fml( "MMA
8/40") + Fml( "MMA 10/45") + Fml( "MMA 12/50") +
Fml( "MMA 15/60")
Col E: Ref(Fml( "MMA 3/30") + Fml( "MMA 5/35") + Fml(
"MMA 8/40") + Fml( "MMA 10/45")+ Fml( "MMA
12/50") + Fml( "MMA 15/60") ,-1)
Filter When(colD,>,0) AND When(colE,<=,0)
CUSTOM MMA INDICATORS

Must be installed using the Indicator builder before Guppy Multiple Moving Average
Exploration can be run.
MMA 10/45
If(OscP(10,45,E,%)>0,+1,-1)
MMA 12/50
If(OscP(12,50,E,%)>0,+1,-1)
MMA 15/60
If(OscP(15,60,E,%)>0,+1,-1)
MMA 3/30
If(OscP(3,30,E,%)>0,+1,-1)
MMA 5/35
If(OscP(5,35,E,%)>0,+1,-1)
MMA 8/40
If(OscP(8,40,E,%)>0,+1,-1)

Finding rising moving averages

You just want to ask for an MA higher than yesterday, or higher than last week. So
e.g., "mov(c,20,s)>ref(mov(c,20,s),-1)" or
"mov(c,20,s)>ref(mov(c,20,s),-7)"

Malcolm Scott

Using the call function


Create a few indicators and add them to your formula by calling on them via the
formula call function:

Example: Create a few new indicators, e.g., n=1,2,3, etc.

Name: MyIndicator-n

255
Formula: Mov(c,10,s)

Now use the formula call function, e.g., create yet another indicator:

Name: MyCalls
Formula: fml (" MyIndicator-n ")

Place the above line in the formula field and repeat the line as needed.

from Ton Maas

Call function explanation

"When I use the FML() function in a formula to call a Multiple Expression formula
my formula only sees one of the Lines. Why? "

The FML() function cannot call multiple values from one formula to another formula.
The FML function can only call one value from one formula to another. If FML()
calls a Multiple Expression formula it can only return the value of the Last Expression
in a Multiple Expression formula, from one formula to another.

For example the following formula creates a Customized MACD with 3 trigger lines.
When plotted it plots a total of 4 lines, exactly as expected.

Mov(C,11,E)-Mov(C,30,E);
Mov(Mov(C,11,E)-Mov(C,30,E),12,E);
Mov(Mov(C,11,E)-Mov(C,30,E),25,E);
Mov(Mov(C,11,E)-Mov(C,30,E),50,E)

In this example Mov(Mov(C,11,E)-Mov(C,30,E),50,E) is the Last Expression in this


Multiple Expression formula. An FML() call to this formula returns the value of
Mov(Mov(C,11,E)-Mov(C,30,E),50,E).

If you need to use FML() to call multiple values into another formula it is best to
break the Multiple Expression Formula into Separate formulas. Then call each
separate formula with a separate FML() call.

The following example formula uses FML() calls but would generate multiple plots
when displayed in a chart:

FML("Mov(C,11,E)-Mov(C,30,E)");
FML("Mov(Mov(C,11,E)-Mov(C,30,E),12,E)"); FML("Mov(Mov(C,11,E)-
Mov(C,30,E),25,E)");
FML("Mov(Mov(C,11,E)-Mov(C,30,E),50,E)")

You could also assign variables to each expression and then use the FMLVAR()
function to call each of the expressions.

256
For example:

Formula: Multiple

One := Mov(C,11,E)-Mov(C,30,E);
Two := Mov(Mov(C,11,E)-Mov(C,30,E),12,E);
Three := Mov(Mov(C,11,E)-Mov(C,30,E),25,E);
Four := Mov(Mov(C,11,E)-Mov(C,30,E),50,E);
One;
Two;
Three;
Four

Formula: Call

FMLVAR("Multiple","One");
FMLVAR("Multiple","Two");
FMLVAR("Multiple","Three");
FMLVAR("Multiple","Four")

Refer to the MetaStock 6.5 manual and/or on-line help for more information on using
variables and the function FMLVAR().

from Equis Support and Ton Maa

Example of use of Prev function


vPrev:=PREV;
Ndays:=If(Cum(1) < 50,Cum(1),vPrev);
Ndays2:=If(Ndays>0,Ndays,LastValue(Ndays>0));
Ndays2

{fromTon Maas}

Chandelier Exit variation


Below is a variation of the Chandelier Exit that I came up with. It doesn't solve the
original question, but I like the way it plots better. It holds
the highest value every time the stop moves up, and never moves lower unless the
stop is hit, in which case its value is reset.
from Barry Marx

Stop1:=If( PREV < L,


{then} If(( H - 3*ATR(10) ) >= PREV,
{then} ( H - 3*ATR(10) ),
{else} PREV),
{else (L <= PREV)}
( H - 3*ATR(10) ));

Stop2:=If( PREV < L,

257
{then} If(( C - 2.5*ATR(10) ) >= PREV,
{then} ( C - 2.5*ATR(10) ),
{else} PREV),
{else (L <= PREV)}
( C - 2.5*ATR(10) ));

StopVal:=If(Stop1>Stop2,Stop1,Stop2);

StopVal;

Zero lag MACD 2


Here's my MetaStock v6.2 coded version of the Zero Lag Moving Average, as
described in the April, 2000, issue of Technical Analysis of Stocks and Commodities.
I've also used it to construct a Zero Lag MACD and a Zero Lag MACD trigger signal.

Period:= Input("What Period",1,250,10);


EMA1:= Mov(CLOSE,Period,E);
EMA2:= Mov(EMA1,Period,E);
Difference:= EMA1 - EMA2;
ZeroLagEMA:= EMA1 + Difference;
ZeroLagEMA

from J. Seed

RSI of MACD
UpCl:= C * (C > Ref(C, -1));
Sum(UpCl,14);

from HHP

Three day Engulfingbear short trade


Buy again three days after the signal.

ENTER SHORT
Engulfingbear()
{Means: today there was an engulfingbear signa, so enter trade.}

EXIT SHORT
Ref(Engulfingbear, -3)
{Means: as of the current day, there was an EngulfingBear three days previous, so
exit the trade today.}

from Walter Lake and HHP

Buy trigger trading system

258
{Enter long}
{System Tester options are set to enter on the Close}
BuyTrigger:=(MOV(C,10,E) - MOV(C,30,E)) / MOV(C,30,E);
BuyTrigger > 0.05

{Close long}
BuyTrigger:=(MOV(C,10,E) - MOV(C,30,E)) / MOV(C,30,E);
BuyPrice:= If(PREV <= 0,
{Then did you go long today?}
If(BuyTrigger > 0.05, CLOSE, 0),
{Else did you exit today?}
If(Close >= PREV*(1+BuyTrigger), -PREV,
PREV));
BuyPrice < 0

{In this formula, BuyPrice is the close on the date BuyTrigger exceeds your
threshold. If you are in a trade and have just received a sell signal, BuyPrice is
redefined as a negative, and System Tester is told to close your long position. If you
are not currently in a trade, BuyPrice is assigned a zero value and System Tester is
told to watch for a new long entry.}

{from Glenn Wallace}

GANN-HiLo 2

HLd:=If(CLOSE>Ref(Mov(H,3,S),-1),
{then}1,
{else}If(CLOSE<Ref(Mov(L,3,S),-1),
{then}-1,
{else}0));
HLv:=ValueWhen(1,HLd<>0,HLd);
HiLo:=If(HLv=-1,
{then}Mov(H,3,S),
{else}Mov(L,3,S));
HiLo;

Gann hi lo crossover
I took the "GANN-HiLo" indicator one step further, exploring in EOD which stocks
crossed the GANN-HiLo dots.

cola buy:
Cross(C, Fml("GANN-HiLo")) AND
CLOSE > Fml("GANN-HiLo")

colb sell:
Cross(C, Fml("GANN-HiLo")) AND
CLOSE < Fml("GANN-HiLo")

259
filter:
cola=1 or colb=1

from Mike Arnoldi

SIDEWAYS CHANNELS EXPLORATION

Periodicity: Daily

Formulas

ColumnA: Top
Mov(Peak(1,H,1),45,S)-Ref(Mov(Peak(1,H,1),45,S),-45)

ColumnB: Bottom
Mov(Trough(1,L,1),45,S)-Ref(Mov(Trough(1,L,1),45,S),-45)

Filter:
ColA < 1 AND ColA > -1 AND ColB < 1 AND ColB > -1

Congestion Index

((HHV(C,80)-LLV(C,80))/LLV(C,80))*100

Consolidation breakout (upside)

If(Ref(Fml("congestion index"),-5),<,10, {and} If(Fml("congestion index"),>=,10,


{and} If(CLOSE,>,Ref(HHV(C,80),-5), {and}
If(Mov(V,5,S),>=,1.5*(Ref(Mov(V,60,S),-5)), +1,0),0),0),0)

Consolidation breakout (downside)

If(Ref(Fml("congestion index"),-5),<,10{%},{and} If(Fml("congestion


index"),>=,10{%},

{and} If(CLOSE,<,Ref(LLV(C,80),-5),{and}
If(Mov(V,5,S),>=,1.5*(Ref(Mov(V,60,S),-5)),+1,0),0),0),0)

from Richard Estes

260
STOCHASTIC AND RSI SYSTEM

Mov((RSI(8)-LLV(RSI(8),8))/(HHV(RSI(8),8)-(LLV(RSI(8),8))),5,w)*100

A formula like this works best with confirming indicators. If the MACD 13-34-89 is
above the zero line (purple line in window 2 above), it confirms and uptrend and the
indicator is usually more accurate. If the MACD 13-34-89 is below the zero line, then
a "short" indication from the StochRSI may give better results.StochRSI 13 also gives
excellent indicators- in this index it had 4 out of 5 winning signals in two year period.
The time between signals is of course longer. Check this method out on your favorite
issues.

from Andy G. andyg@megsinet.net

BPDL TREND FILTER

cum ((if ((mov((C-ref(C,-1)),21,s))>0,1,-1) * pwr(((mov((pwr(C-ref(C,-


1),2)),21,s))+1),.5)) + ((pwr(((pwr(C-ref(C,-1),2))+1),.5))) * if ((C>ref(C,-1)),1,-1))

(fml(" BPDL Trend Filter") - (ref((fml(" BPDL Trend Filter")),-21))) / ((hhv(fml("


BPDL Trend Filter"),21)) - (llv(fml("BPDL Trend Filter"),21)))

BUY -1 SELL 1

PFE Indicator:

Mov(If(C > Ref(C,-9), Sqr( Pwr( ROC(C,9,$),2) + Pwr(10,2))


/ Sum( Sqr( Pwr( ROC(C,1,$),2) +1), 9),-Sqr( Pwr(
ROC(C,9,$),2) + Pwr( 10,2)) / Sum(Sqr(Pwr(ROC(C,1,$),2)
+1),9)) * 100,5,E)

I use a 80, -80 trendline. I have stuck it in different things at different times. Right
now I have it crossing -80 with MACD 4, 35,5, crossing, RSI(9) up one day, and
selling pressure down one day.

from Stephen Zodkov


21 Day trigger
Look at these two oscillators in MSWIN, and compare them to Dahl. Put a 21 day
EMA on each, think of the 21 day ema as a trigger. See what they tell you -- Dahl is
long term, Ian is shortest term.

Raschke Oscillator = Mov(Fml( "Raschke 3-10" ),16,E)


where "Raschke 3-10" = Mov(C,3,S) - Mov(C,10,S)
Ian Oscillator = (Mov(C,4,S)-Mov(C,9,S)) + (Mov(C,9,S)-Mov(C,17,S))

from Alton Stephens

FibboGatto

261
FG1:
((c+ref(c,-1)+ref(c,-2)+ref(c,-3)+ref(c,-5)+ref(c,-8)+ref(c,-13)+ref(c,-21)+ref(c,-
34)+ref(c,-55)+ref(c,-89)+ref(c,-144))/c)*-1

{{{adding closing price only on fib days 1,2,3,5,8,13,21,34,55,89 and 144 and then
dividing by today's close}}}

FG2:
mov(((c+ref(c,-1)+ref(c,-2)+ref(c,-3)+ref(c,-5)+ref(c,-8)+ref(c,-13)+ref(c,-21)+ref(c,-
34)+ref(c,-55)+ref(c,-89)+ref(c,-144))/c)*-1,34,e)

{{{ 34 period mov avg of above indicator}}}

Look for crosses of the two indicators for positive or negatives.

Now, there are many whipsaws. I don't recommend this as a *system* at all, just as an
indicator. It really highlights some big moves but measuring it with the system test is
useless. You must use this as ONE of the tools -- not THE tool.

Regards, Jerry Gatto

Dynamic Zones
{Zamansky&Stendahl's Dynamic Zones for MS6.5 (From the TASC July1997
article). First, for the Lookback Periods plot a 9-day RSI along with StDev adjusted
rolling 70-day SMAs; e.g., as can be seen in the article's S&P500-example}

PR:=Input("Enter Periods for RSI",1,100,9);


PB:=Input("Enter Periods for BUY",1,100,70);
PS:=Input("Enter Periods for SELL",1,100,70);
UpZone:=Mov(RSI(PR),PS,S)+(1.3185 *Stdev(RSI(PR),PS));
LwZone:=Mov(RSI(PR),PB,S)-(1.3185 *Stdev(RSI(PR),PB));
UpZone;
LwZone;

Most indicators use a fixed zone for buy and sell signals. Here's a concept based on
zones that are responsive to past levels of the indicator.

One approach to active investing employs the use of oscillators to exploit tradable
market trends. This investing style follows a very simple form of logic: Enter the
market only when an oscillator has moved far above or below traditional trading
levels. However, these oscillator-driven systems lack the ability to evolve with the
market because they use fixed buy and sell zones. Traders typically use one set of buy
and sell zones for a bull market and substantially different zones for a bear market.
And therein lies the problem.

262
Once traders begin introducing their market opinions into trading equations, by
changing the zones, they negate the system's mechanical nature. The objective is to
have a system automatically define its own buy and sell zones and thereby profitably
trade in any market -- bull or bear. Dynamic zones offer a solution to the problem of
fixed buy and sell zones for any oscillator-driven system.

The algorithm for the dynamic zones is a series of steps. First, decide the value of the
lookback period t. Next, decide the value of the probability Pbuy for buy zone and
value of the probability Psell for the sell zone.

The area above and below the dynamic zones constitute the upper and lower 10%
boundaries. The zones appear to evolve with the market because they use a rolling 70-
day period of indicator values in their construction.

DAHL VARIATIONS

Dahl Volume Trend


Mov(C,55,VOL)-Ref(Mov(C,55,VOL),-15)

PVT Dahl Trend:


Mov((PVT()-Ref( PVT(),-15)),55,E)

Smoothed OBV Vol 88:


Mov((OBV()-Mov(OBV(),88,VOL)),55,E)

OBV Dahl Trend:


Mov((OBV()-Ref(OBV(),-15)),55,E)

Compare each to ordinary Dahl or some other trend indicator. Remember, I put a 21
EMA trigger on each.

from Alton Stephens

DAHL OSCILLATOR

I came up with the following to put Dahl into an oscillator format. It is the
STOCHRSI formula, replacing RSI with a 55 day Dahl. Does this reflect your
thinking on the indicator? It seems to lead changes in Dahl by a period or two, but
doesn't seem as fast as the STOCHRSI indicator. Checking a few stocks in my
database, there are very few times that it goes below zero, but it will 'peg out' at 100
for significant periods. Perhaps the 14 day smoothing is too short in relation to the 55
period primary indicator. A longer MA period seems to smooth it out significantly,
which would seem to defeat the purpose of using an oscillator.

263
Mov((mov(c,55,simp) - ref(mov(c,55,simp),-15)- LLV(mov(c,55,simp) -
ref(mov(c,55,simp),-15),14))/(HHV(mov(c,55,simp) - ref(mov(c,55,simp),-15),14)-
(LLV(mov(c,55,simp) - ref(mov(c,55,simp),-15),14))),14,E)*100

from Jim O'Donnell

FULL FORMULA FOR RSI

{The following is copied from the Formula Field of my *RSI


canonical_12_day_for_P_I indicator. Change m if you choose another # of periods n
for rsi.}

{I wrote my own "canonical" RSI(12) which coincides with MetaStock's RSI(12) if


m=2*n-1 where m is used below in Mov( ,m,E); n - a number of periods in rsi(n).
Mind that since I didn't use those particular tricks from the standard rsi(n) to shorten
the initial transitional period, this function and standard rsi(n) differ for about month
or so from the day 1. It was not that important for me, so I used this shortcut.}

100 - 100/
(1.+ If(Mov(If(P-Ref(P,-1)<0,-(P-Ref(P,-1)),0),23,E)=0,1000000,

Mov(If(P-Ref(P,-1)>0, P-Ref(P,-1), 0),23,E)


/Mov(If(P-Ref(P,-1)<0,-(P-Ref(P,-1)),0),23,E)
))
From: Vitaly Larichev vitaly@superlink.com

2 DAY HAMMER EXPLORATION

Here is an exploration that pattern traders may find useful. It tends to pick up two
patterns: a two day hammer, that is if you combined the open for day 1 and close for
day 2, the resulting bar would be a hammer, and a pattern similar to a Ross Hook, as I
understand a Ross Hook.

Ref((C-L)/(H-L),-1)<=.30 AND

((C-L)/(H-L)) >= .70 AND

Ref(ATR(1),-1) >ATR(10) AND

ATR(1) >= ATR(10)

from Styk

ATR TRAILING STOP LOSS

264
For Long:
HHV(H - 2.5*ATR(5),10)

For Short:
LLV(L + 2.5*ATR(5),10)

Furthermore, it may be beneficial to dynamically adjust the number of lookback


periods in the HHV() or the LLV() function.
Yngvi Hardarson

Sine-Weighted Moving Average

Formula:
PI:=3.1415926;
SD:=180/6;
S1:=Sin(1*180/6)*C;
S2:=Sin(2*180/6)*Ref(C,-1);
S3:=Sin(3*180/6)*Ref(C,-2);
S4:=Sin(4*180/6)*Ref(C,-3);
S5:=Sin(5*180/6)*Ref(C,-4);
Num:=S1+S2+S3+S4+S5;
Den:=Sin(SD)+Sin(2*SD)+Sin(3*SD)+Sin(4*SD)+Sin(5*SD);
Num/Den
%%%%%%%%%%%%%

WRO AND WSO INDICATORS

MetaStock Formulas -- WRO and WSO Indicators

In the May 1998 issue of STOCKS & COMMODITIES, a Traders' Tip provided
MetaStock formulas for calculating support and resistance levels and the WRO
and WSO support and resistance oscillators. The Traders' Tip was based on my
article, "Automated Support And Resistance," also in that issue. Since then,
I've received many E-mail messages from STOCKS & COMMODITIES readers
about
it.
While the method was well received, the formulas provided were a bit
confusing and could use some clarification. Further, execution was slow and
screening of large numbers of stocks was difficult. Since then, I have
developed a faster and improved method for computing these indicators.

To begin, the support levels S1 through S6 and the resistance levels R1


through R6 are separate indicators (12 in all), and each should be entered
using the custom indicator option in the indicator builder.

S1 Indicator:

265
ValueWhen(1, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S2 Indicator:
ValueWhen(2, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S3 Indicator:
ValueWhen(3, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S4 Indicator:
ValueWhen(4, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S5 Indicator:
ValueWhen(5, Ref(L,-4) = LLV(L,9), Ref(L,-4))

S6 Indicator:
ValueWhen(6, Ref(L,-4) = LLV(L,9), Ref(L,-4))

R1 Indicator:
ValueWhen(1, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R2 Indicator:
ValueWhen(2, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R3 Indicator:
ValueWhen(3, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R4 Indicator:
ValueWhen(4, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R5 Indicator:
ValueWhen(5, Ref(H,-4) = HHV(H,9), Ref(H,-4))

R6 Indicator:
ValueWhen(6, Ref(H,-4) = HHV(H,9), Ref(H,-4))

These 12 indicators should be individually plotted with the price data as


points, not lines (click on each and change the style to the one on the
bottom of the style menu). The color red is recommended for the support
levels S1 through S6 and the color blue for the resistance levels R1 through
R6. Entering these formulas and changing the style takes a bit of time, but
once done, they can be saved as a template and easily applied to another
stock.

If you are interested only in computing the WRO and WSO indicators, then
these formulas can be entered as shown here. It is not necessary to compute
S1 through S6 or R1 through R6, since the new formulas are now
self-contained. The new WRO and WSO formulas also contain max and min
functions to ensure that the change for each level is either zero or 1. This
avoids a rare but occasional error when the price change is very large over

266
a short period.

WSO Indicator:

L1:=ValueWhen(1,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L2:=ValueWhen(2,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L3:=ValueWhen(3,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L4:=ValueWhen(4,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L5:=ValueWhen(5,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L6:=ValueWhen(6,Ref(L,-4)=LLV(L,9),Ref(L,-4));
L1M:= Max(0,Min(1,Int(L1/C)));
L2M:= Max(0,Min(1,Int(L2/C)));
L3M:= Max(0,Min(1,Int(L3/C)));
L4M:= Max(0,Min(1,Int(L4/C)));
L5M:= Max(0,Min(1,Int(L5/C)));
L6M:= Max(0,Min(1,Int(L6/C)));
100*(1-(L1M+L2M+L3M+L4M+L5M+L6M)/6)

WRO INDICATOR:

L1:=ValueWhen(1,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L2:=ValueWhen(2,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L3:=ValueWhen(3,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L4:=ValueWhen(4,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L5:=ValueWhen(5,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L6:=ValueWhen(6,Ref(H,-4)=HHV(H,9),Ref(H,-4));
L1M:= Max(0,Min(1,Int(L1/C)));
L2M:= Max(0,Min(1,Int(L2/C)));
L3M:= Max(0,Min(1,Int(L3/C)));
L4M:= Max(0,Min(1,Int(L4/C)));
L5M:= Max(0,Min(1,Int(L5/C)));
L6M:= Max(0,Min(1,Int(L6/C)));
100*(1-(L1M+L2M+L3M+L4M+L5M+L6M)/6)

The WRO and WSO oscillators are generally plotted together on a separate
scale from the price plot. It is helpful to add horizontal lines at zero and
100 on this same scale. Horizontal lines can be added by clicking on the
indicator and selecting "horizontal lines" from the Indicator Properties
menu.

These formulas run much faster (by 40 times) than the earlier formulas, and
theyÕve been tested successfully with both end-of-day data and real-time
data using MetaStock Professional Version 6.51.

267
-- Mel Widner, Ph.D., 703 791-5910

%%%%%%%%%%%%%

GAP1 SYSTEM

===========
{BUY}
L>Ref(H,-1) OR
Cum(1)=LastValue(Cum(1))

{SELL}
H<Ref(L,-1) OR
Cum(1)=LastValue(Cum(1))

GAP2 SYSTEM

===========
{BUY}
N1:=5;
L>Ref(HHV(H,N1),-1) OR
Cum(1)=LastValue(Cum(1))

{SELL}
N1:=5;
H<Ref(LLV(L,N1),-1) OR
Cum(1)=LastValue(Cum(1))

Gap3 System
===========
{Enter Long}
N1:=5;
L>Ref(HHV(H,N1),-1) OR
Cum(1)=LastValue(Cum(1))

{Exit Long}
N2:=3;
C<Ref(LLV(L,N2),-1) OR
Cum(1)=LastValue(Cum(1))

{Enter Short}

268
N1:=5;
H<Ref(LLV(L,N1),-1) OR
Cum(1)=LastValue(Cum(1))

{Exit Short}
N2:=3;
C>Ref(HHV(H,N2),-1) OR
Cum(1)=LastValue(Cum(1))

{from Ton Maas}

%%%%%%%%
TSI AND TSI MOVING AVERAGE
100*(Mov(Mov(Roc(C,1,$),25,E),13,E)/Mov(Mov(Abs(Roc(c,1,$)),25,E),13,E))

Mov(Fml("TSI"),20,E)

%%%%%%%%%

RSI DIVERGENCE EXPLORATION

{A simple exploration filter formula for finding a bullish divergence


between the RSI and the price is shown below. To find a bearish divergence,
replace > with <. The differences in the trough function was found through
an optimization routine and they may not be the best values for your
application.}

Ref(RSI(14),-1)>Trough(1,RSI(14),.8)
AND
Ref(CLOSE,-1)<Trough(1,CLOSE,.2)

{from Dan in Pocatello, ID}


%%%%%%%%%
Candle - Hanging Man/Hammer & CCI Trading System

enter long:
(Fml("Candle - Hammer")=1) AND
(CCI(11)<-50)

close long:
((CCI(11)<80) AND
(Ref(CCI(11),-1)>80)) OR
((CCI(11)<-80) AND
Ref(CCI(11)>-80,-1))

enter short:
(Fml("Candle - Hanging Man'")=-1) AND

269
(CCI(11)>50)

close short:
((CCI(11)>-80) AND
(Ref(CCI(11),-1)<-80)) OR
((CCI(11)<80) AND
Ref(CCI(11)>80,-1))

%%%%%%%%%%%

STIX INDICATOR

Mov((H+L)/2,5,S)-Mov((H+L)/2,35,S)

%%%%%%%%%%%
rsi dIVERGENCE
{RSI(9) DIVERGENCE BUY:}
If(RSI(9) >= HHV(RSI(9),19) AND CLOSE <HHV(CLOSE,19), 1,0) OR
If(CLOSE <= LLV(CLOSE,19) AND RSI(9) > LLV(RSI(9),19), 1,0)

{RSI(9) DIVERGENCE SELL:}


If(CLOSE >= HHV(CLOSE,19) AND RSI(9)<HHV(RSI(9),19),1,0) OR
If(RSI(9) <= LLV(RSI(9),19) AND CLOSE > LLV(CLOSE,19),1,0)

{You can substitute any formula for the "RSI(9)"}

{from Mike Arnoldi}

%%%%%%%%%%%

DENVELOPE (RSI)

pds:=Input("Periods",2,200,14);
sd:=Input("Standard Deviations",.01,10,2);
D1:= RSI(pds);
alpha:=2/(pds+1);
mt:=alpha*D1+(1-alpha)*(If(Cum(1)<pds,D1,PREV));
ut:=alpha*mt+(1-alpha)*(If(Cum(1)<pds,D1,PREV));
dt:=((2-alpha)*mt-ut)/(1-alpha);
mt2:=alpha*Abs(D1-dt)+(1-alpha)*PREV;
ut2:=alpha*mt2+(1-alpha)*PREV;
dt2:=((2-alpha)*mt2-ut2)/(1-alpha);
but:=dt+sd*dt2;
blt:=dt-sd*dt2;
blt;

270
dt;
but;

{from Adam Hefner


VonHef@email.msn.com }
%%%%%%%%%%
HIGH LOW
Len:=Input("Periods",1,400,89);
(Mov((H - L + Abs(H - Ref(C,-1)) + Abs(L - Ref(C,-1)) ),len,E))/2

{ from Bob bjagow@jps.net }

%%%%%%%%%%%%%

CYLICAL SYSTEM

from Ton Maas ms-irb@wxs.nl

=============================================================
=
"Trading Stocks With A Cyclical System" by Jeffrey Owen Katz (TASC-Feb1999).
(Translated for MetaStock 6.5 by Ton Maas -The Netherlands - June1999).
----------------------------------------------------------------------------
(The system's original Easy Language formulas+system were derived from
theabove mentioned TASC article). My guess is that Equis (Alan McNichol) was
not in the possession of them when he wrote the Equis version of the system,
back in the Feb99 Trader's Tips section of TASC).

Cyclical System

- J O Katz

Formula:
{TASC Feb99}
thresh:= {omit whipsaw} 4;
k:= {roc comparison period} 3;
m:= {cycle period} 63;
hld:= {maximum period holding position} 10;
Value1:= {volatility}
Stdev(Mov(C,m,S)-Mov(C,m+k,S),20);
Value2:= {roc, relative comparison ratio}
Mov(C,m,S)-Mov(C,m+k,S);
tv1:= thresh*Value1;
EL:={Enter Long} Value2>tv1;
CL:={Close Long} Ref(Cross(Value2,tv1),-hld);

271
ES:={Enter Short} Value2<tv1;
CS:={Close Short} Ref(Cross(tv1,Value2),-hld);
JKcycl:=If((EL>0)=1,+10,
If((ES>0)=1,-10,0));

JKCYCL

---------------------------
MetaStock 6.5 System Tester
---------------------------
Name:
Jeffrey Owen Katz - Cyclical System
Notes:
{February 1999 - TASC-article (see also TRADERS' TIPS)}

Formulas:
{copy-repeat all that is printed below when applying for the right rule}
thresh:= {omit whipsaw} 4;
k:= {roc comparison period} 3;
m:= {cycle period} 63;
hld:= {maximum period holding position} 10;
Value1:= {volatility}
Stdev(Mov(C,m,S)-Mov(C,m+k,S),20);
Value2:= {roc, relative comparison ratio}
Mov(C,m,S)-Mov(C,m+k,S);
tv1:= thresh*Value1;

Rules:
{Enter Long} Value2>tv1
{Close Long} Ref(Cross(Value2,tv1),-hld)
{Enter Short} Value2<tv1
{Close Short} Ref(Cross(tv1,Value2),-hld)

{After entering the formulas, click OK. Then click Options. On the Testing
page, set the Trade Delay to zero, set Positions to "both", and then set any
other desired options (apart from Optimizing, which is not advisable; leave
the factory default settings). Click OK to save the changes, and then open a
chart and run the system.}

%%%%%%%%%%%%
BODY MOMENTUM
{I was reading in Perry Kaufman's latest book and he described a little
oscillator he called "Body Momentum". This simply calculates the momentum of
the closes above the opens versus the closes below the opens. The theory is
that as prices move up, closing prices will be higher than opening prices
and vice-versa for down. If this oscillator is above 70 then the whites

272
(Candle-sticks) dominate and below 30 the blacks are dominant.}

{I also added a 3 day moving average to the calculation (for smoothing).}

{Here is the code:}

Lb:=Input("Look-Back Period?",3,60,14);
B:=CLOSE - OPEN;
Bup:= Sum(B > 0, Lb);
Bdn:= Sum(B < 0, Lb);
BM:=(Bup/(Bup+Bdn))*100;
Mov(Bm,3,S)

{from Adam Hefner}


%%%%%%%%%%%%

ST OSCILLATOR

{The StTO is really nothing unique. It is basically a momentum indicator and


plots very similar to the "Chande Momentum Oscillator" with the main
difference being the "StTO" doesn't seem to swing as far as the CMO.
I am not sure how the math is calculated for the CMO, but the (basic) math
for the StTO is: (Close- Yesterday's Close) /
(H-L)}

{Here is the MetaStock code I use:}

{name: StTO}

{Short-term Trend Oscillator}

Lb:=Input("Smoothing Period?",1,60,5);
Num:=C-Ref(C,-1);
Den:=H-L;
Mn:=If(Mov(Num,Lb,S)=0,.01,Mov(Num,Lb,S));
Md:=If(Mov(Den,Lb,S)=0,.01,Mov(Den,Lb,S));
(Mn/Md)*100

{Adam Hefner}
%%%%%%%%%%%%%

CCI SPIKE TRADING SYSTEM

273
{This system uses the momentum Commodity Channel Index (CCI) indicator to
find short-term bottoms in the market. The CCI indicator is extremely
volatile and is generally difficult to use when trading the S&P 500 Index.
We, however, have turned this volatility into a trading advantage by using
the spread or gap between the CCI index and its moving average as a reversal
signal. Specifically if the gap is larger then a certain percentage and CCI
indicator crosses above its moving average we buy the market. The system
remains in the market for a short period of time, exiting the trade as the
indicators cross to the downside. As designed, this system only trades long
the market; it can however be altered to short the market. It is best used
in choppy bullish markets similar to the 1995 bull market.}

{Trading Tactics: This short-term bullish trading system exploits over


extended markets. Futures, options, and mutual fund traders should take full
advantage of this high probability trading system, either by taking outright
positions or avoiding declining markets. The code for this system can be
reversed to trade short positions. This system should be used in place of
longer-term momentum systems in strong bullish choppy type markets. This
system rarely exits at the market intermediate peak, so other exiting
signals may be used in place of our indicator crossover technique.}

{Enter long:}

Ref(CCI(13)/(Mov(CCI(13),3,S)),-1)>1.5 AND
Cross(CCI(13),(Mov(CCI(13),3,S))) AND
Ref(CCI(13),-1)<-25

{Exit long:}

Cross((Mov(CCI(13),3,S)),CCI(13)) AND
Ref(CCI(13),-1)>200

{from Craig Monroe}


%%%%%%%%%%%

LOOKBACK

Formula: X := Stdev(C, 30);


Y := Ref(X, -1);
Z := 1+((X-Y)/X);
If(Cum(1)=1, 20, Min(Max(Prev*Z, 20), 60))

Name: BuyBreak
Formula: HHV(H, LastValue(Fml("LookBack")+Prev-Prev))

Name: BuyExit
Formula: LLV(L, LastValue(Fml("LookBack")/2+Prev-Prev))

274
Name: SellBreak
Formula: LLV(L, LastValue(Fml("LookBack")+Prev-Prev))

Name: SellExit
Formula: HHV(H, LastValue(Fml("LookBack")/2+Prev-Prev))

Name: BreakWhere
Formula: TopB := Ref(Fml("BuyBreak"), -1);
LowB := Ref(Fml("SellBreak"), -1);
((O+H+L+C)/4 - LowB)*100/(TopB-LowB);

Name: DBS-System
Enter Long: H > Ref(Fml("BuyBreak"), -1)
Close Long: L < Ref(Fml("BuyExit"), -1)
Enter Short: L < Ref(Fml("SellBreak"), -1)
Close Short: H > Ref(Fml("SellExit"), -1)

This is George Pruitt's ("Futures Truth") basic system. It is also the basic
system used as the basis for Thomas Stridsman's year-long series of articles
about system development and tweaking.
%%%%%%%%%%%
STOCHASTIC MOMENTUM
SMI-Plex:=
StochMomentum(2,1,2)+StochMomentum(3,2,1)+StochMomentum(4,2,3)+StochMo
mentum
(5,3,5)+StochMomentum(8,21,13)+StochMomentum(13,25,2)

SMI13E-Plex:=
Mov(StochMomentum(2,1,2)+StochMomentum(3,2,1)+StochMomentum(4,2,3)+Stoc
hMome
ntum(5,3,5)+StochMomentum(8,21,13)+StochMomentum(13,25,2),13,E)

{from Craig DeHaan}


%%%%%%%%%%%%
BradCCI

BradCCI: From Bill S.

Plot 1: BradCCI Line 1: (((H+L+C)/3)-Mov(C,28,S))/(.015*Std(C,28))

Plot 2: BradCCI Line 2: Std(((h+l+c)/3),28)

To Line 1, you can also add trend lines, if you wish:

Plot 1:

1. BradCCI Line 1: (((H+L+C)/3)-Mov(C,28,S))/(.015*Std(C,28))

275
2. trend(100,100)
3. trend(-100,-100)
4. trend(0,0)

%%%%%%%%%%%%%%

MCCLELLAN OSCILLATOR

rev. 01/06/97
The McClellan Oscillator, developed by Sherman and Marian McClellan, is a
market breadth indicator that is based on the smoothed difference between
the number of advancing and declining issues on the New York Stock Exchange.
The McClellan Oscillator is one of the most popular breadth indicators. Buy
signals are typically generated when the McClellan Oscillator falls into the
oversold area of -70 to -100 and turns up. Sell signals are generated when
the oscillator rises into the overbought area of +70 to +100 and then turns
down.
Extensive coverage of the McClellan Oscillator is provided in their book
Patterns for Profit .

To plot the McClellan Oscillator, create a composite security in The


DownLoader™ of Advancing Issues minus Declining Issues. Open a chart of the
composite in MetaStock™ and plot this custom indicator.

Mov(CLOSE,19,EXPONENTIAL) - Mov(CLOSE,39,EXPONENTIAL)

MCCLELLAN SUMMATION INDEX

rev. 01/06/97
The McClellan Summation Index is a market breadth indicator developed by
Sherman and Marian McClellan. It is a long-term version of the McClellan
Oscillator and its interpretation is similar to that of the McClellan
Oscillator except that it is more suited to major trend reversals.

For more extensive coverage of the index refer to the book Patterns for
Profit, by Sherman and
Marian McClellan.

McClellan suggests the following rules for use with the summation Index:

Look for major bottoms when the Summation Index falls below -1300.

Look for major tops to occur when a divergence with the market occurs above
a Summation Index level of +1600.

276
The beginning of a significant bull market is indicated when the Summation
Index crosses above +1900 after moving upward more than 3600 points from its
prior low (e.g. the index moves from -1600 to +2000).

The summation index is plotted by adding the Cum function to the McCllellan
Oscillator. The formula is Cum(Mov(C,19,E) - Mov(C,39,E)).

%%%%%%%%%%%%%%%%%%%
Jack Landis' weighted stochastic (shortened to Landis)
((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16)+(S
toch(21,5)*.10))

Landis 3 week s m a
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),15,s)

landis multiple time periods


formula #1
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),15,s)
formula #2
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),10,s)
formula #3
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),5,s)
formula #4
mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,8)*.16
)+(Stoch(21,5)*.10)),2,s)

multiple slopes of landis


formula #1
slope(mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,
8)*.16)+(Stoch(21,5)*.10)),15,s),2)
formula #2
slope(mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,
8)*.16)+(Stoch(21,5)*.10)),10,s),2)
formula #3
slope(mov(((Stoch(8,3)*.05)+(Stoch(89,21)*.43)+(Stoch(55,13)*.26)+(Stoch(34,
8)*.16)+(Stoch(21,5)*.10)),5,s),2)

277
BARNES' ACCELERATION

The Barnes' Acceleration measures rate of price change as opposed to price


levels

If the Barnes' Acceleration sustains the value of -1 for many days then the
security may be ready to show strong trend or it may already be trending.
Examine the chart for prolonged values at -1. This may indicate an upcoming
stall or turnaround. The number of days needed may be different depending on
the type of issue. A utility stock may need to sustain the -1 level for 10
days whereas a highly volatile technology stock may need to sustain the -1
trend for as little as 5 days.

From the 1981 Technical Commodity Yearbook, Robert M. Barnes


formula 1: if(mov(fml("Barnes' acceleration",2) - ref(fml("Barnes'
acceleration",2),-1),20,e)>0.0001,1, if(mov(fml("Barnes' acceleration",2) -
ref(fml("Barnes'
acceleration",2),-1),20,e)<-0.0001,-1,0))
formula 2: mov((c-ref(c,-1))/ref(c,-1),daysm,e)

BARNES' ADAPTIVE FORECAST

Based on the premise that closing price may be predictable based on previous
closes

See (1981 Technical Commodity Yearbook Robert M. Barnes Van Nostrand


Reinhold 1981) for theory and applications.

formula 1: if(fml("Barnes' adaptive forecast",2)>0.05,1,if(fml("Barnes'


adaptive forecast",2)<-0.05,-1,0))
formula 2: mov(c,dayf,e) - ref(mov(c,dayf,e),-1)

BARNES' MOVING AVERAGE

See (1981 Technical Commodity Yearbook Robert M. Barnes Van Nostrand


Reinhold 1981) for theory and applications.

if (c - mov( c, dayf, e) > pf,


{ Then Action } 1,
{ Else Action } if ( mov( c, dayf, e) - c > pf, { Then } -1, { Else } 0))

278
{ Notice that comments may be placed within braces }

%%%%%%%%%%%%%%%%
Chande & Kroll's R2 Indicator
rev. 01/06/97

In their book "The New Technical Trader," Chande & Kroll introduce the r2
indicator. They state that
"the primary use of r2 is as a confirming indicator" and that "it is a
lagging indicator that shows
the strength of the trend."

In MetaStock the r2 formula is:

Pwr(Corr(Cum( 1 ),C,14,0),2)

They also present a smoothed r2 which would be:

Mov(Pwr(Corr(Cum( 1 ),C,14,0),2)*100,14,S)

For interpretation refer to Chande & Kroll's book, as stated above.


%%%%%%%%%%%%%%%
Price Action Indicator (PAIN)

If you were only given today's open, high, low and


close, how could you make heads or tails of it?
The Price Action Indicator (PAIN) can help. The formula
returns a single value that weighs
intra-day momentum (C-O), Late Selling Pressure (LSP)
(C-L), and Late Buying Pressure
(LBP) (C-H). The formula is proven by constructing ideal
limit-up and limit down scenarios in bond
futures. The output is shown to be consistent with the
interpretation of Japanese candlestick
patterns. See Michael B. Geraty (1997). "Getting Better
Directions" Futures Vol. 26: Aug.

PAIN

((C-O)+(C-H)+(C-L))/2
%%%%%%%%%%%%%%%%%%%

NATENBERG'S VOLATILITY

rev. 01/21/97

279
Historical volatility is defined by Sheldon Natenberg, as the standard
deviation of the logarithmic
price changes measured at regular intervals of time. In Mr. Natenberg's
book, "Option Volatility &
Pricing," he covers volatility in detail and gives the formula for computing
historical volatility. In
MetaStock, the equivalent formula would be:

Std( Log( C / Ref( C ,-1 ) ) ,10 ) * Sqrt( 365 / 7 )

The above assumes Weekly Data. To utilise this with Daily Data, the
MetaStock formula would be:

Std( Log( C / Ref( C,-1) ),10 ) * Sqrt( 365 )

For further interpretation refer to the book "Option Volatility & Pricing,"
by Sheldon Natenberg.

Nat's Volt
Std(log(c/ref(c,-1)),10)*sqr(365/7)

%%%%%%%%%%%%%%%

TEMA STOCHRSI FORMULA

I use is Tema smoothed and I subtract 0.5 so I


can plot it as a histogram. It's:

Periods := Input("Enter Tema Smoothing Periods",5,233,13);


Tema(((RSI(Periods) - LLV(RSI(Periods),Periods)) /
((0.0001+HHV(RSI(Periods),Periods)) -
LLV(RSI(Periods),Periods))) -0.5,Periods)

{from Jim Greening}

%%%%%%%%%%%%%%%%%5

DEVSTOP

Here's what I think a DEVSTOP is in MetaStock language, described in Kase's


"Trading with the Odds", and better described in Kaufman's "Trading Systems

280
and Methods". It uses a 2-day range, calculates an average range and SD of
the range, and then draws 4 lines below the high, at 1 range and 0,1,2, and
3 SD's. "2.2" and "3.6" are corrections for skew of the distribution.

AVTR:=Mov(HHV(H,2) - LLV(L,2),20, S);


SD:=Stdev(HHV(H,2) - LLV(L,2),20);
HHV(H-AVTR-3.6*SD, 20);
HHV(H-AVTR-2.2*SD,20);
HHV(H-AVTR-SD,20);
HHV(H-AVTR,20);

from Mikelu

%%%%%%%%%%%%

WEEKLY PIVOT POINT

{Weekly Pivot Point Projection 8/4/99}

Dw:=If(DayOfWeek()<=Ref(DayOfWeek(),-1),1,0);
{Weekly Typical Price}
PP1:=If(Dw=1,
{then}(Ref(HighestSince(1,Dw=1,H),-1)+
Ref(LowestSince(1,Dw=1,L),-1) +
Ref(C,-1))/3,
{else}0);
{Weekly High}
Wh1:=If(Dw=1,
{then}Ref(HighestSince(1,Dw=1,H),-1),
{else}0);
{Weekly Low}
Wl1:=If(Dw=1,
{then}Ref(LowestSince(1,Dw=1,L),-1),
{else}0);
Wh:=ValueWhen(1,Wh1>0,Wh1);
Wl:=ValueWhen(1,Wl1>0,Wl1);
PP:=ValueWhen(1,PP1>0,PP1);
{Resistance 1}
R1:=(2*PP)-Wl;
{Support 1}
S1:=(2*PP)-Wh;
{Resistance 2}
R2:=(PP-S1)+R1;
{Support 2}
S2:=PP-(R1-S1);
R2;

281
R1;
S1;
S2;

%%%%%%

STO RSI

Here is the formula for Metastock for the StoRSI. I have made it so we can change
timeperiods of RSI and MA´s and also so that we can change the type of MA´s.
Lars.
RSIPeriod:= Input("Enter periods for RSI",2,300,8);
HLPeriod:= Input("Enter periods for HHV and LLV",2,300,8);
MAPeriod:= Input("Enter periods for Moving Average",2,300,3);
mat:= Input(" MA Typ,S,E,W,T",1,4,2);{1=S,2=E,3=W,4=T}
If(mat=1,(Mov((RSI(RSIPeriod)-
LLV(RSI(RSIPeriod),HLPeriod))/(HHV(RSI(RSIPeriod),HLPeriod)-
LLV(RSI(RSIPeriod),HLPeriod)),MAPeriod,S)*100),
If(mat=2,(Mov((RSI(RSIPeriod)-
LLV(RSI(RSIPeriod),HLPeriod))/(HHV(RSI(RSIPeriod),HLPeriod)-
LLV(RSI(RSIPeriod),HLPeriod)),MAPeriod,E)*100),
If(mat=3,(Mov((RSI(RSIPeriod)-
LLV(RSI(RSIPeriod),HLPeriod))/(HHV(RSI(RSIPeriod),HLPeriod)-
LLV(RSI(RSIPeriod),HLPeriod)),MAPeriod,W)*100),
If(mat=4,(Mov((RSI(RSIPeriod)-
LLV(RSI(RSIPeriod),HLPeriod))/(HHV(RSI(RSIPeriod),HLPeriod)-
LLV(RSI(RSIPeriod),HLPeriod)),MAPeriod,T)*100),0))))

Here is one that works for TS6. Should work for yours.

Randy

Input: Price(close),RSILen(5),Length(3);
Var:StochRSI1(0), Value2(0), Value3(0);
{StochRSI1 =
(Summation(RSI(Price, RSILen) -
Lowest(RSI(Price, RSILen), Length),3)) /
(Summation(Highest(RSI(Price, RSILen), Length) -
Lowest(RSI(Price, RSILen), Length),3));}
Value2=(Summation(RSI(Price, RSILen) -
Lowest(RSI(Price, RSILen), Length),3));
Value3=(Summation(Highest(RSI(Price, RSILen), Length) -
Lowest(RSI(Price, RSILen), Length),3));
StochRSI1 = Iff(Value2=0,0,Value2/Value3);

Plot1(StochRSI1 *100,"StochRSI");

282
Plot2(80);
Plot3(20);

{Function: Stochastic of RSI


Author: Clyde Lee}

Input: length(Numeric);
Vars: RSIVal(0);

RSIVal=RSI(C,LENGTH);
Value1=Highest(RSIVal,Length);
Value2=Lowest (RSIVal,Length);
Value3=Value1-Value2;
If CurrentBar>Length and Value3>0
then StochRSI_Lee = (RSIVal-Value2)/Value3*100
else StochRSI_Lee = 50 ;

ATR MODIFIED

prd1:=input("enter ATR period",1,9999,7);


prd2:=(prd1*2)-1;
{max (absolute) of yesterday's close to today's high or today's low}
myatr1:=Max(Abs(Ref(C,-1)-H),Abs(Ref(C,-1)-L));
{max of yesterday's close to today's high or today's low or today's range}
myatr2:=Max(myatr1,H-L);

{
%%%%%%%%%%%%%%%%%

HIGHEST HIGH SINCE BUY SIGNAL


Anyone know how to keep track of, for example, the highest high since a
buy signal was triggered? I want to > add this into a system test that I am
trying to run.

HighestSince(1, {Buy Signal-->}Cross(C,Mov(C,20,E))


,H)

from Ken

%%%%%%%%%%%%%%%%%%

283
MINER’S STORSI

This indicator came out a number of years ago now and was a hot topic on
compuserve. Sorry, but the thread I saved on it seems to be gone.

Haven't spoken to John Yurko in years but here are two of John's original posts on
StochRsi from CompuServe circa 1995. I backtested the heck out of his "rules" but
found the results inconclusive.

Earl

It was discussed in Chande & Kroll's book 'The New Technical Trader'. Pub
1994 by John Wiley & Sons ISBN 0-471-59780-5 $49.95

It took me only one scan of the book before I decided to buy it, as I saw the potential
of this one indicator at helping identify low risk long and short entry points. Like I
said, I took the simple-minded approach and applied this indicator's ability to define
when a security is strongly trending, by tracking it over a longer time frame (14
week), and looking for 'oversold' or 'overbought' readings with a shorter time frame
(14 day). I've not yet tried to optimize those time frames, or the definitions of
'strongly trending', 'oversold' or 'overbought'.

I wrote the formula quite easily in MSW 5.0, but you have to work with the direct
definition of Stochastics. Remember, StochasticsRSI doesn't calculate the Stochastics
of PRICE values, it calculates Stochastics of RSI values. In essence, in MetaStock's
language, wherever you see a Price, usually the Close, in the Stochastics formula,
replace it with the RSI function. For simplicity sake, I've kept the time frames the
same between Stochastics and RSI. That is, if I'm calculating a 14-period
StochasticsRSI, I use a 14-period RSI in the formula. Of course, one could test
various RSI period lengths for a given StochasticsRSI period length, but I haven't
done that. As you can see, this type of indicator allows for a rather wide set of
testing conditions when it comes to the essence of my idea, if one wants to
go that route. Not only can you vary the RSI periods for a fixed StochasticsRSI
period, but you can vary the relationship between the "short-term" StochasticsRSI
time period and the "long-term" StochasticsRSI time period. The latter of course is
nothing different than if you were testing various combinations of EMAs for say the
McClellan Oscillator, instead of the usual 19 and 39 day time periods. Enough talk.
Here's the MetaStock formulas:

Using the custom formula from page 191 of the MSW manual, and amending it to
that of a 14-period %K Stochastic Oscillator with a 3-period slowing we get:

(SUM( C - LLV(L,14), 3 ) / SUM(HHV(H,14) - LLV(L,14), 3) ) *100

Now, substituting RSI where necessary to get the 14-day StochasticsRSI


Oscillator, we get:

(SUM( RSI(14) - LLV(RSI(14) , 14), 3) / SUM(HHV(RSI(14), 14) - LLV(RSI(14),


14), 3)) *100

284
For the 70-day (14 week) StochasticsRSI Oscillator, we get:

(SUM(RSI(70) - LLV(RSI(70), 70), 15) / SUM(HHV(RSI(70), 70) - LLV(RSI(70),


70), 15))*100

You could of course use a 3-period slowing instead of the 15-period slowing as I
have, but I thought it more "logical" to multiply all the terms in the 14-period
StochasticsRSI by 5 to arrive at the 70-period StochasticsRSI.

Enjoy!
John

First of all, StochRSI gives relatively _few_ buy signals. If you get a half dozen in a
year for a particular stock, that's a lot. Remember, the stock (or market) has to be
trending or beginning to trend before StochRSI will give you low risk buy points.
BTW, I never said in any of my messages that I use StochRSI for _sell signals,
although the occasional super obvious divergence does show itself now and again.
You can use a 50-day MA crossing if you're shorter term oriented as your sell signal,
or the stock's 150-day SMA if you're long term oriented, and test that as an exit rule
for StochRSI. I don't though, at least not by itself. <g> However, if I told you what I
_do_ use, I'd be revealing details of my proprietary Bell Ringer system, which does
use a 150-day SMA as a 'just in case' sell signal.

Buy Signals for StochRSI:

The first two are created through the _interaction_ of the StochRSI-14 and
StochRSI-70 oscillators.

1. IF StochRSI-70 > 80.0 and previous day's StochRSI-14 <= 20.0


and today's StochRSI-14 > 20.0 then BUY at the close of that trading
day.

Footnote: You _can_ determine a day in advance what stock price will cause the
StochRSI-14 value to cross the 20 level, while keeping the StochRSI-70 above the 80
level. That way, you _can buy near the close of that trading day as opposed to waiting
till the next trading day's opening to exceute your purchase. It's not an especially
easy exercise to do that though, unless you don't mind spending some time in
Algorithm Alley. <g> I did though, simply due to the fact that on such crossings of 20
by StochRSI-14, up gap openings are more common than normal, and in fact so are
situations where the next day's low is above today's high.

2. IF StochRSI-70 > 50.0 and previous day's StochRSI-14 <= 20.0 and today's
StochRSI-14 > 20.0 AND HHV(ROC(StochRSI-70,1,Points),21) > 3.0 then BUY.

There is also a provision that LLV(StochRSI-70,21) <= 20.0 In other words, the
stock has been (and may still be) in a basing pattern, but it's upside 70 day
momentum, as defined by StochRSI-70, is sufficiently strong that the odds highly
favor an upside breakout in the stock's price, and the stock is short-term oversold as

285
measured by the StochRSI-14, and has just given the first sign that it's about to run to
the upside, by its breaking above the 20 level in StochRSI-14.

That first condition using HHV basically means that within the previous 21 trading
days, there was at least one trading day where the one-day Change of the StochRSI-
70 exceeded 3 points, i.e., it rose more than 3 points from the prior day's value. You
can set a higher level to test, rather than use 3.0, but I've found that the 3.0 value
doesn't add much if any 'less accurate' potential buying situations into the stock
selection process.

That second condition using LLV basically means that within the previous 21 trading
days, StochRSI-70 was at or below the 20 level. In other words, it was long-term
oversold. I added this condition later on, but it's not absolutely necessary. I just
wanted to reduce the number of potential buy candidates a bit.

This last BUY signal is different from the other two, as it uses the interaction between
the oscillator which is the SUM of the StochRSI-14 and StochRSI-70 values, and the
150-day SMA of the stock. I call this oscillator my "StochRSI-14 + StochRSI-70"
oscillator. Obviously,something a little more intuitive name is required! Maybe I
should call it the SUMStochRSI(14,70) oscillator. Naming suggestions are more than
welcome!

The buy criteria is simplicity itself. The stock MUST close at or above its 150-day
SMA AND yesterday's SUMStochRSI(14,70) < 50.0 and today's StochRSI(14,70) >
50.0

Basically what I'm doing here with this buy signal is I'm saying that whatever level of
selling pressure that developed in a stock, it did NOT have enough staying power to
drive the stock below its 150-day SMA, which is after all a trendline. Not only that,
but that selling pressure has shown it's first sign of abating, by the fact that the
SUMStochRSI(14,70) has broken above the 50 level, which I consider it to be the
level where a stock is long-term deeply oversold.

BTW, an _especially_ good BUY signal occurs when SUMStochRSI(14,70) crosses


from below 50 to above 50, and where the stock could not break below its 50-day
SMA on a closing basis, while the stock got deeply long-term oversold!!!

{*********************STOCHRSI**********************}

Input: RSILen(13), LBLen(8), WAvgLen(5);

Var: RS(0),RSIL(0),RSIH(0),StochRSI(0);

RS=RSI(C,RSILen);
RSIL = Lowest(RS,LBLen);
RSIH = Highest(RS,LBLen);

StochRSI = (RS - RSIL)/(RSIH-RSIL);

286
Plot1 (WAverage(StochRSI,WAvgLen),"Stoch RSI"); NB fix divide by zero error.

FORECAST OSCILLATOR SYSTEM ALTERNATIVE

Enter long:
Cross(ForecastOsc(C,21),Mov(ForecastOsc(C,21),3,E)) AND
Cross(ForecastOsc(C,21),0)

Exit long:
Cross(Mov(ForecastOsc(C,21),3,E),ForecastOsc(C,21)) AND
Cross(6,ForecastOsc(C,21))

{You can use alert() function on either if you don't require both conditions
to fire on the same day.}

%%%%%%%%%%%%%%%%%%%%

FORECAST OSCILLATOR SYSTEM


Enter long:
Cross(ForecastOsc(C,21),Mov(C,3,E)) AND
Cross(ForecastOsc(C,21),0)

Exit long:
Cross(Mov(C,3,E),ForecastOsc(C,21)) AND
Cross(6,Mov(C,3,E))

%%%%%%%%%%%%%%%

EQUIVILANT TO WILDERS TR

Wilders(TR,periods) = Mov(TR,2*periods-1,E)

%%%%%%%%%%%%%%%%%%

TRUE RANGE FORMULA

TR = (H - L + Abs(H - Ref(C,-1)) + Abs(L - Ref(C,-1)) )/2

{from Bob Jagow

MURREY MATH

> >SqW:=Input("Square Width (Days)",4,256,64);


> >MM:=Input("Start Date Month",1,12,10);

287
> >DD:=Input("Start Date Day ",1,31, 5);
> >YY:=Input("Start Date Year ",1700,2100,1998);
> >
> >T0:=LastValue(ValueWhen(1,DayOfMonth()=DD AND
> > Month()=MM AND
> > Year()=YY,Cum(1)));
> >
> >Sqrs:=Int((LastValue(Cum(1))-T0)/SqW)-1;
> >
> >S0:=T0+(Sqrs*SqW);
> >
> >Lo:=LastValue(ValueWhen(1,Cum(1)=S0+SqW-1,
> > LLV(Min(H,L),SqW)));
> >
> >Hi:=LastValue(ValueWhen(1,Cum(1)=S0+SqW-1,
> > HHV(Max(H,L),SqW)));
> >
> >Sf:=
> >If(Hi>25,If(Log(0.4*Hi)/Log(10)-
> > Int(Log(0.4*Hi)/Log(10))>0,
> >Exp(Log(10)*(Int(Log(0.4*Hi)/Log(10))+1)),
> >Exp(Log(10)*(Int(Log(0.4*Hi)/Log(10))))),
> >100*Exp(Log(8)*(Int(Log(0.005*Hi)/Log(8)))));
> >
> >N:=
> >If(Log(Sf/(Hi-Lo))/Log(8)<=0,0,
> > If(Frac(Log(Sf/(Hi-Lo))/Log(8))=0,
> > Int(Log(Sf/(Hi-Lo))/Log(8)),
> > Int(Log(Sf/(Hi-Lo))/Log(8))+1));
> >
> >Si:=Sf*Exp(-N*Log(8));
> >
> >M:=Int(((1/Log(2))*Log((Hi-Lo)/Si))+.00001);
> >
> >I:=Round(((Hi+Lo)*.5)/(Si*Exp((M-1)*Log(2))));
> >
> >B:=(I-1)*Si*Exp((M-1)*Log(2));
> >TT:=(I+1)*Si*Exp((M-1)*Log(2));
> >
> >Er:=If(Hi-TT>0.25*(TT-B) OR
> > B-Lo>0.25*(TT-B),1,0);
> >
> >MM:=If(Er=0,M,If(Er=1 AND M<2,M+1,0));
> >NN:=If(Er=0,N,If(Er=1 AND M<2,N,N-1));
> >
> >Si:=Sf*Exp(-NN*Log(8));
> >
> >I:=Round(((Hi+Lo)*.5)/
> > (Si*Exp((MM-1)*Log(2))));
> >
> >B:=ValueWhen(1,Cum(1)>=S0,
> > (I-1)*Si*Exp((MM-1)*Log(2)));
> >
> >TT:=ValueWhen(1,Cum(1)>=S0,
> > (I+1)*Si*Exp((MM-1)*Log(2)));
> >
> >B;
> >
> >{L1:=}ValueWhen(1,Cum(1)>=S0,
> > B+(0.125*(TT-B)));

288
> >

> >{L2:=}ValueWhen(1,Cum(1)>=S0,
> > B+(2.0*(0.125*(TT-B))));
> >
> >{L3:=}ValueWhen(1,Cum(1)>=S0,
> > B+(3.0*(0.125*(TT-B))));
> >
> >{L4:=}ValueWhen(1,Cum(1)>=S0,
> > B+(4.0*(0.125*(TT-B))));
> >
> >{L5:=}ValueWhen(1,Cum(1)>=S0,
> > B+(5.0*(0.125*(TT-B))));
> >
> >{L6:=}ValueWhen(1,Cum(1)>=S0,
> > B+(6.0*(0.125*(TT-B))));
> >
> >{L7:=}ValueWhen(1,Cum(1)>=S0,
> > B+(7.0*(0.125*(TT-B))));
> >
> >TT;

ZIGZAG CODE
Since there are many users who showed interest in my indicator, I provide
here the code for a complete Expert. It uses Trends, Highlights, Symbols,
Alerts and a simple Commentary.
______________________________________________________

New Expert for ZigZag validity

Name: ZigZag validity

------------------------------------------------------

Trends

Bullish:
Zig(CLOSE ,10 ,% ) > Ref(Zig(CLOSE ,10 ,% ),-1)
AND Fml("ZigZag validity") = 1

Bearish:
Zig(CLOSE ,10 ,% ) < Ref(Zig(CLOSE ,10 ,% ),-1)
AND Fml("ZigZag validity") = 1

------------------------------------------------------

Highlights (the code is the same as above)

Name: UpTrend confirmed


Color: Green or Dk Green
Condition:
Zig(CLOSE ,10 ,% ) > Ref(Zig(CLOSE ,10 ,% ),-1)

289
AND Fml("ZigZag validity") = 1

Name: DownTrend confirmed


Color: Red
Condition:
Zig(CLOSE ,10 ,% ) < Ref(Zig(CLOSE ,10 ,% ),-1)
AND Fml("ZigZag validity") = 1

------------------------------------------------------

Symbols (there are 3 symbols)

Name: Zig invalid


Graphic: ? (question mark)
Color : Black
Condition :
Cross(0.5, Fml("ZigZag validity"))

Name: UpTrend confirmed


Graphic: Thumbs Up
Color : Green or Dk Green
Condition :
cond:=
Zig(CLOSE ,10 ,% ) > Ref(Zig(CLOSE ,10 ,% ),-1)
AND Fml("ZigZag validity") = 1;
Cross(cond,0.5)

Name: DownTrend confirmed


Graphic: Thumbs Down
Color : Red
Condition :
cond:=
Zig(CLOSE ,10 ,% ) < Ref(Zig(CLOSE ,10 ,% ),-1)
AND Fml("ZigZag validity") = 1;
Cross(cond,0.5)

------------------------------------------------------

Alerts (there are 3 alerts using the same code as the Symbols section)

Name: Zig invalid


Alert : Zig is invalid here
Condition:
Cross(0.5,Fml("ZigZag validity"))

Name: UpTrend confirmed


Alert : Up trend confirmed
Condition :
cond:=

290
Zig(CLOSE ,10 ,% ) > Ref(Zig(CLOSE ,10 ,% ),-1)

AND Fml("ZigZag validity") = 1;


Cross(cond,0.5)

Name: DownTrend confirmed


Alert : Down trend confirmed
Condition :
cond:=
Zig(CLOSE ,10 ,% ) < Ref(Zig(CLOSE ,10 ,% ),-1)
AND Fml("ZigZag validity") = 1;
Cross(cond,0.5)

------------------------------------------------------

Commentary

<expert>
by Spyros Raftopoulos

Review of <name> (<symbol>)


<date>
------------------------------------------

Zig(Close,10,% ): writeval(Zig(Close,10,% ),8.2)

writeif(Zig(Close,10,% )>ref(Zig(Close,10,% ),-1), "The ZigZag indicator is


ascending which means that prices are moving up.", "Prices move downward as
shown by the descending ZigZag indicator. ")
writeif(fml("ZigZag validity")=1, "This trend is confirmed by the ZigZag
validity indicator. Zig Zag has been valid for
writeval(barssince(cross(fml("ZigZag validity"),0.5)), 3.0) bars.",
"However, the trend is not confirmed yet. Zig Zag has been invalid for
writeval(barssince(cross(0.5,fml("ZigZag validity"))), 3.0) bars.")

___________________________________________

The above tools are very similar: Alerts coincide with Symbols and
Highlights coincide with Trends.
Therefore you may not need all of them at the same time.
Remember that, at any time, you can activate or deactivate any of the above
by clicking on the corresponding check box(es).

I hope this helps. In any case please drop me a note.


If there are any more problems also let me know.

Cheers
Spyros

____________________________________________

291
TRADE EQUITY AND TRADE STOP FORMULA UPDATE

A number of small changes have been incorporated in the following indicators, and the version
numbers have been adjusted accordingly. Most changes relate to the handling of intra-day trades.
Several restrictions now limit the execution of intra-day trades, and these are really just a matter of
common sense.

TE will inhibit intra-day trades, i.e. not currently in a trade and receives concurrent entry and exit
signals, when;
1. entry option =2 (enter on close)
2. exit option =1 (exit on open)
3. entry and exit options are the same but neither =5

TS will enforce similar restrictions, and it can also terminate a trade intra-day if either target price is
met. The ‘exit on next open’ timing option is precluded when using price exit signals (exit option =5).

Indicators
Trade Equity LE V2.7
Trade Equity LE V3.3
Trade Equity SE V2.7
Trade Equity SE V3.3
Trade Stop LE V3.3
Trade Stop SE V3.3

From my perspective the TE v2.7 indicators are close to “bullet proof”, and the TE v3.3 indicators
almost as robust. The TS indicators are less robust but I would still expect them to be very accurate
under normal usage (whatever that is). By providing a wide range of user options I have also greatly
increased the number of things that can go wrong. I would really appreciate any feedback that anyone
can offer (I’m not looking for bouquets but problems with usage or function).

{Trade Equity LE} {V2.7 long side only}


{* user default settings *}
No:=Input("Enter 1=O 2=C 3=H 4=L 5=Stop",1,5,2);
Xo:=Input(" Exit 1=O 2=C 3=H 4=L 5=Stop",1,5,2);
Nd:=Input("Entry Delay",0,3,0);
Xd:=Input(" Exit Delay",0,3,0);
Cp:=10000; {* trade capital *}
Cn:=Input("Entry Commission $",0,99,30);
Cx:=Input(" Exit Commission $",0,99,30);
{For % commission use this and (*) code}
{Cn:=Input("Entry Commission %",0,3,0.5)*Cp/100;
Cx:=Input(" Exit Commission %",0,3,0.5)/100;}
N:= Fml("PS Fractal Entry")>0;
Ns:=Fml("PS Fractal Entry");
X:= Fml("PS Fractal Exit")>0;
Xs:=0 {Fml("Trade Stop LE")};
{* end of user area *}
Ns:=If(No=5,Ns,0);
Np:=If(Ns>0,Ns,If(No=1,O,If(No=3,H,If(No=4,L,C))));
N:=N AND Alert(N=0,2); X:=X AND Alert(X=0,2);
N:=If(Nd=0,N,Alert(N,Nd+1) AND Alert(N,Nd)=0);
N:=If(No=5 AND Ns>0,1,If(No<5,N,0));
Xp:=If(Xs>0,Min(H,Max(L,Xs)),If(Xo=1,O,If(Xo=3,H,If(Xo=4,L,C))));
X:=If(Xd=0,X,Alert(X,Xd+1) AND Alert(X,Xd)=0);
X:=If(Xs>0,1,X);
Xp:=If(Xo<5 AND No=5 AND X=0,C,Xp);
Xp:=If(Xs>0 AND N AND X,Xs,Xp);

292
Xp:=If(Ref(N AND X,-1),Ref(Xp,-1),Xp);
I:=Cum((N+Ns+X+Xs)>-1)=1;
Tr:=BarsSince(I OR N)<BarsSince(I OR X);
Tr:=If(N+X>1 AND (Alert(Tr,2) OR (Nd+Xd<1 AND
No<>2 AND Xo>1 AND (Max(No,Xo)>4 OR No<>Xo))),1, Tr);
Np:=If(I AND N=0,C,Np);
En:=(Tr AND Alert(Tr=0,2)) OR I;
Ex:=Tr=0 AND Alert(Tr,2);
Lb:=(Alert(Tr,2)) AND LastValue(Cum(1)-0)=Cum(1);
Ea:=ValueWhen(1,En,If(No=5 AND N AND X,Np,Max(O,Np)));
Ea:=If(No<5,ValueWhen(1,En,Np),Ea);
En:=Tr AND Alert(Tr=0,2);
N:=If(Ex OR Lb,(Cp-Cn)*(Xp/Ea)-Cp-If(Ex,Cx,0),0);
{*}{N:=If(Ex OR Lb,(Cp-Cn)*(Xp/Ea)-Cp -If(Ex,Cx*(Cp -Cn)*(Xp/Ea),0),0);}
Bt:=If(Alert(Tr,2),1+BarsSince(En OR I),0);
Xs:=If(Alert(Tr,2),(Cp-Cn)*(Xp/Ea)-Cp-If(Ex,Cx,0),0);
{*}{Xs:=If(Alert(Tr,2),(Cp-Cn)*(Xp/Ea)-Cp-If(Ex,Cx*(Cp-Cn)*(Xp/Ea),0),0);}
Nd:=LowestSince(1,I,Xs);
Ns:=HighestSince(1,I,Xs);
X:=Cum(If((Ex OR Lb) AND N> 0,Bt,0));
Xd:=Cum(If((Ex OR Lb) AND N<=0,Bt,0));
Cum(N)+If(Tr AND Lb=0,(Cp-Cn)*(Xp/Ea),Cp);

{Trade Equity LE} {V3.3 long side only}


{* user default settings *}
No:=Input("Entry and exit prices, 1=O 2=C 3=H 4=L 5=Price, ##",11,55,22);
Cp:=Input("Position size, entry and exit delays, $ ## ",0,100033,10000);
Cm:=Input("Entry and exit costs, $$",0,9999,3030);
N:= Fml("PS Fractal Entry")>0;
Ns:=Fml("PS Fractal Entry");
X:= Fml("PS Fractal Exit")>0;
Xs:=0 {Fml("Trade Stop LE")};
{* end of user area *}
Nd:=LastValue(Int(Frac(Cp/99)*10));
Xd:=LastValue(Cp-Int(Cp/10)*10);
Cp:=Int(Cp/100)*100;
Xo:=No-10*Int(No/10); No:=Int(No/10);
Cx:=Cm-100*Int(Cm/100); Cm:=Int(Cm/100);
Ns:=If(No=5,Ns,0);
Np:=If(Ns>0,Ns,If(No=1,O,If(No=3,H,If(No=4,L,C))));
N:=N AND Alert(N=0,2); X:=X AND Alert(X=0,2);
N:=If(Nd=0,N,Alert(N,Nd+1) AND Alert(N,Nd)=0);
N:=If(No=5 AND Ns>0,1,If(No<5,N,0));
Xp:=If(Xs>0,Min(H,Max(L,Xs)),If(Xo=1,O,If(Xo=3,H,If(Xo=4,L,C))));
X:=If(Xd=0,X,Alert(X,Xd+1) AND Alert(X,Xd)=0);
X:=If(Xs>0,1,X);
Xp:=If(Xo<5 AND No=5 AND X=0,C,Xp);
Xp:=If(Xs>0 AND N AND X,Xs,Xp);
Xp:=If(Ref(N AND X,-1),Ref(Xp,-1),Xp);
I:=Cum((N+Ns+X+Xs)>-1)=1;
Tr:=BarsSince(I OR N)<BarsSince(I OR X);
Tr:=If(N+X>1 AND (Alert(Tr,2) OR (Nd+Xd<1 AND
No<>2 AND Xo>1 AND (Max(No,Xo)>4 OR No<>Xo))),1, Tr);
Np:=If(I AND N=0,C,Np);
En:=(Tr AND Alert(Tr=0,2)) OR I;
Ex:=Tr=0 AND Alert(Tr,2);
Lb:=(Alert(Tr,2)) AND LastValue(Cum(1)-0)=Cum(1);
Ea:=ValueWhen(1,En,If(No=5 AND N AND X,Np,Max(O,Np)));
Ea:=If(No<5,ValueWhen(1,En,Np),Ea);
En:=Tr AND Alert(Tr=0,2);

293
N:=If(Ex OR Lb,(Cp-Cm)*(Xp/Ea)-Cp -If(Ex,Cx,0),0);
Bt:=If(Alert(Tr,2),1+BarsSince(En OR I),0);
Xs:=If(Alert(Tr,2),(Cp-Cm)*(Xp/Ea)-Cp-If(Ex,Cx,0),0);
Nd:=LowestSince(1,I,Xs);
Ns:=HighestSince(1,I,Xs);
X:=Cum(If((Ex OR Lb) AND N>0,Bt,0));
Xd:=Cum(If((Ex OR Lb) AND N<=0,Bt,0));
Cum(N)+If(Tr AND Lb=0,(Cp-Cm)*(Xp/Ea),Cp);

{Trade Equity SE} {V2.7 short side only}


{* user default settings *}
No:=Input("Enter 1=O 2=C 3=H 4=L 5=Stop",1,5,2);
Xo:=Input(" Exit 1=O 2=C 3=H 4=L 5=Stop",1,5,2);
Nd:=Input("Entry Delay",0,3,0);
Xd:=Input(" Exit Delay",0,3,0);
Cp:=10000; {* trade capital *}
Cn:=Input("Entry Commission $",0,99,30);
Cx:=Input(" Exit Commission $",0,99,30);
N:= Fml("PS Fractal Exit")>0;
Ns:=Fml("PS Fractal Exit");
X:= Fml("PS Fractal Entry")>0;
Xs:=0 {Fml("Trade Stop SE")};
{* end of user area *}
Ns:=If(No=5,Ns,0);
Np:=If(Ns>0,Ns,If(No=1,O,If(No=3,H,If(No=4,L,C))));
N:=N AND Alert(N=0,2); X:=X AND Alert(X=0,2);
N:=If(Nd=0,N,Alert(N,Nd+1) AND Alert(N,Nd)=0);
N:=If(No=5 AND Ns>0,1,If(No<5,N,0));
Xp:=If(Xs>0,Min(H,Max(L,Xs)), If(Xo=1,O,If(Xo=3,H,If(Xo=4,L,C))));
X:=If(Xd=0,X,Alert(X,Xd+1) AND Alert(X,Xd)=0);
X:=If(Xs>0,1,X);
Xp:=If(Xo<5 AND No=5 AND X=0,C,Xp);
Xp:=If(Xs>0 AND N AND X,Xs,Xp);
Xp:=If(Ref(N AND X,-1),Ref(Xp,-1),Xp);
I:=Cum((N+Ns+X+Ns)>-1)=1;
Tr:=BarsSince(I OR N)<BarsSince(I OR X);
Tr:=If(N+X>1 AND (Alert(Tr,2) OR (Nd+Xd<1 AND
No<>2 AND Xo>1 AND (Max(No,Xo)>4 OR No<>Xo))),1, Tr);
Np:=If(I AND N=0,C,Np);
En:=(Tr AND Alert(Tr=0,2)) OR I;
Ex:=Tr=0 AND Alert(Tr,2);
Lb:=(Alert(Tr,2)) AND LastValue(Cum(1)-0)=Cum(1);
Ea:=ValueWhen(1,En,If(No=5 AND N AND X,Np,Min(O,Np)));
Ea:=If(No<5,ValueWhen(1,En,Np),Ea);
En:=Tr AND Alert(Tr=0,2);
N:=If(Ex OR Lb,(Cp-Cn)*((Ea-Xp)/Ea)-Cn- If(Ex,Cx,0),0);
Bt:=If(Alert(Tr,2),1+BarsSince(En OR I),0);
Xs:=If(Alert(Tr,2),(Cp-Cn)*((Ea-Xp)/Ea)-Cn-If(Ex,Cx,0),0);
Nd:=LowestSince(1,I,Xs);
Ns:=HighestSince(1,I,Xs);
X:=Cum(If((Ex OR Lb) AND N> 0,Bt,0));
Xd:=Cum(If((Ex OR Lb) AND N<=0,Bt,0));
Cum(N)+If(Tr AND Lb=0,Cp-Cn+(Cp-Cn)*((Ea-Xp)/Ea),Cp);

{Trade Equity SE} {V3.3 short side only}


{* user default settings *}
No:=Input("Entry and exit prices, 1=O 2=C 3=H 4=L 5=Price, ##",11,55,22);
Cp:=Input("Position size, entry and exit delays, $ ## ",0,100033,10000);
Cn:=Input("Entry and exit costs, $$",0,9999,3030);
N:= Fml("PS Fractal Exit")>0;

294
Ns:=Fml("PS Fractal Exit");
X:= Fml("PS Fractal Entry")>0;
Xs:=0 {Fml("Trade Stop SE")};
{* end of user area *}
Nd:=LastValue(Int(Frac(Cp/99)*10));
Xd:=LastValue(Cp-Int(Cp/10)*10);
Cp:=Int(Cp/100)*100;
Xo:=No-10*Int(No/10); No:=Int(No/10);
Cx:=Cn-100*Int(Cn/100); Cn:=Int(Cn/100);
Ns:=If(No=5,Ns,0);
Np:=If(Ns>0,Ns,If(No=1,O,If(No=3,H,If(No=4,L,C))));
N:=N AND Alert(N=0,2); X:=X AND Alert(X=0,2);
N:=If(Nd=0,N,Alert(N,Nd+1) AND Alert(N,Nd)=0);
N:=If(No=5 AND Ns>0,1,If(No<5,N,0));
Xp:=If(Xs>0,Min(H,Max(L,Xs)), If(Xo=1,O,If(Xo=3,H,If(Xo=4,L,C))));
X:=If(Xd=0,X,Alert(X,Xd+1) AND Alert(X,Xd)=0);
X:=If(Xs>0,1,X);
Xp:=If(Xo<5 AND No=5 AND X=0,C,Xp);
Xp:=If(Xs>0 AND N AND X,Xs,Xp);
Xp:=If(Ref(N AND X,-1),Ref(Xp,-1),Xp);
I:=Cum((N+Ns+X+Ns)>-1)=1;
Tr:=BarsSince(I OR N)<BarsSince(I OR X);
Tr:=If(N+X>1 AND (Alert(Tr,2) OR (Nd+Xd<1 AND
No<>2 AND Xo>1 AND (Max(No,Xo)>4 OR No<>Xo))),1, Tr);
Np:=If(I AND N=0,C,Np);
En:=(Tr AND Alert(Tr=0,2)) OR I;
Ex:=Tr=0 AND Alert(Tr,2);
Lb:=(Alert(Tr,2)) AND LastValue(Cum(1)-0)=Cum(1);
Ea:=ValueWhen(1,En,If(No=5 AND N AND X,Np,Min(O,Np)));
Ea:=If(No<5,ValueWhen(1,En,Np),Ea);
En:=Tr AND Alert(Tr=0,2);
N:=If(Ex OR Lb,(Cp-Cn)*((Ea-Xp)/Ea)-Cn- If(Ex,Cx,0),0);
Bt:=If(Alert(Tr,2),1+BarsSince(En OR I),0);
Xs:=If(Alert(Tr,2),(Cp-Cn)*((Ea-Xp)/Ea)-Cn-If(Ex,Cx,0),0);
Nd:=LowestSince(1,I,Xs);
Ns:=HighestSince(1,I,Xs);
X:=Cum(If((Ex OR Lb) AND N> 0,Bt,0));
Xd:=Cum(If((Ex OR Lb) AND N<=0,Bt,0));
Cum(N)+If(Tr AND Lb=0,Cp-Cn+(Cp-Cn)*((Ea-Xp)/Ea),Cp);

{Trade Stop LE} {V3.3}


No:=Input("Entry - exit price 1=O 2=C 3=H 4=L 5=Price ##",11,55,22);
Cp:=Input("Capital, entry - exit delays $ ## ",0,100033,10000);
Cm:=Input("Entry - exit costs $$",0,9999,3030);
Xa:=Input("Stop timing 1=C/O+ 2=C/C 3=Stop/C 4=Stop ##" ,11,44,22);
Pt:=Input("Targets, profit - loss 99=N/A %%",0,9999,2010);
Pd:=Input("Timed exit 99=N/A ##",1,99,99);
N:= Fml("PS Fractal Entry")>0;
Ns:=Fml("PS Fractal Entry");
X:= Fml("PS Fractal Exit")>0;
Xs:=Fml("PS Fractal Exit");
Xo:=No-10*Int(No/10);No:=Int(No/10);
Xc:=Xa-10*Int(Xa/10);Xa:=Int(Xa/10);
Nd:=LastValue(Int(Frac(Cp/99)*10));
Xd:=LastValue(Cp-Int(Cp/10)*10);
Cx:=Cm-100*Int(Cm/100);Cm:=Int(Cm/100);Cp:=Int(Cp/100)*100;
Ls:=Frac(Pt/100);Pt:=Int(Pt/100)/100;
N:=N AND Alert(N=0,2);X:=X AND Alert(X=0,2);
N:=If(Nd=0,N,Alert(N,Nd+1) AND Alert(N,Nd)=0);
N:=If(N>0,If(No=1,O,If(No=3,H,If(No=4,L,C))),0);

295
N:=If(No=5,If(Ns>0,Max(L,Ns),0),N);
X:=If(Xd=0,X,Alert(X,Xd+1) AND Alert(X,Xd)=0);
X:=If(X>0,If(Xo=1,O,If(Xo=3,H,If(Xo=4,L,C))),0);
X:=If(Xs>0 AND Xo=5,Max(L,Xs),X);
Pf:=(Cp*(1+Pt)+Cx)/(Cp-Cm);
Lf:=Min(1,(Cp*(1-Ls)+Cx)/(Cp-Cm));
Tr:=If(PREV=0,If(N>0 AND X=0 AND (No=2 OR
(If(Xa<3,C,H)<Pf*N AND If(Xc<3,C,L)>Lf*N)),N,0), If(X>0
OR (BarsSince(PREV=0)=Pd AND Pd<>99) OR
(If(Xa<3,C,H)>=Pf*PREV AND Pt<>.99) OR
(If(Xc<3,C,L)<=Lf*PREV AND Ls<>.99),0,PREV));
Tr:=If(Alert(Tr>0,2)=0 AND N>0 AND
(((If(Xa<3,C,H)>=Pf*N OR If(Xc<3,C,L)<=Lf*N)
AND No<>2) OR (X>0 AND Nd+Xd<1 AND No<>2 AND
Xo>1 AND (Max(No,Xo)>4 OR No<>Xo))),-N,Tr);
Xb:=(Tr=0 AND Alert(Tr>0,2)) OR (Tr<0 AND Alert(Tr=0,2));
Cx:=ValueWhen(1,Cum((N+Ns+X+Xs)>-1)=1 OR Tr<>0,Abs(Tr));
Cp:=If(Xb,If(Xa<3 AND C>=Cx*Pf,C,If(Xa>2 AND H>=Cx*Pf,Cx*Pf,0)),0);
Cp:=If(Cp>0,If(Cp>=.5,PREC(Cp,2),If(Cp<.1,PREC(Cp,3),PREC(Cp*2,2)/2)),0);
Cp:=If(Xa=4 AND Cp>0,If(Tr<0,Cp,Max(O,Cp)),Cp);
Cp:=If(Xa=3 AND Cp>0,C,If(Xa=1 AND Xo<5,Ref(Cp,-1),Cp));
Cp:=If(Xa=1 AND Cp>0 AND Xo<5,O,Cp);
Cm:=If(Xb,If(Xc<3 AND C<=Cx*Lf,C,If(Xc>2 AND L<=Cx*Lf,Cx*Lf,0)),0);
Cm:=If(Cm>0,If(Cm>=.5,PREC(Cm,2),If(Cm<.1,PREC(Cm,3),PREC(Cm*2,2)/2)),0);
Cm:=If(Xc=4 AND Cm>0,Max(L,Min(If(Tr<0,H,O),Cm)),Cm);
Cm:=If(Xc=3 AND Cm>0,C,If(Xc=1 AND Xo<5,Ref(Cm,-1),Cm));
Cm:=If(Xc=1 AND Cm>0 AND Xo<5,O,Cm);
Pd:=Pd<99 AND Xb AND BarsSince(Ref(Tr,-1)=0)=Pd;
Cx*Alert(Tr<>0,2);Cx*Pf*Alert(Tr<>0,2);Cx*Lf*Alert(Tr<>0,2);
If(Cm>0,Cm,If(Cp>0,Cp,If(Xs>0 AND Xo=5,X,If(Pd>0,C,0))));

{Trade Stop SE} {V3.3}


No:=Input("Entry - exit price 1=O 2=C 3=H 4=L 5=Price ##",11,55,22);
Cp:=Input("Capital, entry - exit delays $ ## ",0,100033,10000);
Cm:=Input("Entry - exit costs $$",0,9999,3030);
Xc:=Input("Stop timing 1=C/O+ 2=C/C 3=Stop/C 4=Stop ##" ,11,44,22);
Ls:=Input("Targets, profit - loss 99=N/A %%",0,9999,2010);
Pd:=Input("Timed exit 99=N/A ##",1,99,98);
N:= Fml("PS Fractal Exit")>0;
Ns:=Fml("PS Fractal Exit");
X:= Fml("PS Fractal Entry")>0;
Xs:=Fml("PS Fractal Entry");
Xo:=No-10*Int(No/10);No:=Int(No/10);
Xa:=Xc-10*Int(Xc/10);Xc:=Int(Xc/10);
Nd:=LastValue(Int(0.1+Frac(Cp/100)*10));
Xd:=LastValue(Cp-Int(Cp/10)*10);
Cx:=Cm-100*Int(Cm/100);Cm:=Int(Cm/100);Cp:=Int(Cp/100)*100;
Pt:=Frac(Ls/100);Ls:=Int(Ls/100)/100;
N:=N AND Alert(N=0,2);X:=X AND Alert(X=0,2);
N:=If(Nd=0,N,Alert(N,Nd+1) AND Alert(N,Nd)=0);
N:=If(N>0,If(No=1,O,If(No=3,H,If(No=4,L,C))),0);
N:=If(No=5,If(Ns>0,Min(H,Ns),0),N);
X:=If(Xd=0,X,Alert(X,Xd+1) AND Alert(X,Xd)=0);
X:=If(X>0,If(Xo=1,O,If(Xo=3,H,If(Xo=4,L,C))),0);
X:=If(Xs>0 AND Xo=5,Min(H,Xs),X);
Pf:=1-((Cp*Ls+Cm+Cx)/(Cp-Cm));
Lf:=Max(1,1+((Cp*Pt-Cm-Cx)/(Cp-Cm)));
Tr:=If(PREV=0,If(N>0 AND X=0 AND (No=2 OR
(If(Xa<3,C,H)<Lf*N AND If(Xc<3,C,L)>Pf*N)),N,0), If(X>0
OR (BarsSince(PREV=0)=Pd AND Pd<>99) OR

296
(If(Xa<3,C,H)>=Lf*PREV AND Ls<>.99) OR
(If(Xc<3,C,L)<=Pf*PREV AND Pt<>.99),0,PREV));
Tr:=If(Alert(Tr>0,2)=0 AND N>0 AND
(((If(Xa<3,C,H)>=Lf*N OR If(Xc<3,C,L)<=Pf*N)
AND No<>2) OR (X>0 AND Nd+Xd<1 AND No<>2 AND
Xo>1 AND (Max(No,Xo)>4 OR No<>Xo))),-N,Tr);
Xb:=(Tr=0 AND Alert(Tr>0,2)) OR (Tr<0 AND Alert(Tr=0,2));
Cx:=ValueWhen(1,Cum((N+Ns+X+Xs)>-1)=1 OR Tr<>0,Abs(Tr));
Cp:=If(Xb,If(Xa<3 AND C>=Cx*Lf,C, If(Xa>2 AND H>=Cx*Lf,Cx*Lf,0)),0);
Cp:=If(Cp>0,If(Cp>=.5,.01+PREC(Cp,2),If(Cp<.1,
.001+PREC(Cp,3),.005+PREC(Cp*2,2)/2)),Cp);
Cp:=If(Xc=4 AND Cp>0,Min(H,Max(If(Tr<0,L,O),Cp)),Cp);
Cp:=If(Xa=3 AND Cp>0,C,If(Xa=1 AND Xo<5,Ref(Cp,-1),Cp));
Cp:=If(Xa=1 AND Cp>0 AND Xo<5,O,Cp);
Cm:=If(Xb,If(Xc<3 AND C<=Cx*Pf,C,If(Xc>2 AND L<=Cx*Pf,Cx*Pf,0)),0);
Cm:=If(Cm>0,If(Cm>=.5,.01+PREC(Cm,2),If(Cm<.1,
.001+PREC(Cm,3),.005+PREC(Cm*2,2)/2)),Cm);
Cm:=If(Xa=4 AND Cm>0,If(Tr<0,Cm,Min(O,Cm)),Cm);
Cm:=If(Xc=3 AND Cm>0,C,If(Xc=1 AND Xo<5,Ref(Cm,-1),Cm));
Cm:=If(Xc=1 AND Cm>0 AND Xo<5,O,Cm);
Pd:=Pd<99 AND Xb AND BarsSince(Ref(Tr,-1)=0)=Pd;
Cx*Alert(Tr<>0,2);Cx*Pf*Alert(Tr<>0,2);Cx*Lf*Alert(Tr<>0,2);
If(Cm>0,Cm,If(Cp>0,Cp,If(Xs>0 AND Xo=5,Xs,If(Pd>0,C,0))));

So much for quick fixes. My Thanks to David Hobbs for letting me know that
my 'Nd' variable fix was also flawed. I'll try again.

If you have version 3.X Trade Equity or Trade Stop formulas with an 'Nd' that looks
like either of the lines below,
Nd:=LastValue(Int(Frac(Cp/100)*10));
or
Nd:=LastValue(Int(Frac(Cp/99)*10));
then it should be changed to
Nd:=LastValue(Int(0.1+Frac(Cp/100)*10));

Hopefully this will fix the problem once-and-for-all.

LATCHES

Using latches (or flags as I prefer to call them) in MetaStock is a simple, convenient
and accurate way of remembering certain conditions or events. Many MS users find
these concepts are difficult to grasp and apply to their own formulas. This post is an
attempt to explain the various uses and nuances of latches, but it is by no means all
there is to say on the matter.

297
A ‘latch’ is a device that stores and holds, or remembers, a particular event or
condition. A ‘binary latch’ can be set to one of two values (normally zero and one but
not necessarily), while a ‘price latch’ can be set to virtually any value one could think
of. Each has its own advantages and disadvantages as we shall discover.

In the following discussion ‘one’ is interchangeable with ‘true’ ‘on’, and ‘zero’ with
‘false’ or ‘off’.

Binary Latch Description

Example 1 is the simplest form of a latch. It requires two different signals to operate –
a ‘set’ signal, and a ‘reset’ signal. You could think of these signals as the ‘on’ switch
and the ‘off’ switch. By using the BarsSince() function we are able to decide which
signal occurred most recently, and therefore whether the current state of the latch
should be ‘on’ or ‘off’. MetaStock processes a chart from the first bar on the left to
the last bar on the right. And this means that the latch condition is checked and
updated as each new bar is processed.

{Example 1}
N:=Fml("set signal");
X:=Fml("reset signal");
BarsSince(N)<BarsSince(X);

One problem to be overcome with this simple code is that the output line (using
BarsSince) can have an extended invalid signal period. In other words it will return
N/A instead of a legitimate value. This N/A period will extend until the ‘set’ signal is
true and the ‘reset’ signal is valid. The extended N/A problem can be addressed by
adding an ‘initialized’ variable into the output line. I normally use ‘I’ to name this
variable, and its purpose is to inform any code after ‘N’ and ‘X’ that the set and reset
signals are valid – i.e. are not returning N/A. In a latch configuration it also serves to
provide ‘fake’ set and reset signals that provide a specific start-of-signal bar for the
latch.

It is also convenient to name the output line variable since additional code usually
follows. Example 2 is a complete binary latch and as such it can store only two values
– zero and one.

{Example 2}
N:=Fml("set signal");
X:=Fml("reset signal");
I:=Cum(N+X>-1)=1;
Tr:=BarsSince(I OR N)<BarsSince(I OR X);
Tr;

The ‘I’ variable confuses many people. It will be true (one) for the first bar when both
set and reset signals are valid, and false (zero) for every bar thereafter. Until both set
and reset signals are valid it will be invalid too, and return N/A. ‘I’ being true for one
bar provides the ‘fake’ set and reset signals used to kick the latch into action. Notice
that the construction if ‘I’ is not concerned with actual values, but whether or not ‘N’
and ‘X’ are VALID. The sum of the two cannot be tested as being greater than –1

298
until both return a value of at least zero (hence both are valid). Since ‘N’ and ‘X’ are
binary signals (zero or one), by definition they will never be less than zero. The
Cum() count equal to one ensures that this signal is true for the first valid bar only,
and false after that.

It is possible to assign values other than zero and one to the latch output, but be
warned that this latch can’t be used to store prices. The reason is that multiple set
signals will allow the stored price to change. However the If() function can be used to
select the two values that that latch can swing between.

{Example 3}
N:=Fml("set signal");
X:=Fml("reset signal");
I:=Cum(N+X>-1)=1;
Tr:=If(BarsSince(I OR N)<BarsSince(I OR X),1,0);
Tr;

Now that we are able to assign different values to the ‘Tr’ variable one needs to be
aware that not all methods of making ‘Tr’ are equal.

Tr:=If(BarsSince(I OR N)<BarsSince(I OR X),1,0);


Is functionally identical to
Tr:=If(BarsSince(I OR N)>=BarsSince(I OR X),0,1);
But neither is the same as
Tr:=If(BarsSince(I OR N)>BarsSince(I OR X),0,1);

The difference is in the use of “=” with “>” or “<” symbols. Written the wrong way
the section of the flag prior to the first ‘set’ signal will be true instead of false. This
may be only a small point but to my mind it is still the difference between right and
wrong.

Typical Signal Timing for Binary Latch.

High is ‘one’, low is ‘zero’,

__ _
__/ \_____/\_______________/ \__ set (N)
__
N/A ___/\____________/ \________ reset (X)

N/A \____________________________ Initialization (I)


_________ ____
N/A _______/ \______/ latch (Tr)

Price Latch Description

A PREV version of the latch offers more options for MS coding because it can
remember a user determined value. This value can then be accessed from within the

299
latch to manage a number of resets that could be related to set timing. The one down
side to using PREV is that it is resource hungry and it will significantly slow the
execution time of any code using it. Each additional PREV increases the resource
burden.

{Example 4}
N:=Fml("set signal");
X:=Fml("reset signal");
Tr:=If(N,1,If(X,0,PREV));
Tr;

Example 4 is the simplest form of a PREV based latch, and here it is still being used
to give a binary result because it has no way of discriminating between the first and
subsequent ‘set’ signals. By also checking the previous state of ‘Tr’ we can ensure
that only the FIRST entry signal and bar is used to decide what value to store in the
latch. Notice that the ‘I’ variable is not used here. It is not needed to provide a starting
point, and neither is there any problem (other than lack of skill) in setting the correct
polarity of the output signal ‘Tr’.

I suggest that all PREV variables be named – I have had some unpredictable results
when using PREV as an unnamed output line.

{Example 5}
N:=Fml("set signal");
X:=Fml("reset signal");
Tr:=If(PREV=0,If(N,CLOSE,0),If(X,0,PREV));
Tr;

Example 5 has expanded the role of the latch to that of a true price latch, and here it is
storing the CLOSE from the initial ‘set’ bar. The only time the latch will set to
something other than zero is when the previous bar of the latch was zero (latch not
active) and the ‘N’ variable (set) is active for the current bar. When these conditions
are not both met the latch can either retain its previous value, or it can reset to zero
when the ‘X’ variable is active.

From here it is an easy step to creating a latch that can monitor its own value and be
self-resetting when specific latch-set related criteria is met. Example 6 shows how to
rest the latch when the closing price rises to 20% above that when the latch was set.
Notice in this example that the reset signal is ‘Ored’ with the price condition to reset
the latch (reset signal OR price condition). Either condition true will force a reset.

{Example 6}
N:=Fml("set signal");
X:=Fml("reset signal");
Tr:=If(PREV=0,If(N,CLOSE,0),If(X OR C>=PREV*1.2,0,PREV));
Tr;

The independent reset signal may well be unnecessary with this type of latch when
both positive and negative movements can be checked against the stored value, as in
Example 7 below.

300
{Example 7}
N:=Fml("set signal");
Tr:=If(PREV=0,If(N,CLOSE,0),If(C>=PREV*1.2 OR C<=Prev*0.9,0,PREV));
Tr;

I hope this explanation has cleared away some of the mystery regarding the
construction and potential use of binary and price latches. A binary latch forms the
heart of all my ‘Trade Equity’ indicators, and a price latch fills a very similar role in
all of my ‘Trade Stop’ indicators.

Roy Larsen
rlarsen@man.quik.co.nz

301
TradeStation Code

SLOWKCLASSIC

as some don't seem to have the function SlowKClassic, which is


referenced by the DivFinder i posted yesterday, here it is.

{********************************************************}

{*******************************************************************
Description : This Function returns Slow Stochastic %K Classic
Provided By : Omega Research, Inc. (c) Copyright 1999
********************************************************************}

Inputs: FastKLen(NumericSimple), Length(NumericSimple);

SlowKClassic = Average(FastK(FastKLen), Length);

{************************************************************}

MACD HISTOGRAM
-------------------------------------------
{MACD red/green Hist edited from TS4}
{MaxBarsBack set to 1}

inputs: FastMA(12),SlowMA(26),MacdMA(9);

Plot1(MACD(Close,FastMA,SlowMA),"MACD");
{green line}
Plot2(XAverage(MACD(Close,FastMA,SlowMA),MacdMA),"MACDAvg"); {red
line}

plot3(0,"MA up"); {green hist}


plot4(0,"MA dn"); {red hist <======reset plot values to 0 before
plotting
the MACDD values (erases last bar value)}

value1=MACD(Close,FastMA,SlowMA)-
(XAverage(MACD(Close,FastMA,SlowMA),MacdMA));

{Note that the MACD calculation here is not optimized for speed. It
should be... }

if value1>value1[1] then begin


plot3(value1,"MA up"); { <=========plots according to MACD climbing}

302
end else begin
plot4(value1,"MA dn"); { <=========plots according to MACD falling}

end;

HIGH OF TODAY

Hi

Try this :

value1 = highd(0) ;
value2 = lowd(0) ;
value3 = (value1 + value2)/2 ;

plot1(value1,"HIGH");
plot2(value2,"LOW") ;
plot3(value3,"MID") ;

ensure plot type set to point

Cheers Stuart

From: kjh129@runbox.com
To: omega-list@eskimo.com
Subject: EL help please.
Date: Tue, 24 Apr 2001 21:08:29 GMT

Good day all..

I am trying to create this indicator in TS4 for the currentsession only.


For some reason, my code is not working. I have written it as follows.

plot1(TrueHigh, "HighofToday");
Plot2(((High+low) /2), "Mid");
Plot3(TrueLow, "LowofToday");

I am simply looking to Plot the HighOfToday, the LowofToday, and the


midpoint between the high and the low of today. Would appreciate someone's
advice as i have gone through the manual already to no avail.. thankyou.

KJH

303
MACD CROSSOVER CHART

The following code was used to produce the two indicator lines shown
in the MACD crossover chart. The trades shown on the chart were
generated at the moment the two indicator lines crossed.

The default input parameters have been replaced with an asterisk (*).
We encourage you to find parameter values that best suits your
particular trading needs.
Note: FOR Supercharts 4 and TradeStation 4 ....
-----------------------------------------------------------------
Input: series(close),
len1(*), phase1(*),
len2(*), phase2(*),
len3(*), phase3(*);

value1 = JRC.JMA.MACD ( series, len1, phase1, len2, phase2 ) ;


value2 = jrc.jma.flex ( value1, len3, phase3 ) ;
plot1 ( value1, "" ) ;
plot2 ( value2, "" ) ;
-----------------------------------------------------------------

Note: FOR TradeStation 2000 and ProSuite 2000 ....


-----------------------------------------------------------------
Input: series(close),
len1(*), phase1(*),
len2(*), phase2(*),
len3(*), phase3(*);
value1 = JRC.JMA.MACD.2k ( series, len1, phase1, len2, phase2 ) ;
value2 = jrc.jma.flex.2k ( value1, len3, phase3 ) ;
plot1 ( value1, "" ) ;
plot2 ( value2, "" ) ;
-----------------------------------------------------------------

COLES’S RANGE

Indicator Cole's Pivot Daily

{ Uses yesterdays prices to plot todays Support - Resistance levels using


Daily Data }
Vars: Pivot(0);
Pivot = ((H+L+C)/3);
Plot1(Pivot[1],"Cole'sPivot");
*********************************

304
INDICATOR COLE'S RANGE DAILY

{ Indicator Cole's Range Daily }


Vars: CalcR2(0), CalcR1(0), CalcS1(0), CalcS2(0);
CalcR2 = ((H+L+C)/3) + (High - Low);
CalcR1 = ((H+L+C)/3) + (((H+L+C)/3) - Low);
CalcS1 = ((H+L+C)/3) - (High - ((H+L+C)/3));
CalcS2 = ((H+L+C)/3) - (High - Low);
Plot1(CalcR2[1],"R2");
Plot2(CalcR1[1],"R1");
Plot3(CalcS1[1],"S1");
Plot4(CalcS2[1],"S2");
************************

8 PERIOD DONCHIAN CHANNEL MID-POINT LINE

var: median8(0);
median8 = (highest(H,8) + lowest(L,8))*.5;
plot1(median8,"median8);

> I am looking for coding help. I want to calculate the 8 Period Donchian
> Channel Mid-point line.

INDICATOR SUPP-RESIS DAILY

{ Indicator Supp-Resis Daily }


{ Uses yesterdays prices to plot todays Support - Resistance levels for Daily Data }
{
Pivot = Daily (High plus Low plus Close) divided by 3
Supp1 = (Two times Pivot) minus daily high
Supp2 = Pivot minus (Resis1 minus Supp1)
Resis1 =(Two times Pivot) minus daily Low
Resis2 = Pivot plus (Resis1 minus Supp1)
}
Vars: Supp1(0), Supp2(0), Resis1(0), Resis2(0);
Resis2=((H+L+C)/3)+(((2*((H+L+C)/3))-Low)-((2*((H+L+C)/3))-High));
Resis1=((2*((H+L+C)/3))-Low);
Supp1=((2*((H+L+C)/3))-High);
Supp2=((H+L+C)/3)-(((2*((H+L+C)/3))-Low)-((2*((H+L+C)/3))-High));

Plot1(Resis2[1],"R2");
Plot2(Resis1[1],"R1");
Plot3(Supp1[1],"S1");

305
Plot4(Supp2[1],"S2");

Indicator Supp-ResisPivotDaily

{ Indicator Supp-ResisPivotDaily }
Vars: Pivot(0);
Pivot = ((H+L+C)/3);
Plot1(Pivot[1],"S-Rpivot");

Undefined

Value1 = Close + 0.088*Value1[6];


Value2 = Value1 - Value1[6] + 1.2*Value2[6] - 0.7*Value2[12];
D = Value2[12] - 2*Value2[6] + Value2;
Plot1(D,"D");

Undefined 2

Inputs: Stp1(0.14);
Vars: Top(0), Bot(0);

Top = High + Stp1;


Bot = Low - Stp1;
Condition1 = wspr(d1d3) > cotmom(2,5);
Condition2 = wspr(d1d3) < cotmom(2,5);
{......go short......} Condition3 = cotmom(2,5) crosses above wspr(d1d3);
{......go long.......} Condition4 = cotmom(2,5) crosses below wspr(d1d3);
Condition5 = cotmom(2,5) crosses above 0;
Condition6 = cotmom(2,5) crosses below 0;
Condition7 = Condition5 = True or Condition6 = True;

If Condition4 then begin {......go long.......}


Value1 = Bot;
If Condition7 then Value1 = Bot;
If Condition3 then Value1 = Top;
end;

If Condition3 then begin {......go short.......}


Value1 = Top;
If Condition7 then Value1 = Top;
If Condition4 then Value1 = Bot;
end;

If Condition1 then Plot1(Value1,"exitlong") {one colour}


else Plot2(Value1,"exitshort"); {different
colour}

Code doesn’t work but !!

306
ANDREW’S PITCHFORK

input: ABACline(true), Median(false), TL_Thick(1);


{ ======================================
This is my implementation of some aspects of Andrews Pitchforks. You are welcome
to use this code freely. You may redistribute it provided you include this comment
block, plus a description of any changes you make.

If you extend it, or adapt it to other uses, I'd appreciate a look at what you've
done. Thanks.

Gregory Wood
SwissFranc@worldnet.att.net

12/18/96 v1.0 - Initial distribution


01/08/96 v1.1 - Added median lines
01/15/96 v1.2 - Added TL_Thick, user-customizable colors (see "SET COLORS
HERE")
01/16/96 v1.3 - Removed projections to make room for up to 7 pitchforks

01/23/01 v1.3a- Fixed search algorithm -- would miss at times.


Drew missing Bar and got rid of extra length on one projection.
Made it work on upper or lower case. Clyde Lee

03/09/01 v1.3b- Add Option to not plot AB and AC Lines.


========================================}

{
SETUP

Set Plot1 and Plot2 to be large points.


Note that the trendlines use the default trendline settings

USAGE

Use the text tool to label swing high/lows with "A", "B" and "C", then refresh
the indicator (clicking "Status" twice causes the indicator to recalculate).
Be sure to put the label above the bar's high for a swing high, and below the
low for a swing low.

You can display other groups of points by using labels "Ax", "Bx" and "Cx",
where 'x' is 1, 2, or 3, e.g. "A3", "B3", "C3".

Note that you can use the pointer tool to move the points anytime.
Then to view the new Pitchfork, refresh the indicator.

Use Median to add median lines.

307
Set MyColor (below) to be the colors for each Pitchfork
}

if currentbar = 1 then begin { initialize control arrays }

array:abc[3](""); { The basic point labels }


abc[0] = "A";
abc[1] = "B";
abc[2] = "C";

array:nums[7](""); { The way to distinguish one series of points from another, A-B-
C, A1-B1-C1, etc }
nums[0] = "";
nums[1] = "1";
nums[2] = "2";
nums[3] = "3";
nums[4] = "4";
nums[5] = "5";
nums[6] = "6";

var: inums(7);

array: MyColor[7](0);
MyColor[0] = tool_blue; { <=========== SET COLORS HERE }
MyColor[1] = tool_red;
MyColor[2] = tool_yellow;
MyColor[3] = tool_cyan;
MyColor[4] = tool_green;
MyColor[5] = tool_white;
MyColor[6] = tool_magenta;
end;

array:dd[3,7](0),tt[3,7](0),vv[3,7](0),bb[3,7](0),hh[3,7](0);
array:fb[7,4](0),fv[7,4](0);
var: tft(0), fdd(0), fvv(0), ptt(0), pdd(0), pvv(0), fbb(0), pbb(0), pvv2(0);
var: ii(0), jj(0), mm(0);
var: handl(0), handlA(0), handlB(0), handlC(0), handlB1(0), handlC1(0), handlB2(0),
handlC2(0);
var: ss("");
var: y1(0), y2(0);

if currentbar = 1 then begin { examine all the text strings and save some info about
the ones we recognize }
handl = text_getfirst(2);
while handl >= 0 begin
ss = text_getstring(handl);
ss = UpperStr(ss);
for ii = 0 to inums - 1 begin
for jj = 0 to 2 begin { look for well-formed strings }

308
if ss = abc[jj] + nums[ii] then begin { save the item's date, time, value and handle
}
tt[jj,ii] = text_gettime(handl);
dd[jj,ii] = text_getdate(handl);
vv[jj,ii] = text_getvalue(handl);
hh[jj,ii] = handl;
end;
end;
end;
handl = text_getnext(handl,2); { IMPORTANT -- infinite loop if this is
missing! }
end;
end;

for ii = 0 to inums - 1 begin { check each series... }

for jj = 0 to 2 begin { check each point }


if time = tt[jj,ii] and date = dd[jj,ii] then begin { we've found a selected point }
bb[jj,ii] = currentbar; { remember where we found it }
if vv[jj,ii] > c then begin { move the label above the bar and center it }
vv[jj,ii] = h;
Text_SetLocation(hh[jj,ii],text_GetDate(hh[jj,ii]),text_GetTime(hh[jj,ii]),h);
Text_SetStyle(hh[jj,ii],2,1);
end
else begin { move the label below the bar and center it }
vv[jj,ii] = l;
Text_SetLocation(hh[jj,ii],text_GetDate(hh[jj,ii]),text_GetTime(hh[jj,ii]),l);
Text_SetStyle(hh[jj,ii],2,0);
end;

plot1(vv[jj,ii],"Selection"); { show the user which point we used for the


calculations }

if jj = 2 then begin { we're at the third point, generally the Cx }


If ABACline then begin
handl = TL_New(dd[0,ii],tt[0,ii],vv[0,ii],dd[1,ii],tt[1,ii],vv[1,ii]);
TL_SetExtLeft(handl,false);
TL_SetExtRight(handl,false);
TL_SetColor(handl,MyColor[ii]);
TL_SetSize (handl,TL_Thick+1);

handl = TL_New(dd[0,ii],tt[0,ii],vv[0,ii],dd[2,ii],tt[2,ii],vv[2,ii]);
TL_SetExtLeft(handl,false);
TL_SetExtRight(handl,false);
TL_SetColor(handl,MyColor[ii]);
TL_SetSize (handl,TL_Thick+1);
End;
fbb = bb[1,ii] / 2 + bb[2,ii] / 2;
fvv = vv[1,ii] / 2 + vv[2,ii] / 2;
pvv = TLValue(vv[0,ii],bb[0,ii],fvv,fbb,currentbar);

309
{DRAW CENTERLINE}
handlA = TL_New(dd[0,ii],tt[0,ii],vv[0,ii],date,time,pvv);
TL_SetExtRight(handlA,TRUE);
TL_SetColor(handlA,MyColor[ii]);
TL_SetSize (handlA, TL_Thick);

{ show the related trident channel }


pvv = TLValue(vv[1,ii],bb[1,ii],fvv+vv[1,ii]-vv[0,ii],fbb+bb[1,ii]-
bb[0,ii],currentbar);

handlB = TL_New(dd[1,ii],tt[1,ii],vv[1,ii],date,time,pvv);
TL_SetExtRight(handlB,true);
TL_SetColor(handlB, MyColor[ii]);
TL_SetSize(handlB, TL_Thick);
if Median then begin { save for later }
handlB1 = TL_New(dd[1,ii],tt[1,ii],vv[1,ii],date,time,pvv);
TL_SetExtRight(handlB1,true);
TL_SetColor(handlB1, MyColor[ii]);
TL_SetSize(handlB1, TL_Thick);
handlB2 = TL_New(dd[1,ii],tt[1,ii],vv[1,ii],date,time,pvv);
TL_SetExtRight(handlB2,true);
TL_SetColor(handlB2, MyColor[ii]);
TL_SetSize(handlB2, TL_Thick);
end;
pvv = TLValue(vv[0,ii]-(fvv-vv[2,ii]),bb[0,ii]+(bb[2,ii]-
fbb),vv[2,ii],bb[2,ii],bb[1,ii]);
handlC = TL_New(dd[1,ii],tt[1,ii],pvv,date,time,vv[2,ii]);
TL_SetExtRight(handlC,true);
TL_SetColor(handlC, MyColor[ii]);
TL_SetSize(handlC, TL_Thick);

value99=TL_New(dd[1,ii],tt[1,ii],vv[1,ii],dd[2,ii],tt[2,ii],vv[2,ii]);
TL_SetExtLeft(Value99,false);
TL_SetExtRight(Value99,false);
TL_SetColor(Value99,MyColor[ii]);
TL_SetSize (Value99, TL_Thick+1);

if Median then begin { save for later }


handlC1 = TL_New(dd[1,ii],tt[1,ii],pvv,date,time,vv[2,ii]);
TL_SetExtRight(handlC1,true);
TL_SetColor(handlC1, MyColor[ii]);
TL_SetSize(handlC1, TL_Thick);
handlC2 = TL_New(dd[1,ii],tt[1,ii],pvv,date,time,vv[2,ii]);
TL_SetExtRight(handlC2,true);
TL_SetColor(handlC2, MyColor[ii]);
TL_SetSize(handlC2, TL_Thick);
end;

310
if Median then begin { sorry these are hard-coded... you know what they say
about quick + dirty! }

{ show the median lines }


y1 = TL_GetValue(handlB, dd[1,ii], tt[1,ii]);
y2 = TL_GetValue(handlA, dd[1,ii], tt[1,ii]);
TL_SetBegin(handlB1, dd[1,ii], tt[1,ii], (y1 + y2) / 2);
y1 = TL_GetValue(handlB, dd[2,ii], tt[2,ii]);
y2 = TL_GetValue(handlA, dd[2,ii], tt[2,ii]);
TL_SetEnd(handlB1, dd[2,ii], tt[2,ii], (y1 + y2) / 2);

y1 = TL_GetValue(handlB, dd[1,ii], tt[1,ii]);


y2 = TL_GetValue(handlA, dd[1,ii], tt[1,ii]);
TL_SetBegin(handlB2, dd[1,ii], tt[1,ii], y1 + y1- (y1 + y2) / 2);
y1 = TL_GetValue(handlB, dd[2,ii], tt[2,ii]);
y2 = TL_GetValue(handlA, dd[2,ii], tt[2,ii]);
TL_SetEnd(handlB2, dd[2,ii], tt[2,ii], y1 + y1 - (y1 + y2) / 2);

y1 = TL_GetValue(handlC, dd[1,ii], tt[1,ii]);


y2 = TL_GetValue(handlA, dd[1,ii], tt[1,ii]);
TL_SetBegin(handlC1, dd[1,ii], tt[1,ii], (y1 + y2) / 2);
y1 = TL_GetValue(handlC, dd[2,ii], tt[2,ii]);
y2 = TL_GetValue(handlA, dd[2,ii], tt[2,ii]);
TL_SetEnd(handlC1, dd[2,ii], tt[2,ii], (y1 + y2) / 2);

y1 = TL_GetValue(handlC, dd[1,ii], tt[1,ii]);


y2 = TL_GetValue(handlA, dd[1,ii], tt[1,ii]);
TL_SetBegin(handlC2, dd[1,ii], tt[1,ii], y1 + y1 - (y1 + y2) / 2);
y1 = TL_GetValue(handlC, dd[2,ii], tt[2,ii]);
y2 = TL_GetValue(handlA, dd[2,ii], tt[2,ii]);
TL_SetEnd(handlC2, dd[2,ii], tt[2,ii], y1 + y1 - (y1 + y2) / 2);
end;
end;
end;
end;
end;

E-MINI WITH MONTE CARLO

{ EasyEmini A simple short-term e-mini breakout system to illustrate the use of


Monte Carlo simulation for position sizing. System: Buy at a fraction of yesterday's
range from yesterday's high. Hold 1 day then look to exit on the first profitable open.
Use a fixed money management stop (nominally $1000 in the e-mini). WARNING:
This system looks ahead one day to the next day's open to decide whether to exit the

311
open position. Consequently, the system never executes on the last bar of data on the
chart. This means that the entry order for the next day will not appear in the
TradeStation Tracking Center. ATTENTION TRADESTATION 2000i USERS This
system includes a call to function MonteCarlo, which performs Monte Carlo
simulation for position sizing. MonteCarlo only works in TradeStation 2000i because
it uses built-in function Random, which is new to 2000i. I have commented out the
call to MonteCarlo so that this system will work properly for TradeStation 4.0 users.
If you are a TradeStation 2000i user, you can download function MonteCarlo for free
from my web site (address below). Remove the comment braces {..} from the call to
the line below that begins "Value1 = ...". This will enable the call to MonteCarlo. The
MonteCarlo code records the profits and losses from the trading system and generates
random sequences of the trades. For each sequence, it calculates the return and
drawdown assuming a fixed percent of the account is risked on each trade. The output
is the probability that with a given account size and risk percentage you can meet
given rate of return and drawdown goals. For example, it might calculate the
probability that you can achieve a rate of return of 50% with 30% drawdown by
risking 10% on each trade. I have developed a version of MonteCarlo with additional
functionality and several input and output options that will work with either
TradeStation 2000i or 4.0. This version can be purchased on my web site. Copyright
2001 Breakout Future www.BreakoutFutures.com mrb@BreakoutFutures.com }
Input: ASize (30000), { account size, $ } RetGoal (50), { rate of return goal, %}
DDGoal (30), { max closed out trade drawdown, % } RiskPer (10), { percentage risk
per trade } EntFrac (0.75), { multiple of prior day's range for entering } MMStop
(1000), { money management stop, $ } NRand (1000); { number of random
sequences } Var: EntPr (0), { Entry target price } XitPr (0), { mm stop exit price }
TrRisk (0); { trade risk, $ } TrRisk = MMStop; { Entry conditions } EntPr = H +
EntFrac * (H - L); If C C[1] then Buy next bar at EntPr Stop; { Exit conditions }
Exitlong("MMStop") next bar at EntryPrice - MMStop/BigPointValue stop; If
BarsSinceEntry = 1 and open of next bar EntryPrice then ExitLong("ProfOpen") next
bar at market; { Perform Monte Carlo analysis: MonteCarlo only works in
TradeStation 2000i } {Value1 = MonteCarlo(ASize, RetGoal, DDGoal, RiskPer,
TrRisk, NRand); }

Monte Carlo Function

{ User function: MonteCarlo Monte Carlo simulation for position sizing. This
function records the profits and losses from the trading system that calls it and
generates random sequences of the trades. For each sequence, it calculates the return
and drawdown assuming a fixed percent of the account is risked on each trade. The
result is the probability that with a given account size and risk percentage you can
meet given rate of return and drawdown goals. For example, it might calculate the
probability that you can achieve a rate of return of 50% with 30% drawdown by
risking 10% on each trade. ATTENTION TRADESTATION 4.0 USERS Because this
function calls the built-in function Random, which is new to TradeStation 2000i, this
function will not work in TradeStation 4.0. I have developed a version of MonteCarlo
with additional functionality and several input and output options that will work with
either TradeStation 2000i or 4.0. This version can be purchased on my web site.
Copyright 2001 Breakout Future www.BreakoutFutures.com
mrb@BreakoutFutures.com } Input: ASize (NumericSimple), { account size, $ }
RetGoal (NumericSimple), { rate of return goal, %} DDGoal (NumericSimple), {

312
max closed out trade drawdown, % } RiskPer (NumericSimple), { percentage risk per
trade } TrRisk (NumericSeries), { risk for current trade, $ } NRand (NumericSimple);
{ number of random sequences } Array: Trades[200](0), { Trades, $ (win +; loss -) }
TrRisks[200](0), { trade risks, $ (+) } RandNums[200](0), { array of random numbers
} RandIndx[200](-1); { randomly chosen indices for trade array } Var: NTrades (0), {
Number of trades } iSeq (0), { sequence number } MaxNum (0), { max number left in
random number array RandNums } iMax (0), { index (location) of MaxNum in array
RandNums } NCon (0), { number of contracts } Equity (0), { account equity }
NewEquity (0), { account equity } EqtyHigh (0), { highest equity } DD (0), { closed
trade drawdown } DDmax (0), { worst case closed trade drawdown } PReturn (0), {
percent return } AveRet (0), { average percent return } ProbRet (0), { probability of
return goal } ProbDD (0), { probability of drawdown goal } ProbComb(0), {
probability of return & DD goals } ii (0), { loop counter } jj (0), { loop counter } k
(0); { loop counter } { Collect profit/loss and risk } If TotalTrades NTrades then
Begin If TotalTrades - NTrades MaxNum then Begin MaxNum = RandNums[jj];
iMax = jj; end; end; RandIndx[ii] = iMax; { record location of max number }
RandNums[iMax] = -1; { "remove" max number from array } end; { Calculate
account balance and drawdown for current sequence of trades } Equity = ASize;
EqtyHigh = Equity; DDmax = 0; For ii = 0 to NTrades - 1 Begin NCon =
IntPortion(RiskPer/100 * Equity/TrRisks[RandIndx[ii]]); NewEquity = Equity +
NCon * Trades[RandIndx[ii]]; { Calculate closed trade percent drawdown } If
(NewEquity EqtyHigh) then EqtyHigh = NewEquity else Begin DD = 100 *
(EqtyHigh - NewEquity)/EqtyHigh; if (DD DDmax) then DDmax = DD; end; Equity
= NewEquity; end; { for ii } PReturn = 100 * (Equity - ASize)/ASize; { Accumulate
results for probability calculations } AveRet = AveRet + PReturn; if (PReturn =
RetGoal) then ProbRet = ProbRet + 1; if (DDmax <= DDGoal) then ProbDD =
ProbDD + 1; if (PReturn = RetGoal and DDmax <= DDGoal) then ProbComb =
ProbComb + 1; End; { for iSeq } { Calculate probabilities by dividing sums by
number of sequences } AveRet = AveRet/NRand; ProbRet = 100 * ProbRet/NRand;
ProbDD = 100 * ProbDD/NRand; ProbComb = 100 * ProbComb/NRand;
MessageLog("RiskPer=", RiskPer:5:1," RetGoal=", RetGoal:5:1," DDGoal=",
DDGoal:5:1, " ProbRet=",ProbRet:5:1," ProbDD=",ProbDD:5:1," ProbComb=",
ProbComb:5:1); MessageLog("Average Return = ", AveRet:6:2); end; MonteCarlo =
1;

HURST EXPONENT

{
*********************************************************************
**

Function : Hurst

Last Edit : 3/3/01

Provided By : Bob Fulks

Description : Calculates the Hurst Coefficient based upon the paper

313
by J. Orlin Grabbe at <http://www.aci.net/kalliste/chaos7.htm>

*********************************************************************
***}

Inputs: Len(Numeric);
Vars: Mean(0), j(0), k(1.253314), SumSqr(0), Scale(0), MaxY(0),
MinY(0), Rng(0);
Arrays: X[100](0), Y[100](0);

Mean = Average(C, Len);


SumSqr = 0;
for j = 0 to Len - 1 begin
X[j] = C[j] - Mean;
SumSqr = SumSqr + X[j] * X[j];
end;
Scale = SquareRoot(SumSqr / Len);
Y[0] = X[0];
MaxY = X[0];
MinY = X[0];
for j = 1 to Len - 1 begin
Y[j] = Y[j - 1] + X[j];
if Y[j] > MaxY then MaxY = Y[j];
if Y[j] < MinY then MinY = Y[j];
end;
Rng = MaxY - MinY;
Hurst = Log(Rng/(k * Scale)) / Log(Len);

ERGOTIC CSI

{Format: Ergotic_CSI(r)
SinglaLine(r); }

Inputs: r(32), Zeroline(0);

Value1 = CSI(r, 5, 1);

Value2 = XAverage(CSI(r, 5, 1), 5);

Plot1(Value1, "ErgCSI");

Plot2(Value2, "SigLin");

Plot3(ZeroLine, "Zero");

314
ERGOTIC MACD

{Format: Ergotic_MACD(r)
SignalLine(r) }

Inputs: r(32), ZeroLine(0);

Value1 = MACD(Close, r, 5);

Value2 = XAverage(MACD(Close, r, 5), 5);

Plot1(Value1, "ErgMACD");
Plot2(Value2, "SigLin");
Plot3(ZeroLine, "Zero");

315
AIQ How To’s

ENTRY & EXIT

Next, there are days where the exit combination will not properly work. NOTE: This
applies only to those entry days where the entry AND exit happen on the same day.
In other words, where the date of entry is an outside day. As an example, take a look
at IBM on 8/05/99.

You have no idea whether your entry was triggered first and then the stock fell and
triggered your stop loss and then went up again, OR it fell first before you got in, then
went up and triggered your entry and then just stayed up without triggering your the
stop loss. NOTE AGAIN: This applies to the entry day ONLY.

SIDE NOTE: Don't pay attention to the Entry Date and Exit Date columns of the
backtest report under "Positions". Entry Date shows 1 day ahead of actual entry date,
and Exit Date shows 2 days ahead of actual exit date.

!!========================================================
Allworks if setdate(1) and (put your final rule here) and resetdate() and entrytrigger.

entrytrigger if [high] >= val([high],1) + 0.125.


entryprice is max(val([high],2) + 0.125, val([open],1)).

exittrigger if setdate(1) and [low] <= val([low],1) - 0.125 and resetdate().


exitprice is min(val([low],3) - 0.125 , val([open],2)).
!!========================================================

Point & Figure

Another helpful idea is to double click on the P&F indicator and change the
colors. I have mine set to upside black and down side dayglo green. Much
easier to see. Try several colors and find the ones you like.

Vance

Try setting your printer to draft and black print


> only and after "Z ing" the
> P$F print. It is much more legible then
>
> Vance

----- Original Message -----


From: "Joe Gruender Jr." <Newcyber7@yahoo.com>

316
To: <aiq@yahoogroups.com>
Sent: Friday, April 13, 2001 8:16 PM
Subject: [aiq] Another Point & Figure Question

> I have used the "Z" zoom feature to view point &
> figure formations. However, in many cases, this is
> still too small. Is there a way to zoom in even more
> since I am really interested in the most recent 5 or
> 10 columns, not the entire 30 to 50 column view? Or
> is there a way to spread out the point & figure
> information like you can do on the price chart
> information?
>
> Thanks, Joe
>

STOPS IN EDS

I made some assumptions since you didn't specify how much higher or lower should
the stops be placed for entry and exit. So I assumed a 1/8 point entry/exit stop. You
can change this number to your liking. Next, there are days where the exit
combination will not properly work. NOTE: This applies only to those entry days
where the entry AND exit happen on the same day. In other words, where the date of
entry is an outside day. As an example, take a look at IBM on 8/05/99. You have no
idea whether your entry was triggered first and then the stock fell and triggered your
stop loss and then went up again, OR it fell first before you got in, then went up and
triggered your entry and then just stayed up without triggering your the stop loss.

NOTE AGAIN: This applies to the entry day ONLY. SIDE NOTE: Don't pay
attention to the Entry Date and Exit Date columns of the backtest report under
"Positions". Entry Date shows 1 day ahead of actual entry date, and Exit Date shows 2
days ahead of actual exit date.

!!========================================================
Allworks if setdate(1) and (put your final rule here) and resetdate() and entrytrigger.

entrytrigger if [high] >= val([high],1) + 0.125.

entryprice is max(val([high],2) + 0.125, val([open],1)).

exittrigger if setdate(1) and [low] <= val([low],1) - 0.125 and resetdate().


exitprice is min(val([low],3) - 0.125 , val([open],2)).
!!========================================================

Bill S.

317
TRIGGERS BASED ON ENTRY PRICES

The basic coding for triggers based on entry prices is...


profittriger if [high] > {Position Entry Price} * 1.2.
profitprice is {Position Entry Price} * 1.2.

You can combine many exit triggers with the logic OR function, eg, with the triggers
from our previous stop-loss thread. > Bill S.

COUNT OF

! define the thing to look for

MacdCrossOver if ([MACD Osc] > 0 ) and ( Val([MACD Osc],1) < 0 ).

! see when it occurred occurredOn is ScanAny( MacDcrossOver, 20 ).

didOccur if occurredOn <> NoDate().


numDaysAgo is occurredOn then OffSetToDate(month(),Day(),Year()).

! define the second thing to look for UpDay if [Close] > [Open].
! count the number of times the 2nd thing happened, since the 1st thing occurred.
count is CountOf( UpDay, ^numDaysAgo + 1,0 ).
=====================================================

COMPARE TWO INDICES

Stan,

You will need to use TickerRule or TickerUDF functions


for DnRule1 to ever fire.

Each ticker in the list of symbols is processed


one at a time. This means NDXMKT was processed in one pass
and DJIA was processed in a different pass. Therefore, both
rules will never be TRUE at one time. A symbol can not both
be DJIA and NDXMKT as the same time.

Try adding a rule:

MyRule3 if TickerRule("DJIA",DojiAprox).
DnRule1 if MyRule1 and MyRule3.

Thanks,

318
Ron

> -----Original Message-----


> From: sjsolak@email.msn.com [mailto:sjsolak@email.msn.com]
> Sent: Thursday, May 03, 2001 3:13 PM
> To: aiq-eds@yahoogroups.com
> Subject: [aiq-eds] Signal based on two index
>
>
> I am trying to build an EDS that will give me a buy (or sell) signal
> when two indexs form a Doji on the same day.
>
> --------------------
> MyRule1 if DojiAprox and symbol()="NDXMKT".
> MyRule2 if DojiAprox and symbol()="DJIA".
> DnRule1 if MyRule1 and MyRule2.
> ----------------------
>
> I set three tabs, MyRule1, MyRule2 and DnRule1. I did a report on
> all with a summary for March 30, 2001.
> Got a Passed for DJIA in MyRule2 and a Passed for NDXMKT in MyRule1.
> But did not get anything in DnRule1.
>
> Maybe what I am trying to do is not possible. Can anyone help?
> Thanks.
> Stan

COLOUR STUDIES

• first, make sure you're on version 6.0


• then from charts, click the 'define studies' icon
• then 'on the top of the color studies window, type in the name of your eds file
• then hit the 'create new color study' button
• pick either 'price plot' or 'indicator' then cilck next
• keep following the prompts on the subsequent panels
• make sure you uncheck the 'dont show color studies' box on the first panel , i think the
default is to have this checked on, disabling the color studies

Colour chart

319
This is how I did my color studies:

Enter if (val([st esa],1) < val([it esa],1)) and [st esa] > [it
esa].
Exit if (val([st esa],1) > val([it esa],1)) and [st esa] < [it esa].

Put the rules in an EDS file and save it.


Open Chart.
Click on the multicolor icon and choose the saved EDS file.
Click “create new color study”.
Click radio button next to Price Plot (if this is what you want).
Click “next” and follow the instructions.
You should not be experiencing what you are describing unless “equal” exists. In this
case it will be the default color being displayed.

SetDate

Note that WMR must be a UDF and not a rule (because rules don't have values like
90-they are true or false) to use it the way you describe, eg

WMR is [stochastic].
Alert if WMR<90 and setdate(1) and WMR>90 and resetdate().

If you want WMR to be a rule, then

WMR if [stochastic]>90.
Alert if not WMR and setdate(1) and WMR and resetdate().

RECURSION

! EDS file to demonstate the various methods of computing a simple ESA.


! This file shows how NOT to crash EDS using recursive functions.
! you will also notice the results of all 3 esa calculations will be different. This is an
inherent problem with
! the calculation since it is dependent on where you start, and it is not a problem with
AIQ or EDS.

define UserDays 28.

close is [close].
alpha is 2/(1+UserDays).
beta is 1-alpha.

!This esa will crash EDS as it is recursive. However, it is the standard way of
computing many Indicators.
! Do not add this as a column UNLESS you want EDS to crash.

320
esacrash is (alpha * [close]) + (beta * valresult(esacrash,1)).

! This method will allow the recursion and not crash EDS. It will go back 240 days
! and start calculating the current days ESA value from there.

DaysInto is ReportDate() - RuleDate().


Stop if DaysInto >365.

! to stop the recursion we just return the value of [close] after we have looped 240
times into this routine.
stopesa is iff(stop,[close], myesa).
myesa is alpha * [close] + beta * valresult( stopesa, 1 ).

! Just a test of what the internal ESA function comes up with.


ExpAvg is ExpAvg(close,UserDays).

everything if 1.

321
MetaStock How To’s

CLEANING OUT UNWANTED STOCKS FROM METASTOCK

A fast method to clean out unwanted stocks from Metastock and also save them for
future viewing.
On your hard drive, create a series of folders and sub folders like your present
Metastock data system. In my case OLD_META_DATA/ALL01/A01,B01,C01 etc to
Z01. (Be sure no more than 450 stocks go in each folder when you do copy/deletions)
Open METASTOCK/Tools/DOWNLOADER and once in DOWNLOADER open
Tools/Copy .
Browse to the folder you wish to make deletions from.
In the "Copy Securities" window make sure you can read the Last Date column with
the Name column showing. If not,do not use the scroll bar but place the cursor in the
Name box at its RH end almost in the Symbol box and when your cursor turns into a
cross hold down the LH button on the mouse and drag it left thereby narrowing the
Name column till the Last Date column is visible.( This is also a good tip when
printing out Metastock reports that do not fit on the width of an A4 page, just reduce
the width of a column or eliminate it completely if it is not wanted on the print out.)
Hold down the Control key and highlight each Name you wish to delete. I go on the
Last Date column to find useless stocks. If you use the scroll bar to go down the list
be sure not to let go of the control key as you will lose all your previous selections.
When finished highlighting let go of control key and press copy. Browse to the new
folder you created, tick the "Delete Source Security" box and press OK. Old securities
gone out of current data base and saved for future reference. You can do hundreds in a
matter of minutes. If you want to ever see the old securities just alter the lead folders
names in explorer.
From Basil Holloway

LINKING METASTOCK UPDATES TO EXCEL FILES

As I understand your desire, it's to take data from a MetaStock file and use it to
update an Excel file. The way to have this update-process automatically done requires
for you to have an OLE-link capable object (chart or indicator) to be present. In
MetaStock this can be easy established by creating separate Charts for each security.
Follow and execute these steps below. Here I am using a single daily closing price as
object, for a simplified use of the Win 95's OLE program.

1. First make a new indicator Close Only :


-Start MetaStock and click the button for the Indicator Builder
-In Indicator Builder create a custom indicator named "Close Only"
(without the quotations) and in the formula field type CLOSE and click OK

2. To create a Close Only Template :


-Start the Win95-Explorer and create a new folder named OLE(which folder
will hold your Template and Charts used for this OLE) below your working
folder(that is holding your metastock files dat/dop/master/emaster etc.)
-Then switch back to MetaStock
-Open the by you desired security using Smart Charts as type

322
-Delete all other charts and all inner windows and all indicators that are open
in the current screen(=layout) except for the base securities' Price indicator
(the bar, line, sticks)
-Drag the newly created Close Only indicator down from the IB-Quick List
(from the small window in the middle at the top) and release it to have the newly
created indicator displayed in its own inner-window
-Now SAVE AS the current screen (with Template as the file type) using the
CloseOnly name(without a space) as the Template's name("CloseOnly.mwt")
-Close down MetaStock + Win95-Explorer

3. To create the separate Charts used for OLE :


-Start MetaStock (fresh again) and click New|Chart or click Open
-Click Apply Template (this action is always required prior to selecting a security)
and scroll to the OLE folder to apply the newly created CloseOnly Template
-On Opening of this New Chart the above mentioned Template's layout containing
the Price and the Close Only indicators will be displayed
-Now SAVE AS the current screen (with Chart as the file type) using the security's
name as the Charts' pointer name("SecurityX.mwc") to the newly created
OLE-folder
-Close Metastock

4. To create the OLE link from Metastock to an Excel spreadsheet :


-Start MetaStock (fresh again) and click Open
-Open the required security in the newly created OLE-folder
-Right-click to Select and click Copy to have the security's CloseOnly indicator
copied to the Clipboard
-Start Excel and check that the first cell at the top-left is been selected(=black
line bordered rectangle)
-Select the required cells by placing the mouse-pointer at the right corner of the
selected rectangle and click and press down the Left-mouse button and whilst
at the same time holding the mouse-button down, drag down this first column(A)
and release button until you have reached record row #999 and all of the
selected cells will be colered black(Note that this selection made, has to be
done in one(1) straight firm move down the column, eg a one single selection
has been made)
-Now let the mouse-pointer float on this blackened selection and Right-click to
choose Paste Special
-In the Paste Special's Dialog Window click the Paste Link radio-button and
choose CSV as file-type
-With plenty of system memory on board it will not take that long before the
Special Linked data is calculated and displayed (as the cell's contents), and
that the Link has been made
-Close and Save As the Excel file to the OLE folder(with standard XLS as file type)
with the security's name as the pointer name
-Each time now, that you Open this XLS-file again, automatically the Excel program
will have you prompted if you would to update the Link. Within the Excel program's
options (Tools|Options|Calculations or Edit|Link|Manual) you can pre-set this to
"manual" as well, but then you will have to click Edit|Link|Update Now to update
once the spreadsheet's above Linked cell selection entirely

323
A.
Note here that the more history is stored in your 'original' Metastock files, eg the
files the Chart uses as its base, the longer the column contents(displayed cells), the
longer it will take to calculate and also the more memory is being used, so you
will have to keep this 'history' as short as what can be possible for any fast results.

B.
Note here too that you can then apply the special instructions (mailed in a previous
mail to the List) to have the Linked cells' contents SPLIT UP over more cells in the
spreadsheet(s), so as to enable you to make calculations in Excel, eg using Excel's
cell linking(referencing) and formula language(the tiny editor) capabilities and/or
apply any of the other Excel program's features.

C.
Note here also that the above applies for MS6.x and Excel8.0(OfficePro97).

D.
To reverse this OLE linkage back into MetaStock , do not forget to create an
empty Inner Window first, prior to creating the Link.
In MS click Window|New Inner Window and then Right-click in this Inner Window
and
choose Paste Special|Paste Link (with CSV as file type). See MS-Help or MS-Manual
or Equis' Customer|Support Website for more detailed instructions.

suggested by Ton Maas, ms-irb@wxs.nl

324
DIFFERENT RESULTS IN TRADESTATION

You can try something like this. Create an indicator that computes the 14
> period RSI of 10 bars ago. The two ways of doing this are to put the [10]
> inside the function or outside the function. If they were the same the
> difference should be zero. Plot the following code in an indicator and
> look at the results in the debug window. You will see that early on, the
> difference is not zero but gets smaller over time. If you use TS4.0, you
> cannot use the Cleardebug function.
>
> if barnumber = 1 then cleardebug;
> Print( d:6:0, RSI(C[10],14) - RSI(C,14)[10]:5:5);

You are right, the 2 different calls give different results. This
is because the code uses an exponential moving average and the 2
different calls start calculating on different bars;
RSI(C[10],14) gives results 10 bars before RSI(C,14)[10]. The
difference in this case seems acceptable to me, but who knows
what issues lurk in other functions.

So I agree that back references should always be placed outside


the arguments of the function call.

325
SIGNAL REVIEW – UPSIDE

Vance,

Excellent! I must admit, I've used AIQ for 3-4 years and have never
worked with that particular report before. But it seems to be a really
good one to use for short-term trading. One good feature is that, with
two mouse-clicks, you can generate a list of stock on the report and
easily scroll through their daily charts in AIQ, looking for good
setups. Thanks for bringing this to my attention. I'm attaching a copy
of today's report for anyone not using AIQ and interested in seeing how
this feature works.

Bill

Vance Swindell wrote:

> I have been doing fair by selecting stocks from the Stock Reports =
> Signal Review upside. This signal has a fairly good record with some
> stocks reaching 83% in a few days, of course there losers too, but I
> watch moving averages and cut my loses quick and ride the ones that
> stay above my moving average. This report uses the ER signal and then
> posts a date when it has signal a buy using a price phase direction
> change. The report keeps 2 weeks info and one can track the results by
> scrolling down. Works so far for me. And it requires minimal
> studying and work, as Bill stated, some times I get in my on way and
> miss trades, because I'm trying to incorporate too many tech. and
> fundamentals. Vance

3 BAND RESEARCH SYSTEM

Here is research dept code for the bands that can be adjusted via inputs
for other securities.

Prosper

Inputs: Pcnt1(1.025),Pcnt2(.975),Offset(1);

326
vars:bandup(0),banddn(0),av(0);

av=average(c,21);
bandup=av*Pcnt1;
banddn=av*Pcnt2;var:

aa(0),bb(0),cc(0),dd(0);

if c > bandup and c[2]<bandup then value1=1;


if value1= 1 then begin plot4(H+offset,"break");
aa=aa+1;

Print(File("C:\xitami\root\mod\SPBand.txt"),d:6:0,", ",c:3:2,",
C>UpperBand",", ","L>MiddleBand, ",aa:0," Days");
print(d:6:0,", ",c:3:2,", C>UpperBand",", ","L>MiddleBand, ",aa:0,"
Days");end;
if l<=av then value1=0;
if l<=av then aa=0;

if c < banddn and c[2]>banddn then value2=1;


if value2= 1 then begin plot4(l-offset,"break");
bb=bb+1;

Print(File("C:\xitami\root\mod\SPBand.txt"),d:6:0,", ",c:3:2,",
C<LowerBand",", ","H<MiddleBand, ",bb:0," Days");
print(d:6:0,", ",c:3:2,", C<LowerBand",", ","H<MiddleBand, ",bb:0,"
Days");end;
if h>=av then value2=0;
if h>=av then bb=0;

plot1(av,"21MA");
plot2(bandup,"bandup");
plot3(banddn,"banddn");

MARKET PROFILE

Here's a neat Market Profile .ela that stopped working for some strange
reason. Worked fine until a couple of days ago on both TS4 and TS2000i...
but now... everything is jumbled. You have to set the scale to "screen" or
entire data series when using it (unless some ela wizard can correct it,
too).

input:compress(1),len(30),letter1(1),txtcolr(7),opncol(6),closcol(6),lastcol(6),VAprcnt

327
(.70),Valcol(5),
Valsize(3),Stime(Sess1StartTime);

vars:lett("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"),t
1(0),vsize(0),cpt(0),dl(0),
lcount(1),fp(0),daynum(0),d0(0),mid(0),dlo(0),pc(0),pc2(0),skp(0),labl(0),vala(0),vap
(0),cp(0),t0(0),nuflag(0),
hh(0),ll(0),x(0),et(0),
clet(""),curtxt(""),th(0),tl(0),tpstr("00"),tot(0),va(0),d2p(0),oldclet(""),
barhi(0),barlo(0),mintick(0),xpts(0),price(0),up(0),dn(0),oldup(0),olddn(0),flag(0),fla
g2(0)
;

array:pri[1000](0),tpo[1000](0),pristr[1000]("");

nuflag=0;
if t0 <= Sess1EndTime and t > Sess1EndTime and Sess2StartTime <> 0 then
nuflag=1;
if d <> d0 and Sess2StartTime = Sess2EndTime then nuflag=1;
if t0=sess1endtime then nuflag=1;
if currentbar=1 or nuflag=1 then begin
if currentbar=1 then begin
if VAprcnt < 0 or VAprcnt >= 1 then vap=0 else vap=VAprcnt;
vsize=mod(valsize+7,7);
if vsize < 2 then value88=5 else value88=vsize;
mintick = 1 point * minmove * compress;
xpts=500*mintick;
end;
lcount=letter1; if lcount < 0 or lcount > 52 then lcount=1;
if currentbar > 1 then begin
if valcol <> 0 and flag2=0 then begin
mid=0;value23=0;
cpt=tl;cp=tl + (th-tl)/2; {center of dist.}
for x = tl to th begin
if pristr[x] <> "" then begin
pristr[x]=nutpstr(tpo[x],pristr[x],pri[x]);
value23=value23 + tpo[x]; {total tpo count}
if tpo[x]=mid and x <= cp then cpt=x;
if tpo[x]=mid and x>cp and(x-cp) < AbsValue(cp-cpt) then cpt=x;
if tpo[x] > mid then begin
cpt=x;
mid = tpo[x];
end;
end;
end;
va=value23 * vap;
labl= text_new(d2p,t1,dl-mintick,NumToStr(value23,0)+" TPO's");
TEXT_SETSTYLE(labl,0,2);
TEXT_SETCOLOR(labl,valcol);

328
if va > 0 then begin
value61=value19;
value19=cpt;
x=mid;up=value19+1;dn=value19-1;
while x < va begin
if tpo[up] = tpo[dn] then begin
x=x+tpo[up];
up=up+1;
if x < va then begin
x=x+tpo[dn];
dn=dn-1;
end;
end else begin
if tpo[up] > tpo[dn] then begin
x=x+tpo[up];
up=up+1;
end else begin
x=x+tpo[dn];
dn=dn-1;
end;
end;
end;
up= fp+((up-1-500)*mintick);
dn=fp+((dn+1-500)*mintick);
vala=TL_New(D2p,t1,up,D2p,t1,dn);
TL_SetColor(vala,valcol);
TL_SetSize(vala,vsize);
value62=fp+((value19-500)*mintick);
value60=TL_New(D2p,t1,value62+mintick/15,D2p,t1,value62-mintick/15);
TL_SetColor(value60,valcol);
TL_SetSize(value60,value88);
end;
end;
pc2=0;
for value4=tl to th begin
price=fp+((value4-500)*mintick) ;
if price <= pc then pc2=value4;
end;
if pc2=0 then pc2=barlo;
curtxt=pristr[pc2];
if RightStr(curtxt,1) <> "<" then begin
text_setstring(pri[pc2],curtxt+" <");
Text_SetColor(pri[pc2],closcol);
end;
end;
t1=t;
d2p=d;
labl=0;vala=0;
for value1=tl to th begin

329
pristr[value1]="";

tpo[value1]=0;
end;
clet=curletstr(stime,len,letter1);
oldclet=clet;
dlo=l;
fp=o;
tpo[500]=1;
th=500;tl=500;
flag=0;
pri[500]= text_new(d,t1,o," >"+clet);
pristr[500]=" >"+clet;
TEXT_SETSTYLE(pri[500],0,2);
TEXT_SETCOLOR(pri[500],opncol);
hh=o;ll=o;mid=1;tot=1;value22=currentbar;
dl=l;
if d= JulianToDate(LastCalcJDate) then flag2=1;
end;
if t <> t0 then clet=curletstr(stime,len,letter1) ;{this does not work -
always is true}
t0=t;d0=d;pc=c;
barhi=intportion((xpts+h-fp+(mintick/10))/mintick);
barlo=ceiling((xpts+l-fp-(mintick/10))/mintick);
if barhi > th then th=barhi;
if barlo < tl then tl=barlo;
if l < dl then dl=l;
IF datacompression=0 and currentbar > value22 then begin
lcount=lcount+1;
if lcount=53 then lcount=1;
clet=midstr(lett,lcount,1) ;
hh=o;ll=o;flag=flag+1;
end;
value22=currentbar;
IF datacompression = 1 and oldclet <> clet then begin
hh=o;ll=o;flag=flag+1;
end;
{skp=0;
if h > hh or l < ll then begin
skp=1;}
for value4=barlo to barhi begin
price=fp+((value4-500)*mintick);
curtxt=pristr[value4];
if curtxt = "" then begin
tpo[value4]=1;
pri[value4]= text_new(d2p,t1,price," "+clet);
pristr[value4]=" "+clet;
TEXT_SETSTYLE(pri[value4],0,2);
TEXT_SETCOLOR(pri[value4],txtcolr);
end else begin

330
if RightStr(curtxt,1) <> clet then begin
text_setstring(pri[value4],curtxt+clet);

pristr[value4]=curtxt+clet;
tpo[value4]=tpo[value4]+1;
end;
end;
end;
if h>hh then hh=h;
if l < ll then ll = l;
{end;}
if valcol <> 0 {and skp =1} and {d= JulianToDate(LastCalcJDate)}
lastbaronchart then begin
mid=0;value16=0;value23=0;
cpt=tl;cp=tl + (th-tl)/2; {center of dist.}
for x = tl to th begin
if pristr[x] <> "" then begin
pristr[x]=nutpstr(tpo[x],pristr[x],pri[x]);
value23=value23 + tpo[x]; {total tpo count}
if tpo[x]=mid and x <= cp then cpt=x;
if tpo[x]=mid and x>cp and(x-cp) < AbsValue(cp-cpt) then cpt=x;
if tpo[x] > mid then begin
cpt=x;
mid = tpo[x];
end;
end;
end;
va=value23 * vap;
if l < dlo then begin
dlo=l;
price=fp+((tl-501)*mintick);
if labl <> 0 then Text_SetLocation(labl,d2p,t1,price);
end;
if labl =0 then begin
price=fp+((tl-501)*mintick);
labl= text_new(d2p,t1,price,"-");
TEXT_SETSTYLE(labl,0,2);
TEXT_SETCOLOR(labl,valcol);
end;
Text_SetString(labl,NumToStr(value23,0)+" TPO's");
if va <> 0 then begin
value61=value19;
value19=cpt;
x=mid;up=value19+1;dn=value19-1;
while x < va begin
if tpo[up] = tpo[dn] then begin
x=x+tpo[up];
up=up+1;
if x < va then begin
x=x+tpo[dn];

331
dn=dn-1;
end;
end else begin

if tpo[up] > tpo[dn] then begin


x=x+tpo[up];
up=up+1;
end else begin
x=x+tpo[dn];
dn=dn-1;
end;
end;
end;
oldup=up;
olddn=dn;
up= fp+((up-1-500)*mintick);
dn=fp+((dn+1-500)*mintick);
if flag=1 then value63=t;
if up > dn and flag > 1 then begin
if vala = 0 then begin
vala=TL_New(D2p,t1,up,D2p,t1,dn);
TL_SetColor(vala,valcol);
TL_SetSize(vala,vsize);
value62=fp+((value19-500)*mintick);
value60=TL_New(D2p,t1,value62+mintick/15,D2p,t1,value62-mintick/15);
TL_SetColor(value60,valcol);
TL_SetSize(value60,value88);
end else begin
if oldup <> up then TL_SetBegin(vala,D2p,t1,up);
if olddn <> dn then TL_SetEnd(vala,D2p,t1,dn);
end;
end;
if value61 <> value19 and flag > 1 then begin
value62=fp+((value19-500)*mintick);
TL_SetBegin(value60,D2p,t1,value62+mintick/15);
TL_SetEnd(value60,D2p,t1,value62-mintick/15);
end;
end;
end;

if lastcol > 0 and lastcol < 17 then begin


if value10 = 0 and currentbar=3 then begin
value10=tl_new(value50,value51,c,d,t,c);
tl_setcolor(value10,lastcol);
tl_setsize(value10,0);
TL_SetExtLeft(value10,true);
end else if currentbar > 3 and LastBarOnChart then begin
{tl_setbegin(value10,value52,value53,c);}
tl_setend(value10,d,t,c);
tl_setbegin(value10,value52,value53,c);

332
end;
value52=value50;value53=value51;
value50=d;value51=t;
end;

plot1(l-mintick,"dummy");

plot2(vala,"dummy");

333
TradeStation How To’s

T BOND SYSTEM

Hi everyone,
Here's a simple little EOD system for TBonds which seems to
perform well over a wide range of years, has a low DD and reasonably high
win/loss and profit factor percentage figures:

if range<average(range,9)[1]/2 then buy next bar at high+1 point stop;


if marketposition=1 and barssinceentry=1 then exitlong next bar at open;

Set a MM stop of $300.

You can experiment with the barssinceentry setting - 0, 1, 2 etc - and set
the system to close all trades at end of day.

Can anyone say what's wrong with this or would you be happy to trade it?

Cheers,
Ian

HIGHER HIGHS

>here is what i came up with and i would appreciate it if anyone could help me just a
little more... when this is put on the chart it works for the first couple of bars but then
doesn't "reset" to continue to count the new highs.
>
>What i'm looking for is an indicator that will count the number of higher highs (a
high higher than the prior bar but not necessarily consecutive to the last higher high)
in a set number of bars.

The attached code is my best guess as to what you are looking for. You still didn't
specify "new Highs since when" so I assumed you meant since the beginning of the
N-bar interval. A gif picture is attached.

This is a pretty brute force method, just searching for new highs from N bars ago.
There are faster ways by keeping track of things as you move forward through the
bars but they take a lot more code.

Bob Fulks

{ *******************************************************************

334
Indicator : NewHighsLows

Last Edit : 4/15/01

Provided By : Bob Fulks

Description : This indicator plots the number of new highs and


new lows in the past "N" bars, as measured from the highs
and lows of "N"bars ago.

********************************************************************}
Input: N(20);

Vars: j(0), HHigh(0), LLow(0), NHigh(0), NLow(0);

HHigh = High[N];
LLow = Low[N];
NHigh = 0;
NLow = 0;
for j = N - 1 downto 0 begin
if High[j] > HHigh then begin
HHigh = High[j];
NHigh = NHigh + 1;
end;
if Low[j] < LLow then begin
LLow = Low[j];
NLow = NLow + 1;
end;
end;

Plot1(NHigh, "NHigh");
Plot2(-NLow, "NLow");
Plot4(0, "zero");

"

INDICATOR MARKS

Does anyone on the list know if one must use a strategy to draw the
>up/down arrows used to denote buy and sell signals? Is there a way to

335
>code them in an indicator?
>
>I've checked documentation, but perhaps am not looking in the right
>place, and Omega online support is down.
>
>Any help much appreciated,

Try:

if Date = XXXXXX and Time = YYYY then Buy;


if Date = XXXXXX and Time = YYYY then Sell;

YESTERDAY’S HIGH LOW ON AN INTRADAY CHART

From: "Sean O'Toole" <sean@kingfieldcapital.com>


To: "Omega List" <omega-list@eskimo.com>
Subject: EL Question
Date: Mon, 9 Apr 2001 16:35:10 -0500

I'm having a mental lapse here. I would like to incorporate yesterday's


high and low into an indicator which will be used on today's intraday data.
How do I call daily data from an intraday chart?

Use the HighD(1) / LowD(1) functions although make sure you assign them to
variables

Cheers Stuart

TO COUNT THE NUMBER OF NEW HIGHS IN THE LAST N BARS

Here asking for help. Would like to create a indicator that has two plots. I would like
to count the number of new highs in the last "N" number of bars, which would be plot
1, and plot 2 would be the number of new lows for last "N" number of bars. Would
anyone know how to do this? Not sure how to code a "counter" in EL. I would really
appreciate anyone's help trying to code this.

I can think of a couple of methods off hand. You do not say how you ever reset the
new-high level. You probably do not want it to just keep getting higher forever...

The following illustrates a couple of ideas. (These are not tested.) See the comments
for a description. These do not ever reset the new high level so you will need to
decide when you would like to do that.

336
Bob Fulks

{Method 1}

Input: N(14);

Vars: HHigh(-99999), NHigh(0), HCount(0)

if High > HHigh then begin


HHigh = High; {Save new high level}
NHigh = 1; {Save location of new high}
end else NHigh = 0;

HCount = Summation(NHigh, N); {Count number over past N bars}


if ??? then HHigh = ???;

-------

{Method 2}

if High > HHigh then begin


HHigh = High; {Save new high level}
HCount = HCount + 1 - HCount[N]; {Calculate number over past N bars}
end;
if ??? then HHigh = ???;

COMMENTARY FUNCTION

The use of commentary together with stop and limit orders for the next bar is not very
complicated. Simply insert a comentary function with the comentary you want to have
after the stop/limit order.

Look at this code for example:

If PlaceShort then begin


Sell ("Short") next bar at ShortPrice Stop;
#BEGINCMTRY;
Commentary ("Order (Short) to sell next bar at ",ShortPrice," Stop",NewLine);
#END;
end;
If PlaceLong then begin
Buy ("Long") next bar at LongPrice Stop;
#BEGINCMTRY;

337
Commentary ("Order (Long) to buy next bar at ",LongPrice," Stop",NewLine);
#END;
end;

When you use commetary function the system shows you your active orders. But
don't forget that stop/limit orders are active only for the next bar and have to be
placed again to remain active.

NO PLOT() STATEMENT

<< Does anyone have experience with the NoPlot() statement in EasyLanguage?
I
believe this is new to TS2000i.

I was trying to use it this morning to draw an intermittent line, but it


doesn't seem to be working correctly.

Basically, at times the areas where I used NoPlot come up blank -- as I'd
expect. But if I scroll left or right, "sometimes" those areas fill in
with a straight line between the points on either side of the gap.

Has anyone else experienced this? Found a workaround? Brought it up with


Omega?

Thanks,
Dave
>>

Dave,

I use it frequently. After the frustration resulting from the 'symptoms' you
described, I took the easy way out and plotted those 'indicators' for which I
was using 'noplot' statements as points rather than lines. This doesn't
solve the problem you bring up but it at least gets rid of those 'nasty'
lines connecting the 'gaps' you mention. For me this has proved an adequate
but not perfect solution to the problem.

Lee Scharpen

What I discovered is I can achieve the result I want with Trend


Lines. It's not ideal, but at least gives the visual effect that I need.

Example:

IF val1 > 0 AND

338
val1[1] > 0
THEN BEGIN
VAR: foo(0);
foo = TL_New(date[1], TIME[1], val1[1], DATE, TIME, val1);
END;

If anyone else has ideas, I'd love to hear them.

Thanks for your help,


Dave

At 12:24 PM 4/20/2001 -0400, LScharpen@aol.com wrote:


>In a message dated 4/20/01 9:18:46 AM Pacific Daylight Time,
>david_wieringa_ml@worldnet.att.net writes:
>
><< Does anyone have experience with the NoPlot() statement in EasyLanguage?
>I
> believe this is new to TS2000i.
>
> I was trying to use it this morning to draw an intermittent line, but it
> doesn't seem to be working correctly.
>
> Basically, at times the areas where I used NoPlot come up blank -- as I'd
> expect. But if I scroll left or right, "sometimes" those areas fill in
> with a straight line between the points on either side of the gap.
>
> Has anyone else experienced this? Found a workaround? Brought it up with
> Omega?
>
> Thanks,
> Dave
> >>
>
>Dave,
>
>I use it frequently. After the frustration resulting from the 'symptoms' you
>described, I took the easy way out and plotted those 'indicators' for which I
>was using 'noplot' statements as points rather than lines. This doesn't
>solve the problem you bring up but it at least gets rid of those 'nasty'
>lines connecting the 'gaps' you mention. For me this has proved an adequate
>but not perfect solution to the problem.
>

339
NUMERICAL ACCURACY

There are ways to reduce the errors by a huge order


if someone has to use easy lang. I highly recommend
those who is into using "deep" exponential moving
averages and cumulative "percentage" multiplication
in TS to read some introductory text on computational
numerical analysis. Most of these text cover some
basic techniques in error reduction that can be
copied into actual work easily.

TRADESTATION: RELATIVE VIGOR INDEX

John Ehlers's article "Relative Vigor Index (RVI)" in this issue includes a version of
EasyLanguage code for the indicator. That version includes hardcoded
implementations of a symmetrically weighted moving average in three places, and
also a hardcoded implementation of two summations. We provide an alternative
version below that replaces these hardcoded implementations with function calls. This
version produces identical results, except for minor initialization differences.
The SWMA, also known as a triangular moving average, can be conveniently
implemented as a double simple moving average, and this code can be separated out
into a function that can than be called from the main body of the code as many times
as necessary. TradeStation includes a TriAverage function, but the function required
here is a little more generalized, so we call it TriAverage_gen and provide the code
for it below, following the main indicator code. Summation is another built-in
function in TradeStation, and we use that as is.
Indicator: Relative Vigor Index
inputs:
Length( 10 ) ;
variables:
Change( 0 ),
MyRange( 0 ),
Num( 0 ),
Den( 0 ),
RVI( 0 ),
RVISig( 0 ) ;
Change = Close - Open ;
MyRange = High - Low ;
Value1 = TriAverage_gen( Change, 4 ) ;
Value2 = TriAverage_gen( MyRange, 4 ) ;
Num = Summation( Value1, Length ) ;
Den = Summation( Value2, Length ) ;
if Den > 0 then
RVI = Num / Den ;
RVISig = TriAverage_gen( RVI, 4 ) ;
Plot1( RVI, "RVI" ) ;
Plot2( RVISig, "Sig" ) ;
Function: TriAverage_gen
inputs:
Price( numericseries ),
Length( numericsimple ) ;
variables:
Length1( 0 ),

340
Length2( 0 ) ;
Length1 = Floor( ( Length + 1 ) * .5 ) ;
Length2 = Ceiling( ( Length + 1 ) * .5 ) ;
TriAverage_gen =
Average( Average( Price, Length1 ), Length2 ) ;

STOPS

Warning: I'm answering these questions in the context of TS4, which


is what I use. I believe TS2k works the same way.

> I`ve included a stop loss signal in my strategy, but I noticed


> that many of the losing trades were way above that amount. Then I
> saw that TS was only looking at the stop loss at the next bar, not
> the same bar in which the trade was initiated. Any way to get
> stopped out even intrabar?

Buy/sell/exit orders are issued at the *end* of the current bar, and
are in effect only for the next bar. For stops you manage yourself,
you need to issue the order on EVERY bar.

But it sounds like you're concerned about getting stopped out in the
same bar you entered in. One choice is to use TS's built-in MM stop,
which should be in effect immediately after entry. Another choice is
to issue the MM stop on the bar BEFORE you enter the trade. I.e. if
you have a "buy" order on bar X, which enters on bar X+1, then you
should also issue an MM stop order on bar X. That way it will also
be in effect on bar X+1. You might want to modify the MM stop after
you've entered, since your actual fill might be different than the
theoretical fill you anticipated in bar X.

> "generate orders for next bar" didn`t make a difference...

That's a very badly-named option. It doesn't seem to have any impact


on when or whether systems issue orders. It only affects whether the
system's orders appear in the STCC, and whether order changes are
signalled with the "new/changed/removed orders" dialog boxes.

ADAPTIVE STOP

I just happened to be playing in this area. See if this


helps. You won't get an specific $ level exit since it is
adaptive. It takes into account the current bar.

Just fiddle with the hard coded numbers to meet your needs.

341
var: xprice(0);
if mp <> mp[1] then xprice=0;
if NumLosTrades > 0 and OpenPositionProfit < (GrossLoss/NumLosTrades)*3 and
xprice=0 then xprice = close;
if mp = 1 and xprice<>0 then exitlong("lx1") next bar at xprice - 30 points stop;
if mp = -1 and xprice<>0 then exitShort("sx1") next bar at xprice + 30 points stop;
if mp=0 then begin
exitlong("lx2") next bar at close - TR*2 stop;
exitShort("sx2") next bar at close + TR*2 stop;
end;

LINE THICKNESS WON’T RESPOND

> I'm using TS2ki (latest) & I've been unable to change the line thickness
> (weight) in my indicators no matter which one I select. Is this a bug?
>
> Michael

Are your bars spaced widely enough to allow the change to occur? Try
expanding the width between bars and see it the bar size adjusts.

This one drove me nuts for a month before I finally figured it out, so I'm happy to
be able to pass on the answer (one of these days I'll be able to answer someone's
question about TRADING...)

In TS2Ki, go to the View/Chart Options dialog, General tab, and turn off "Auto-size
bar width when bar spacing changes." Voila, line thickness will work again. As far
as I'm concerned, this is for sure a bug. According to Help, this is what the
option is supposed to do:

"Auto-size bar width when bar spacing changes - Controls the width of the individual
bars. Selecting this option causes the width of each bar to increase when bar
spacing increases and decrease when bar spacing decreases. "

In fact, all it seems to do is break Line Width display.

TEXT STUDIES

342
Indicator #1: Dynamic Arrow to the Right of Closing Price on Chart
(@TextCurrentC<=.ela).
Nothing new --- I've posted this here before and am reposting it for
completeness.

Indicator #2: As Above Plus Dynamic Value of Closing Price in Text


(@TextCurrentCText.ela)
Same as above. In other words, not only does the arrow follow the
current close but just to the right of the arrow is the value of the
current close in text. For, example, if the current close is 999.50,
then immediately to the right of the current close on the chart is
<=999.50.

Indicator #3: Dynamic Arrow to the Right of Current Indicator Value on


Price Chart Plus Dynamic Value of Current Indicator Value in Text
(@TextCurrentIndic.ela). Similar to above although with an Indicator on
a Price Chart. For example, if the Indicator is a 10-period simple
moving average of the Close, the Indicator is plotted on a Price Chart,
and the current value of the Indicator is 995.75, then immediately to
the right of the end of the Indicator plot is <=995.75.

Notes ---

A. I have not found a way to plot text indicators on anything but a


Price Chart, for example, on an Indicator subgraph, such as on Subgraph
2: Indicator below Subgraph 1: Price Chart. One of the consequences of
this is that the values plotted by Text Indicators have to be close to
those plotted in the Price Chart. For example, not only haven't I found
any way to plot a Text Indicator on, for example, an indicator such as a
Stochastic in Subgraph 2, the Text Indicator on an indicator such as a
Stochastic won't effectively plot even on a Price Chart because of the
substantial difference in values between those of the Stochastic (from 0
to 100) and the Price Chart (unless the latter has a range between
approximately 0 and 100). It appears that Text Indicators are, in fact,
limited to Text ShowMes --- if so, a major limitation to Text
Indicators. I hope that I am wrong about this, and that you'll tell me
so --- or, if I'm right, that some of you have found work-arounds to
these limitations and would be willing to share them.

B. For these indicators to plot dynamically, check "Update Every Tick".

C. To plot these indicators effectively, set "Bars to the Right" > 0


--- I suggest, for example, 10.

D. These indicators plot effectively only with minute-based charts ---


they can produce artifacts on tick-based charts, especially when
Ticks/Minute > Ticks/Bar. Try it on something like a 5-Tick ES chart
and see for yourself. The arrow's location progresses to the right in
time only upon the next decrement in TS time, ie, minute, so as bars are
produced following the last time decrement, they start to overlap the

343
arrow. One work-around for this would be to set "Bars to the Right" to
an appropriately large number.

E. There's no "magic" in my choice of the combined symbols "<" and "="


to make a left-pointing arrow. Try some others at your discretion.
Furthermore, you have some control over its location, as well as its
color (but apparently not its strength), under the ELA rules. (Its
strength appears to be set by your choice of Price Chart font.)

F. These indicators were programmed with TS2Ki. I believe they will


also work with TS4 with a little modification. For example, for any
Indicator lacking a plot statement, the plot statement "IF False THEN
Plot1(0,"");" (without the bracketing quotation marks --- but with the
internal quotation marks) needs to be added at the end.

@Text Current C <=


Var: Arrow(" <="),
ID(-1);

IF BarNumber = 1 THEN ID = Text_New(D,T,C,Arrow);


Text_SetLocation(ID,D,T,C);
Text_SetStyle(ID,0,2);
Text_SetColor(ID,6);

{ ELA Color Numbers ---

Black = 1 White = 8
Blue = 2 Dark = 9
Cyan = 3 Dark = 10
Green = 4 Dark = 11
Magenta = 5 Dark = 12
Red = 6 Dark = 13
Yellow = 7 dark = 14
DkGrey = 15 LightGrey = 16 }

@TextCurrentCText

Var: Arrow(" <="),


ID(-1);

IF BarNumber = 1 THEN ID = Text_New(D,T,C,Arrow+NumToStr(C,2));


Text_SetString(ID,Arrow+NumToStr(C,2));
Text_SetLocation(ID,D,T,C);

344
Text_SetStyle(ID,0,2);
Text_SetColor(ID,6);

{ ELA Color Numbers ---

Black = 1 White = 8
Blue = 2 Dark = 9
Cyan = 3 Dark = 10
Green = 4 Dark = 11
Magenta = 5 Dark = 12
Red = 6 Dark = 13
Yellow = 7 dark = 14
DkGrey = 15 LightGrey = 16 }

@TextCurrentIndic

Var: MA(0),
Arrow(" <="),
ID(-1);

MA = Average(C,10);
Plot1(MA,"Avg");

IF BarNumber = 1 THEN ID =
Text_New(Date,Time,Close,Arrow+NumToStr(MA,2));
Text_SetString(ID,Arrow+NumToStr(MA,2));
Text_SetLocation(ID,D,T,MA);
Text_SetStyle(ID,0,2);
Text_SetColor(ID,6);

{ ELA Color Numbers ---

Black = 1 White = 8
Blue = 2 Dark = 9
Cyan = 3 Dark = 10
Green = 4 Dark = 11
Magenta = 5 Dark = 12
Red = 6 Dark = 13
Yellow = 7 dark = 14
DkGrey = 15 LightGrey = 16 }

345
TRADESTATION INSTABILITY

James
I had constant crashes with Ts2ki under Win98, occasional crashes under
NT4/SP6 and ZERO crashes since I switched to Win2k. Get Win2k, it is far
more stable than NT. Also I run 256mb ram which I believe is the minimum
necessary for trouble free operation of Ts2k running real time. Also
whenever you have mysterious gremlins like self-modifying toolbars I suggest
a clean install of your O/S and Ts2k. When I have had similar problems I
did not reuse old workspaces or data because prior attempts to do so caused
the gremlins to return. Export your data before reinstall and import it
back and recreate your workspaces manually. This gives you a dead clean
install and in every case that eliminated my gremlins. None have returned
since I went on Win2k. Other folks get away with copying back data and
workspaces onto a clean install of Ts2k but I was not that lucky.

Good luck

Bill Wood

346
Other How To’s

Trend Squelch

The code for the TrendMode true-false condition is

347
348
TS4 INSTALLATION ON WIN 2K

Following is originally from Dave Nadeau. At the bottom there is some notes
on the problem I had with Command prompt. May help ? I will post another
email with copies of threads from omega-list around the topic.

Regards
Jon

DocumentID: 120
Last Updated on: 9/29/00

Security Block Problems


This document addresses the steps to trouble-shoot the following error
messages:
Security block not found
-OR-
Security block is missing
Users of Microsoft Windows Millenium Edition (ME) will use slightly
different steps. Please see the following link for Windows ME instructions.
Here are a number of items to check. Try each step in order and continue
only if the problem persists:
1. After installing, reboot the computer. Windows must be restarted after an
installation in order for any Version 4.0 or Version 1.2 application to work
properly.
2. Check that the Security Block is attached to the parallel port of the PC.
3. If there are any other devices attached to the block, try removing them.
4. If there is a printer attached, try starting the Data Server with the
following combinations:
a. Printer attached to the block, turned on.
b. Printer attached to the block, turned off.
c. Printer not attached to the block.
5. If there is no printer or the combinations in step 3 do not work, check
the speed settings of the block. This requires running the SSIACT speed
measurement utility in DOS. Note to AMD K6 users: This utility may report an
incorrect setting. Please skip to step h. and use the setting 2,2,50.
a. Select the Start | Programs | MS-DOS Prompt menu sequence.
b. The DOS prompt should be running in full screen mode. This means the
monitor screen will be completely black, with DOS text in white. No other
"windows" should be seen with exception of the DOS screen. If this is not
the case, change to full screen mode by clicking on the Properties icon on
the menu bar. Select the Screen tab and select Full Screen Mode. Click OK.
c. At the prompt type CD C:\OMEGA\PROG\DRIVERS\NT <Enter>.
d. At the prompt (C:\OMEGA\PROG\DRIVERS\NT>) type SSIACT <Enter>. This
will
start the Speed Measurement Utility.
e. At the "Hit enter when ready" message, make sure the security block is
attached properly and then hit <Enter>.

349
f. The test will begin followed by "MEASURING". If the message ACTIVATOR
NOT
FOUND appears please call our Customer Support department. Otherwise, a
message will appear stating, "The optimal parameters for this computer is
SET SSI_ACT=" followed by series of numbers. Copy down the series of
numbers.
g. At the prompt (C:\OMEGA\PROG\DRIVERS\NT>) type EXIT. This will return to
the WINDOWS environment.
h. To use the new parameters:
i. Click the Start | Run menu sequence.
ii. At the Open: edit box type SYSEDIT and click OK. This will bring up the
System Configuration Editor.
iii. Select the Window | AUTOEXEC.BAT menu sequence.
iv. Scroll down to the line: SET SSI_ACT=10,10,10 (10,10,10 is the default
setting). Change 10,10,10 to the series of numbers from the test in DOS
(Results of step f).
v. Click the File | Save menu sequence.
vi. Click File | Exit.
i. Reboot and restart the Data Server
6. The SYSTEM.INI file, [386Enh] section should contain the line
DEVICE=SSIACT.386
a. Click the Start | Run menu sequence.
b. At the Open: edit box type SYSEDIT and click OK. This will bring up the
System Configuration Editor.
c. Select the Window | SYSTEM.INI menu sequence.
d. Scroll down to the line that reads [386Enh]. Check until the next blank
line for a line that begins device=ssiact.386. There should NOT be a
semicolon (;) in front of the line. If the line does not exist, add it
immediately under the [386Enh] line.
e. Click the File | Save menu sequence.
f. Click File | Exit.
7. If the Security Block is on an LPT port other than LPT1, the SYSTEM.INI
file, [386Enh] section must contain the following line:
a. Click the Start | Run menu sequence.
b. At the Open: edit box type SYSEDIT and click OK. This will bring up the
System Configuration Editor.
c. Select the Window | SYSTEM.INI menu sequence.
d. Scroll down to the line that reads [386Enh]. Check until the next blank
line for a line that reads SSI_LPT=n (where n=1,2,3) depending what port the
block is on. There should NOT be a semicolon (;) in front of the line. If
the line does not exist, add it immediately under the [386Enh] line.
e. Click the File | Save menu sequence.
f. Click File | Exit.
8. Delete the *.CRI files from the OMEGA subdirectories
a. Click the Start | Find | Files or Folders menu sequence.
b. In the Named: edit box, type in *.CRI
c. In the Look In: edit box, type in C:\OMEGA
d. Make sure there is a check in the Include Subfolders checkbox and click
the Find Now button.

350
e. One or more files should be found. Click on Edit | Select All, then File

| Delete. Confirm deletion to the Recycle Bin and close the Find window.
9. If these steps are unsuccessful, you will need to change the BIOS
settings in your computers setup utility. If you have never edited the BIOS
settings, please refer to your computer's documentation or ask a qualified
technician to help you make changes. The computer will usually display a
message when booting that will explain how to enter the computer's setup
utility. Once you have entered the setup utility, navigate to the section
where you will be able to edit the Parallel port settings. In the BIOS, you
will need to change the settings for the Parallel port to use ECP mode and
Enabled if applicable. Once the mode for the parallel port has been changed,
try to access the program again. If the security block message is still
displayed, it will be necessary to try each different mode setting for the
Parallel port to find a combination that will work properly. The Parallel
port may be setup to use Bi-Directional and Auto or OS Controlled. These
settings will usually not allow the security block to function.

DocumentID: 10
Last Updated on: 10/12/98

Security Block Problems with Windows NT (Also OS/2 and PS/2 machines)
Security Block Access Using Windows NT
The directory X:\Omega\Prog\Drivers\NT, where X is the drive where the
Omega Research product was installed, contains the drivers necessary for
accessing the Activator(/M)or Aegis(/M) under Windows NT.
*** IMPORTANT NOTE ***
In order to make the following changes, Windows NT MUST be started with an
account with ADMINISTRATIVE privileges.
**********************
For native NT applications, only the physical device driver (SSIPDDP.SYS) is
needed. For DOS and Windows applications running in a compatibility box
under NT, both the physical and virtual device drivers are necessary. See
REGISTRY.DOC on how these files should be installed.
There are 2 additional programs, SSIREGI.EXE and SSIREGM.EXE, which will
automatically install/modify the SSIPDDP driver into NT's Registry database.
Refer to the REGISTRY.DOC for details on how the programs are used, and what
directories the files should be copied to.
** IMPORTANT NOTE **
The virtual device driver needs the physical device driver to operate. On
some computers (if you run NT 3.5 or later version), the physical drivers
are loaded continuously, but the user may log on before all of them are
loaded.
In this case, during the log on process, the virtual device driver may be
loaded BEFORE NT has finished loading the physical (SSIPDDP.SYS) driver, and
the user gets the message:
"SSIVDDP Error: SSIPDDP.SYS device driver not loaded"

351
If you encounter this during the first log on or after a boot, don't panic:
Either log out and log in again, or wait longer (approximately one minute)

when the log on message appears before logging in.


To enable DOS and Windows programs to check the ACTIVATOR under Windows
NT
put the Virtual device driver into \winnt\SYSTEM32 directory and the DOS and
Physical device drivers into \winnt\SYSTEM32\DRIVERS:
COPY SSIVDDP.DLL C:\winnt\SYSTEM32\SSIVDDP.DLL
COPY SSIDDDP.SYS C:\winnt\SYSTEM32\DRIVERS\SSIDDDP.SYS
COPY SSIPDDP.SYS C:\winnt\SYSTEM32\DRIVERS\SSIPDDP.SYS
To load the Virtual Device Driver for ACTIVATOR, you have to add
DEVICE=%SystemRoot%\system32\drivers\SSIDDDP.SYS
to the CONFIG.NT file in Windows NT \winnt\SYSTEM32 directory.
With the programs SSIREGI.EXE and SSIREGM.EXE you can automatically
install/modify the SSIPDDP driver into NT's Registry database.
To install, simply run the command
SSIREGI install
After installing into Registry (and copying the SSIPDDP.SYS into the
directory \WINNT\SYSTEM32\DRIVERS) you have to reboot Windows NT.
If the security device is attached to LPT1, no modification is necessary. If
another port is used, modify the registry with the command
SSIREGM LPTPort=n
where n=1-9 is the port#. Probably you don't need to modify the virtual port
address (for DOS and Win16 programs), but if you wish, you may change with
the command
SSIREGM VPort=hhhh
where hhhh is 4-digit hexadecimal port address (use 1000-3FF8). If your
computer is too fast and (in DOS mode) need delay adjustment with the
SSI_ACT environment variable, you have to do the same in the registry with
the command
SSIREGM SSI_ACT=n,n,n
In case you are using a very old ACTIVATOR/M, you have to modify the
registry in order to correctly write the old device. Use the command
SSIREGM SSI_MEM=OLD
If you make any modification in the registry, you have to reboot NT in order
to use the new setting.
If you want to completely remove the driver, run the command
SSIREGI remove
(If the driver is in use, the Registry key will be deleted only next boot
time.) If you used the virtual device driver, don't forget to remove the
line DEVICE=SSIDDDP.SYS from the CONFIG.NT file. Alternatively, you may
modify the Registry manually (using REGEDT32.EXE) to add the device driver.
Go into the hive
\Registry\HKey_Local_Machine\System\CurrentControlSet\Services
and create a new key "SSIPDDP". Add the following values:
ErrorControl = REG_DWORD 0x00000001
Group = REG_SZ Extended Base
Start = REG_DWORD 0x00000002
Type = REG_DWORD 0x00000001

352
Create (inside SSIPDDP) a subkey "Parameters" and inside this subkey
add the following values:
LPTPort = REG_DWORD 1

VPort = REG_DWORD 0x3078


(If you want to use different LPT port, set the 1st value to 2 or 3, for
different virtual port address, the value must be >0x1000 and the last hexa
digit must be 0, 4, 8 or C)
You also may add the values SSI_ACT=n,n,n and SSI_MEM=OLD in the
"Parameters" subkey.
With the programs SSIREGI.EXE and SSIREGM.EXE you can automatically
install/modify the SSIPDDP driver into NT's Registry database. To install,
simply run the command
SSIREGI install
After installing into Registry (and copying the SSIPDDP.SYS into the
directory \WINNT\SYSTEM32\DRIVERS) you have to reboot Windows NT.
If the security device is attached to LPT1, no modification is necessary. If
another port is used, modify the registry with the command
SSIREGM LPTPort=n
where n=1-9 is the port#. Probably you don't need to modify the virtual port
address (for DOS and Win16 programs), but if you wish, you may change with
the command
SSIREGM VPort=hhhh
where hhhh is 4-digit hexadecimal port address (use 1000-3FF8). If your
computer is too fast and (in DOS mode) need delay adjustment with the
SSI_ACT environment variable, you have to do the same in the registry with
the command
SSIREGM SSI_ACT=n,n,n
In case you are using a very old ACTIVATOR/M, you have to modify the
registry in order to correctly write the old device. Use the command
SSIREGM SSI_MEM=OLD
If you make any modification in the registry, you have to reboot NT in order
to use the new setting.
If you want to completely remove the driver, run the command
SSIREGI remove
(If the driver is in use, the Registry key will be deleted only next boot
time.) If you used the virtual device driver, don't forget to remove the
line DEVICE=SSIDDDP.SYS from the CONFIG.NT file.

Dave

finally got it right.


(MS-DOS has now been renamed COMMAND PROMPT in w2000.)
typed the following in and all went smoothly;

C:\> \OMEGA\
C:\OMEGA>CD PROG\
C:\OMEGA\PROG>CD DRIVERS\NT\
C:\OMEGA\PROG\DRIVERS\NT>SSIREGI install
CreateService SUCCESS

353
C:\OMEGA\PROG\DRIVERS\NT>

then I rebooted and the security block allowed opening of server and

charting.

Thankyou very much for your help. After having spent hours trying various
combinations of the Omega Knowledge base string and getting "not a valid
path" your suggestion of altering the string led to the 'fix' above. The
space after "CD" is definitely required. Why Omega cannot publish this
correctly, one will never know!

Regards and thanks again


Jon

----- Original Message -----


From: "Dave Nadeau" <dave_nadeau@yahoo.com>
To: "Jon Macmichael" <jonmac@bigpond.com>; "omega" <omega-
list@eskimo.com>
Sent: Saturday, 05 May, 2001 3:11 PM
Subject: RE: TS4 install to Win 2000 Prof problem

> John,
>
> Looking at the instructions below and your .gif that you had sent with the
> posting, it seems that the error is in the syntax of this last command
>
> It should read
> CD OMEGA\PROG\DRIVERS\NT\SSIREGI install
>
> That is CD is followed by a space.
>
> Also, you might want to follow the procedure for checking your SSI_ACT
> Settings for the Autoexec.bat as described in the MS Word file I'm
> attaching.
>
> Dave Nadeau
>
> > -----Original Message-----
> > From: Jon Macmichael [mailto:jonmac@bigpond.com]
> > Step 4
>>
> > Locate your MS-DOS prompt. At the prompt type the letter of the drive in
> > which your Omega directory resides followed by the colon and the

354
pressing
> > Enter or Return key.
>>
> > Then Type in the following line followed by pressing the Enter or Return
> > key.

>>
> > CD\OMEGA\PROG\DRIVERS\NT\SSIREGI install
>>
>
>

----- Original Message -----


From: "Jim Johnson" <jejohn@cesmail.net>
To: <omega-list@eskimo.com>
Sent: Wednesday, 31 July, 2002 6:20 AM
Subject: still snags on TS4 install on Win2k

> Hello omega-list,


>
> Thanks for the response to my first plea. I followed all the
> instructions but still get the message that security block is missing
> (it is there). I moved all the specified files to various winnt
> directories and the did the speed measurement test to find the correct
> settings for SSI_ACT.
>
> anybody have anything else to suggest?
>
> Thanks.
>
> --
> Best regards,
> Jim Johnson mailto:jejohn@cesmail.net
>

ATR DISCUSSION

> The problem results when moving from yesterday's last bar close to today's
> open bar low or high. If there is a large gap up or down from yesterday,
it
> distorts TR. It appears that the distance from yesterday's close to
today's
> high or low should be excluded.

Maybe I've missed the point of your message, since I have not
really been following this threat, but that was kind of the whole point

355
about ATR--to take into account the gaps that a standard range
indicator misses. The theory being that by capturing those gaps,
ATR more accurately reflects price movements.

If ATR has a defect, it's that it doesn't go far enough. Logically,


if you have seven days of limit moves, it should display them all
as a single price change, including the less-than-limit move that
ends the streak. That is not easy to do, however.

Granted, this might not be convenient for day trading, but ATR
was designed for interday use, with days of limited length and
limits to the daily price movement. In day trading, apparent gaps
almost always result from the length of the bar, rather than from real
voids in the price movement. Same with 24-hour trading, when
there is enough late-night volume to provide an orderly market.
It sounds like whatever problem you are trying to solve comes from
trying to apply ATR to the wrong kind of trading, rather than any
defect in ATR itself.

CODING VELOCITY AND ACCELERATION

The analog for price and time are:

velocity = Delta Price/Delta Time


= (P1 - P2)/(T1 - T2)

acceleration = Delta Velocity/Delta Time


= (V1 - V2)/(T1 - T2)

Kaufman has a section on this type of calculation in Trading Systems and Methods.

356
WealthScript Code

DEAD CAT CATCHER

Below is the WealthScript code for this ChartScript.


{#OptVar6 Default: -30}
{#OptVar7 Default: 30}
{#OptVar5 Default: 1}
{#OptVar4 Default: 5}
{#OptVar1 Default: 1}

CMOPeriod := #OptVar4;
holdPeriod := #OptVar5;
longROCLimit := #OptVar6;
shortROCLimit := #OptVar7;

{ Install AutoStops }
if #OptVar2 > 0 then InstallStopLoss( #OptVar2 );
if (#OptVar2 > 0) and (#OptVar3 > 0) then InstallTrailingStop(
#OptVar2, #OptVar4 );

for Bar := 20 to BarCount() - 1 do


begin
ApplyAutoStops( Bar );
if LastPositionActive() then
begin
if PositionLong( LastPosition() ) then begin
if ( Bar >= BarSave + holdPeriod ) then begin
SellAtMarket( Bar + 1, LastPosition() );
end;
end
else begin
if ( Bar >= BarSave + holdPeriod ) then begin
CoverAtMarket( Bar + 1, LastPosition() );
end
end;
end
else
begin
if (#OptVar1 >= 0)
and (CMO(Bar,#Close,CMOPeriod) < -99.0)

and (ROC(Bar,#Close,CMOPeriod) < longROCLimit)

then
begin
Print(Format('Long %f',ROC(Bar, #Close, CMOPeriod)));
BuyAtMarket( Bar + 1, 5000 );
BarSave := Bar + 1;
end

else if (#OptVar1 <= 0)


and (CMO(Bar,#Close,CMOPeriod) > 99.0)

357
and (ROC(Bar,#Close,CMOPeriod) > shortROCLimit)

then
begin
Print('Short');
ShortAtMarket( Bar + 1, 5000 );
BarSave := Bar + 1;
end;
end;
end;

INTRADAY

WealthScript Code
Below is the WealthScript code for this ChartScript.
{ Create CMOPane Pane }
CMOPane := CreatePane( 50, TRUE, FALSE );
SetPaneMinMax( CMOPane, -60, 60 );
DrawHorzLine( 0, CMOPane, #Gray, 1 );
DrawHorzLine( 50, CMOPane, #Navy, 1 );
DrawHorzLine( -50, CMOPane, #Navy, 1 );

SetBarColors( #Black, #Black );

{ Plot Indicators }
PlotSeries( CMO( #Close, 20 ), CMOPane, 009, 2 );

{ Implement Trading Rules }


LastBar := 999;
AT := 0;
for Bar := 20 to BarCount() - 1 do
begin
Inc( LastBar );
if CumDown( Bar, #Close, 4 ) >= 9 then
SetBarColor( Bar, #Blue );
if CumUp( Bar, #Close, 4 ) >= 9 then
SetBarColor( Bar, #Red );
if CMO( Bar, #Close, 20 ) < -50 then
SetBackgroundColor( Bar, #GreenBkg );
if CMO( Bar, #Close, 20 ) > 50 then
SetBackgroundColor( Bar, #RedBkg );
for P := 0 to PositionCount() - 1 do
if PositionActive( P ) then
if CMO( Bar, #CLose, 20 ) > 50 then
begin
SellAtMarket( Bar + 1, P );
LastBar := 999;
Dec( AT );
end;

358
if ( CumDown( Bar, #Close, 4 ) >= 9 ) and ( CMO( Bar, #Close, 20 )
< -50 ) then
if ( LastBar >= 9 ) and ( AT < 3 ) then
begin
BuyAtMarket( Bar + 1, 5000 );
LastBar := 0;
Inc( AT );
end;
end;

359
WealthScript Code

TURTLE SOUP WITH FILTER

Like TurtleSoup+1, but additional filter criteria.

Below is the WealthScript code for this ChartScript.


xStopLevel := 0.0;

InstallTrailingStop( 10, 50 );
InstallProfitTarget(15);
InstallStopLoss(7);
for Bar := 21 to BarCount() - 1 do
begin
ApplyAutoStops( Bar );
if LastPositionActive() then
begin
if PositionLong( LastPosition() ) then
CoverAtStop( Bar + 1, xStopLevel, LastPosition() )
end
else
begin
if ( PriceLow( Bar) <= Lowest( Bar, #Low ,20 ) ) AND
( PriceLow(Bar -1) > Lowest( Bar -1, #Low, 20) ) AND
( PriceLow(Bar -2) > Lowest( Bar -2, #Low, 20) ) AND
( ATR(Bar,14) / PriceClose( Bar ) > 0.20 ) AND
( CMO(Bar,#Close,14) < -5 )
then begin
{ search previous 20 - day low }
PrevLowPrice := PriceLow(Bar);
for i := 3 to 20 do
begin
if PriceLow(Bar-i) <= Lowest(Bar-i,#Low,20) then
begin
PrevLowPrice := PriceLow(Bar-i);
i := 20;
end;
end;
BuyAtStop(Bar+1, 5000, PrevLowPrice);
xStopLevel := 0.99 * PriceLow(Bar);
if PriceLow(Bar+1) < PriceLow(Bar) then
xStopLevel := 0.99 * PriceLow(Bar+1);
end;
end;
end;

In the March, 2001 issue of Stocks & Commodities magazine, Viktor Likhovidov
shares a method of coding candlesticks.

This ChartScript uses Mr. Likhovidov's CandleCode formulation with one simple

360
modification, and creates a trading system based on CandleCode.

The CandleCode method expresses a candlestick value as a binary number, coding the
body, upper shadow, and lower shadow in different "bits" of the number. One
principal of binary numbers is that we can use the highest bit as a sign. In our
adaptation this is what we do. Rather than adding 64 to the CandleCode value, we
simply make black candles have negative values. This simplifies the code because we
do not have to reverse the bits values when calculating black candlesticks.

On a technical note, we use 20 day Bollinger Bands with 0.5 Standard Deviations to
determine whether the body and shadow sizes are small, medium or large. A value
above the upper BBand indicates large, within the BBands medium, and below the
lower BBand small. The ChartScript displays the candle body size, with
corresponding Bollinger Bands, to illustrate this technique.

We also present a trading system based on the sign-modified CandleCode. The system
presented takes a 20 day simple moving average of CandleCode. When this value
crosses below -25, an extreme reading occurs and a long position is established. When
it crosses above 25 a short position is opened. The system exits at a 20% stop loss,
and 15% profit target.

WealthScript Code
Below is the WealthScript code for this ChartScript.
{ PriceSeries to hold candle body/shadow sizes, and CandleCode }
BodySize := CreateSeries();
UpperShadowSize := CreateSeries();
LowerShadowSize := CreateSeries();
CandleCode := CreateSeries();

{ Obtain body/shadow sizes }


for Bar := 0 to BarCount() - 1 do
begin
SetSeriesValue( Bar, BodySize, Abs( PriceOpen( Bar ) - PriceClose(
Bar ) ) );
if PriceClose( Bar ) > PriceOpen( Bar ) then
SetSeriesValue( Bar, UpperShadowSize, PriceHigh( Bar ) -
PriceClose( Bar ) )
else
SetSeriesValue( Bar, UpperShadowSize, PriceHigh( Bar ) -
PriceClose( Bar ) );
if PriceClose( Bar ) < PriceOpen( Bar ) then
SetSeriesValue( Bar, LowerShadowSize, PriceClose( Bar ) -
PriceLow( Bar ) )
else
SetSeriesValue( Bar, LowerShadowSize, PriceOpen( Bar ) -
PriceLow( Bar ) );
end;

{ Plot Body Size w/Bollinger Bands as an example }


BollPane := CreatePane( 100, true, true );
PlotSeries( BodySize, BollPane, #Blue, 2 );
PlotSeries( BBandUpper( BodySize, 20, 0.5 ), BollPane, #Purple, 0 );
PlotSeries( BBandLower( BodySize, 20, 0.5 ), BollPane, #Purple, 0 );

361
DrawLabel( 'Candle Body Size with 20 day, 0.5 STD Bollinger Bands',
BollPane );

{ Calculate CandleCode value.


Use Bollinger Bands to determine body/shadow size mappings. }
for Bar := 20 to BarCount() - 1 do
begin
{ Body }
nSize := GetSeriesValue( Bar, BodySize );
nUpper := BBandUpper( Bar, BodySize, 20, 0.5 );
nLower := BBandLower( Bar, BodySize, 20, 0.5 );
if nSize > nUpper then
nCode := 32 + 16
else if nSize < nLower then
nCode := 16
else
nCode := 32;
{ Upper Shadow }
nSize := GetSeriesValue( Bar, UpperShadowSize );
nUpper := BBandUpper( Bar, UpperShadowSize, 20, 0.5 );
nLower := BBandLower( Bar, UpperShadowSize, 20, 0.5 );
if nSize > nUpper then
nCode := nCode + 8 + 4
else if nSize < nLower then
nCode := nCode + 4
else
nCode := nCode + 8;
{ Lower Shadow }
nSize := GetSeriesValue( Bar, LowerShadowSize );
nUpper := BBandUpper( Bar, LowerShadowSize, 20, 2 );
nLower := BBandLower( Bar, LowerShadowSize, 20, 2 );
if nSize > nUpper then
nCode := nCode + 2 + 1
else if nSize < nLower then
nCode := nCode + 1
else
nCode := nCode + 2;
{ Set sign for black candles }
if PriceClose( Bar ) < PriceOpen( Bar ) then
nCode := nCode * -1;
{ Store in CandleCode PriceSeries }
SetSeriesValue( Bar, CandleCode, nCode );
end;

{ Plot CandleCode, and a 20 day SMA }


CandlePane := CreatePane( 100, true, true );
PlotSeries( CandleCode, CandlePane, 447, 3 );
PlotSeries( SMA( CandleCode, 20 ), CandlePane, #Navy, 2 );
DrawLabel( 'CandleCode with 20 day SMA', CandlePane );

{ Simple CandleCode trading system. }


InstallStopLoss( 20 );
InstallProfitTarget( 15 );
for Bar := 20 to BarCount() - 1 do
begin
ApplyAutoStops( Bar );
if not LastPositionActive() then
begin
if CrossUnderValue( Bar, SMA( CandleCode, 20 ), -25 ) then
BuyAtMarket( Bar + 1, 5000 )
else if CrossOverValue( Bar, SMA( CandleCode, 20 ), 25 ) then

362
ShortAtMarket( Bar + 1, 5000 );
end;
end;

"Party Girl I, Optimized" has the same code for identifying bull and bear trends than
the already public CharScript "Party Girl".

Some of our colleagues encouraged me to improve the old script because, although
"Party Girl" is often listed among the top ten systems for ISDEX, the returns - both in
terms of RAR and profits - were not so high as they were at release date in October
2000.

For optimization I have just added the following components:


- First, I buy (short) and sell (cover) at stop.
- Second, I use a Trailing Stop (OptVar1, OptVar2).
- Third, I have introduced a ProfitTarget (OptVar4) and a StopLoss (OptVar3).

You can play around with OptVar1 to OptVar4 if you are already working with
Wealth-Lab Desktop.

Having introduced above components, returns (RAR and profits) are again more than
100% as they were before. It seems that the system works a lot better at bear trends
(going short) than at bull trends (going long).

As of today (25 th of November 2000) Gross Profits are today impressive (over
300%) but we also have a lot of gross losses (about -200%) so we end up with poor
100% +/- of real profits.

On the other hand, this means that we have chances to better the results. Please email
me suggestions to improve this system series.

MULTI COLOUR MA ETC.

actually there are three states to the code a long (green) a


short(magenta) and a yellow(flat) replace whatever with your choice
of whatever, even astro stuff will go in there if you choose.

VALUE1=whatever;

if value1<>0 then

if value1[1]<VALUE1 then begin plot1(value1,"what+");END;


if value1[1]>VALUE1 then begin plot2(value2,"what-");END;
if value1=value1[1]then begin plot3(value3,"what");END;

363
DIVERGENCE BETWEEN PRICE AND RSI OR MACD HISTO...?

> Good evening,


>
> I think this question was 10x on the list but maybe one kind soul will
> answer.
> Is there any kind of indicator which will show divergence between
price and
> maybe RSI or MACD histo...?
> Any hint would be appreciate even if its total useless
>
> Thanks Laura
>

Laura,

a pretty good one i came across some time ago.

regards

michael

{*******************************************************************}

Input:OSC(slowkclassic(5,
3)),Mingap(3),MaxOfset(3),OscDif(.01),PrcDif(1),MinPeak(30),
MinPeak2(30),MaxVal(70),MaxVal2(70),MaxNum(10);

Array:OscH[51](0),OscHBar[51](0),OscL[51](0),OscLBar[51](0);

Var:OscVal(0),LastH(0),LastL(0),Loop(0),FoundH(0),FoundL(0),

StrtBar(0),EndBar(0),StrtVal(0),IncVal(0),NewPeak(false),NewVal(false),
LastPeak(0),LastVal(0),EndVal(0);
{MaxOfset - Number of bars away (in price chart) from corresponding peak
or valley in Stochastic that is allowable and still
considered valid
Zero - tight, will produce fewest trades, the greater the
number,
the more trades that will be generated.
MinGap - Minimun number of bars needed between peaks or valleys.
OscDif - Minimum difference needed between points of Stochastic in
order to be greater or less than.
PrcDif - Minimun number of points between highs or lows of bars in
order to be greater or less than.
MinPeak - The minimum value needed for the first peak (of the
stochastic)
MaxVal - The Maximum value allowed for the first valley (of the

364
stochastic)}

{Record current values of oscilator in OscH and OschL arrays. If we


come to a peak or valley, start a new entry. Set up as a stack,
most
recent entry is element 1, older entries have higher numbers. }

OscVal = OSC;
NewPeak=false;
NewVal=false;

{look for peak in Stochastic}

If barnumber > 2 and LastH > 0 then


begin
if OscH[1]-OscVal>=OscDif and OscH[1] - OscVal[2]>=OscDif then
begin
{found new peak}
LastH = Minlist(LastH+1,MaxNum);
NewPeak = true;
for loop = LastH downto 2
begin
OscH[Loop] = OscH[Loop-1];
OscHBar[Loop] = OscHBar[Loop-1];
end;
end;
end ELSE LastH = 1; {first entry}

{Capture and *save values}

OscH[1] = OscVal;
OscHBar[1] = BarNumber;

{Look for valley in Stochastic}

if barnumber>2 and LastL > 0 then


begin
if NewPeak = false then
begin
if OscVal-OscL[1]>=OscDif and OscVal[2]-OscL[1]>=OscDif then
begin
{Found new valley}
LastL = minlist(LastL+1,MaxNum);
NewVal = true;
For Loop = LastL downto 2
begin

365
OscL[Loop] = OscL[Loop-1];

OscLBar[Loop] = OscLBar[Loop-1];
end;
end;
end;
end ELSE LastL = 1; {first entry}

{Capture and save values}


OscL[1] = OscVal;
OscLBar[1] = BarNumber;

{Look for the first part of a sell divergence, the second stochastic
peak is
Lower than the previous stochastic peak by one full % point. Also,
the first peak has to
be >= the MinPeak value. Take the first occurance}

if NewPeak or barnumber-OscHBar[2] <= MaxOfset then


begin
FoundH = 0;
for loop = 3 to lastH
begin
if FoundH=0 and (OscH[loop]-OscH[2]>=1) and
OscHBar[2]-OscHBar[loop]>=MinGap
and OscH[loop]>=MinPeak and
OscH[2]>=MinPeak2
then FoundH = Loop;
{ negative slope}
end;

if foundH > 0 then


begin
{FOUND FIRST PART OF SELL DIVERGENCE, CHECK PRICE BARS FOR
MATCH}
StrtBar = RB_CheckPeak(OscHBar[FoundH],MaxOfset,PrcDif);
EndBar = RB_CheckPeak(OscHBar[2],MaxOfset,PrcDif);
StrtVal = high[StrtBar];
EndVal = high[EndBar];

If StrtBar > 0 and EndBar > 0 and EndVal >= StrtVal and
StrtBar - EndBar >= MinGap then
begin
{Found match, have true Divergence}

{ if OscHBar[2]<>LastPeak then }
if EndVal = StrtVal then IncVal = 0 else
IncVal = (EndVal-StrtVal)/(StrtBar-EndBar);
value2 = 0;
for value1 = StrtBar downto EndBar

366
begin
Plot1[value1](StrtVal+value2*IncVal,"SDIVERG");

value2 = value2 + 1;
end;

{ LastPeak = OscHBar[2]; }

end;
end;
end;

{Look for the first part of a buy divergence, the second stochastic
valley is
Higher than the previous stochastic Valley by one full % point.
Also, the first valley
has to be<=the MaxVal value.Take the first occurance}

if NewVal or barnumber-OscLBar[2] <= MaxOfset then


begin
FoundL = 0;
for loop = 3 to lastL
begin
if FoundL=0 and (OscL[2]-OscL[Loop]>=1) and
OscLbar[2]-OscLBar[loop]>=MinGap
and OscL[loop] <= MaxVal and
OscL[2]<=MaxVal2
then FoundL = Loop;
{ positive slope}
end;
if foundL > 0 then
begin
{FOUND FIRST PART OF BUY DIVERGENCE, CHECK PRICE BARS FOR
MATCH}

EndBar = RB_CheckValley(OscLBar[2],MaxOfset,PrcDif);
StrtBar = RB_CheckValley(OscLBar[FoundL],MaxOfset,PrcDif);
StrtVal = low[StrtBar];
EndVal = low[EndBar];
if StrtBar>0 and EndBar>0 and EndVal <= StrtVal and
StrtBar - EndBar >= MinGap then
begin
{Found match, have true Divergence}

{ if OscLBar[2]<>LastVal then }

if EndVal = StrtVal then IncVal = 0 else


IncVal = (StrtVal-EndVal)/(StrtBar-EndBar);
value2 = 0;
for value1 = StrtBar downto EndBar

367
begin
Plot2[value1](StrtVal-value2*IncVal,"BDIVERG");
value2 = value2 +1;

end;

{ LastVal = OscLBar[2]; }

end;
end;
end;

{******************************************************************}

CHECK PEAK & CHECK VALLEY

Gary,

> Michael, the indicator you posted requires two functions,


> RB_CheckPeak and RB_CheckValley. Do you have those?

see below.

> Any idea who wrote this?

nope. but it works pretty good. you can use different indicators as an
input.

> Gary

michael

Function: RB_CheckValley

{*****************************************************************}
Inputs:PkNmbr(NumericSimple),MaxOfset(NumericSimple),
PrcDif(numericsimple);
Vars:Last(0),First(0),TstVal(0),NextVal(0),PrevVal(0);

{PkNmbr - Barnumber of peak in stochastic that you are checking against


MaxOfset - Number of bars away from this PkNmbr that is allowable and
still considered a valid match
PrcDif - Minimun number of points between highs or lows of bars in
order to be greater or less than.

Will return the offset bar number (bars back from current bar) of the
valley bar or will return a Zero if there is no matching valley}

368
First = Barnumber - Minlist(PkNmbr+MaxOfset,Barnumber-1);
Last = Barnumber - Maxlist(PkNmbr-MaxOfset,2);
RB_CheckValley = 0;

if First<=maxbarsback and Last<=maxbarsback then


begin
For Value1 = First to Last
begin
TstVal = Low[value1];
PrevVal = Low[Value1+1];
NextVal = Low[Value1-1];

{
{***Check For Equal Bars***}
value2 = 2;
while TstVal = PrevVal
begin
PrevVal = Low[value1+value2];
value2 = value2+1;
end;
value2 = 2;
while TstVal = NextVal and value1-value2>= 0
begin
NextVal = Low[value1-value2];
value2=value2+1;
end;
}

if NextVal-TstVal>=PrcDif points and


PrevVal-TstVal>=PrcDif points then
RB_CheckValley = value1;
end;
end;
{**************************************************************}

Function: RB_CheckPeak

{*************************************************************}
Inputs:PkNmbr(NumericSimple),MaxOfset(NumericSimple),
PrcDif(numericsimple);
Vars:Last(0),First(0),TstVal(0),PrevVal(0),NextVal(0);

{PkNmbr - Barnumber of peak in stochastic that you are checking against


MaxOfset - Number of bars away from this PkNmbr that is allowable and
still considered a valid match
PrcDif - Minimun number of points between highs or lows of bars in
order to be greater or less than.

369
Will return the offset bar number (bars back from current bar) of the

peak bar or will return a Zero if there is no matching peak}

First = Barnumber - Minlist(PkNmbr+MaxOfset,Barnumber-1);


Last = Barnumber - Maxlist(PkNmbr-MaxOfset,2);

RB_CheckPeak = 0;
if First<=maxbarsback and Last<=maxbarsback then
begin
For Value1 = First to Last
begin
TstVal = High[value1];
PrevVal = High[Value1+1];
NextVal = High[Value1-1];

{
{***Check For Equal Bars***}
value2 = 2;
while TstVal = PrevVal
begin
PrevVal = High[value1+value2];
value2 = value2+1;
end;
value2 = 2;
while TstVal = NextVal and value1-value2>= 0
begin
NextVal = High[value1-value2];
value2=value2+1;
end;
}

if TstVal-NextVal>=PrcDif points and


TstVal-PrevVal>=PrcDif points then
RB_CheckPeak =value1;
end;
end;

{*******************************************************************}

HIGHEST HIGH

At 2:08 AM +0200 5/13/01, Charles Strong wrote:

>Thanks for your comments. I substituted highest high and lowest low but
>that didn't seem to work either. Any ideas? I get multiple buys and sells all
>clumped together.
>
>Inputs: BZ(2), SZ(1);

370
>
>Sell at highest(high,50) - (highest(high,50)* (sz*.01)) stop;
>
>buy at lowest(low,50) + (lowest(low,50)* (bz*.01)) stop;

Bill Wynne described the problem correctly.

But I am guessing that you want to sell at some amount below the tops, etc.

The trouble with the Highest(High, XX) function is that it searches back in time to a
high. What I think you want is to move forward in time keeping track of new highs.

The following code should do that:

Bob Fulks

---

Inputs: BZ(2), SZ(1);

Vars: HHigh(0), LLow(0), MP(0);

MP = MarketPosition;

HHigh = iff(High > HHigh or MP <> MP[1], High, HHigh);


LLow = iff(Low < LLow or MP <> MP[1], Low, LLow);

if MP >= 0 then Sell next bar at HHigh * (1 - 0.01 * SZ) stop;


if MP <= 0 then Buy next bar at LLow * (1 + 0.01 * BZ) stop;

MOVING AVERAGES

• Tillman T3
• volume-weighted average or Buff average
• sine-weighted moving average
• adaptive moving average by Perry Kaufman
• DEMA
• TEMA

It would take a while to compile all of them into a list.


T3 seems a good choice (among the freely available) to generate signals because it
doesnt lag as much as others. It doesnt turn as fast as jma in trend changes but you
need some noise to generate valid signals.

Juriks moving average has very little noise so it should not be used

371
directly to generate trading signals. It is more useful to smooth time series for instance
a rsi of a jma of the closes.

Some experimentation can be done by displacing them horizontally to generate


earlier signals.

Below is the WealthScript code for this ChartScript.


{ Plot SMAs and EMAs }
PlotSeries( EMA( #Close, 28 ), 0, 044, 2 );
PlotSeries( EMA( #Close, 14 ), 0, 044, 1 );
PlotSeries( SMA( #High, 5 ), 0, 922, 0 );
PlotSeries( SMA( #Low, 5 ), 0, 262, 0 );

{Trailing Stop}
OptVar1 := 10;
OptVar2 := 80;
{Stop Loss}
OptVar3 := 50;
{Profit Target}
OptVar4 := 20;

for Bar := 30 to BarCount() - 1 do


begin

{ See if we're in a trend mode }


BullTrend := false;
BearTrend := false;
if SMA( Bar, #Low, 5 ) < EMA( Bar, #Close, 28 ) then
begin
BearTrend := true;
SetBackgroundColor( Bar, 988 );
end
else
if SMA( Bar, #High, 5 ) > EMA( Bar, #Close, 28 ) then
begin
BullTrend := true;
SetBackgroundColor( Bar, 898 );
end;

InstallStopLoss( OptVar3 );
InstallTrailingStop( OptVar1, OptVar2);
InstallProfitTarget( OptVar4 );

if LastPositionActive() then
begin
ApplyAutoStops(Bar);
{ Test for closing Long Positions }
if PositionLong( LastPosition() ) then

372
begin
if not BullTrend then
SellAtStop( Bar + 1, PriceLow(Bar) , LastPosition() );
end
else
{ Test for closing Short Positions }
begin
if not BearTrend then
CoverAtStop( Bar + 1, PriceHigh(Bar), LastPosition() );
end;
end
else
begin
{ Trigger long/short trades }
if BullTrend then
begin
if ( PriceClose( Bar ) > SMA( Bar, #High, 5 ) )
and ( SMA( Bar, #High, 5 ) > SMA( Bar - 1, #High, 5 ) )
then
BuyAtStop( Bar + 1, 5000, PriceHigh(Bar) );
end;
if BearTrend then
begin
if ( PriceClose( Bar ) < SMA( Bar, #Low, 5 ) )
and ( SMA( Bar - 1, #Low, 5 ) > SMA( Bar, #Low, 5 ) )then
ShortAtStop( Bar + 1, 5000, PriceLow(Bar) );
end;
end;
end;

FIBONACCI FORMULAS

Hi Shashi,

Many thanks for your help. I've come up with the following - not exactly to
your suggestion in every detail, but hopefully in the spirit of it. I
haven't tested it much yet - all feedback and improvements welcome (coding
is not my strong point!). Anyone testing it please vary V1 especially to
your preference - I have it set very low for a 5-minute chart.

V1:=0.5; {ZigZag reversal amount}


V2:=0.50; {Minimum Retracement %}
V3:=0.618; {Maximum Retracement %}

C1:=Peak(1,C,V1) - Trough(1,C,V1); {Swing amount, i.e. price difference


between previous peak and previous trough}

C2:=Peak(1,C,V1) - C; {price difference between previous peak and current


close}

PeakBars(1,C,V1) <

373
TroughBars(1,C,V1) {the previous peak is later than the previous trough}

AND

C < Peak(1,C,V1) {price dropped below last Peak}

AND

C= LowestSince(1, C=Peak(1,C,V1), C)

AND

C2 C1*V2 {retracement minimum}

AND

C2 < C1*V3 {retracement < maximum}

Thanks again,
Nick

----- Original Message -----


From: "Shashi Aggarwal" <shashiag@swbell.net
To: "Metastock Digest (E-mail)" <metastock@listserv.equis.com
Sent: Sunday, February 03, 2002 10:26 AM
Subject: Re: Fibonacci formula

Nick, Maurice, Kush and others,

At one time I had created a pullback/ Fib. retracement formula but can't
seem to find it now. I then gave up using it, not because it didn't work
(it
did!), but I could never tell in real time whether the retracement would
be
38%, 50%, or 62% (the commonest ratios)! Thus, for example, I would buy on
a
38% retracement just to see it fall to 62% retracement. Or I would buy at
62% retracement just to see it fall even further and the trend get
reversed.
I guess that's a limitation we have to live with; of course, once the
trend
resumes, it is very easy with 20/20 hindsight to see how much the
retracement was.

Enough said. The logic was as follows:


1) Define trend. e.g. for an uptrend, you would specify the most recent
swing high/low (#1) be higher than the prior swing high/low (#2). You NEED
to use the Peak & Trough functions for this, which depend on the zigzag

374
indicator. As for the % amount you would choose, that depends on your

trading time frame - larger % for longer time frame and vice versa. (Note:
zigzag is a tricky function; read the online help. In particular, note
this
section from online help: "Be forewarned, that the last leg (i.e.,
segment)
of the Zig Zag is dynamic, meaning that it can change. Therefore, be
careful when designing system tests, experts, etc. based on the Zig Zag
indicator". But don't let this scare you. I got used to it over time, and
so
can you.)
2) Define a recent high implying that the trend is continuing e.g.
HHV(C,20)
most recent swing high (e.g. HHV(C,20) Peak(1,C,10)).
3) Define a pullback e.g. C < HHV(C,20)
4) Define most recent swing e.g. Swing:= HHV(C,20) - Trough(1,C,10) (using
10% swing as an example);
4) Define extent of pullback e.g. for a pullback between 50% & 68% of
recent
swing, it would be something like: C < (Trough(1,C,10) + 0.51*Swing) AND C

(Trough(1,C,10) + 0.31*Swing).
Use filters as needed.

There you have it. Metastock programming is not very easy, but its not
rocket science either. Once you start doing it yourself, AND UNDERSTAND
THE
LOGIC BEHIND YOUR ARGUMENTS, you will catch on pretty fast. Try it - I
have
done most of the work for you above. Just make sure you use the parameters
appropriate for your trading.

Shashi
----------------------------------------------------------
----- Original Message -----=20
From: Maurice Cruz=20
To: metastock@metastock.com=20
Sent: Friday, February 01, 2002 6:46 AM
Subject: Fibonacci Formulas

Group,

I would also be interested in this, or any other


fibonacci-related indicators.

Maurice

375
----- Original Message -----=20
From: Nick Channon=20

To: metastock@metastock.com=20
Sent: Thursday, January 31, 2002 8:53 PM
Subject: Fibonacci Formulas

Hi Group,

I wonder if anyone has a formula to detect a Fibonacci Retracement? =


If so, kindly post. If not, any suggestions on how best to construct =
one? Would it be feasible to base it on zigzag?

Many thanks,
Nick

JOE DINAPOLI - DINAPOLI TREND FORMULA

From: Krzysztof.Kowczur@brebank.com.pl
Subject: "Joe DiNapoli - DiNapoli Trend formula
Date: 30/01/2002 11:35:09
To: metastock@metastock.com

Hi Guys
Does anyone have this system formula???

Dinapoli Trends

{UP}C=Ref(Mov(C,3,S),-3) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))=(PREV+(0.199*((Mov(
CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))-PREV))) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))=Ref((Mov( CLOSE, 8.3896,
E) - Mov( CLOSE, 17.5185, E)),-1)
{DOWN}{DOWN}C<=Ref(Mov(C,3,S),-3) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))<=(PREV+(0.199*((Mov(
CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))-PREV))) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))<=Ref((Mov( CLOSE,
8.3896, E) - Mov( CLOSE, 17.5185, E)),-1){jimt}

This message was sent through MyMail http://www.mymail.com.au

Thanks Peter,

376
I use this formula much differently than Chande suggests. I've had a lot of
success with a 13 period FO. I plot the formula and establish equidistant
levels (from zero) that trigger buy and sell signals. Simple, but effective. This
approach is graphically displayed in the attachment. I like the FO because it
can be somewhat "adaptive" (and it can pull twenty bucks out of crude).
Thanks again, Equis doesn't "trust" us with the formula. If you "click" on the
little "arrow&?", on the task bar, in MetaStock and drop it on the Forecast
Oscillator you get the following blurb:
"The oscillator is above zero when the forecast price is greater than the actual
price. Conversely, it's less than zero if its below."
Of course, this is totally false (the opposite is true). Which of edition of
MetaStock do you believe they might correct their mistake?
Take Care,
Steve
----- Original Message -----
From: Peter Gialames To: metastock@metastock.com Cc:
kernish@turbonet.com Sent: Thursday, January 10, 2002 9:45 AM Subject:
RE: Forecast Oscillator

Not sure if this is what you are looking for but ...

Peter Gialames

Here is the text from S&C V. 10:5 (220-224): Forecasting Tomorrow's


Trading Day by Tushar S. Chande, Ph.D.
Using linear regression as a crystal ball for forecasting the market? After all,
if you were to be able to determine tomorrow's high, low and close for trend
changes and placement of stop points, it would simplify your life
immeasurably. Can it work? Tushar Chande explains how it can be done.
Wouldn't you trade better It you could "see" the future? A simple linear
regression can provide an objective forecast for the next day's high, low and
close. These ingredients are essential for a trading game plan, which can help
you trade more mechanically and less emotionally. Best of all, a regression
forecast oscillator, %F, gives early warning of impending trend changes. The
linear regression method is well known for finding a "best-fit" straight line for
a given set of data. The output of the regression are the slope (m) and constant
(c) of the equation
(1)Y = mX + c
Here, m and c are derived from a known set of values of the independent
variable X and dependent variable Y. The relative strength of the linear
relationship between X and Y is measured by the coefficient of determination
r 2 , which is the ratio of the variation explained by the regression line to the
total variation in Y. Here is a table to help interpret the values of r 2 , which
range from 0 to 1:
The coining of the term "regression" can be attributed to Sir Francis Galton,
who observed in the late 1800s that tall fathers appeared to have as a rule short
sons, while short fathers appeared to have as a rule tall sons. Galton suggested

377
that the heights of the sons "regressed" or reverted to the average. Technician
Arthur Merrill also had a good explanation in a recent issue of STOCKS &
COMMODITIES, and Patrick Lafferty recently wrote on an application of
multiple regression to gold trading. Virtually all introductory books on
statistics have a detailed discussion of the linear regression method.
Successful professional traders emphasize the importance of having a trading
plan. A trading game plan, much like that of a football team, clearly defines
specific actions under different conditions. The linear regression method is
very useful in developing a forecast for the next trading day's high, low and
close based on the last five trading sessions. The method is general and broad-
based enough so that it can be used with stocks, indices or commodities. The
forecast is the basis of my trading plan: I can define what I should do if the
market rises above the forecast high, falls below the forecast low or stays
within the forecast range. This way, I can avoid being emotional and trade as
mechanically as possible by having a plan to rely on.
FORECASTING WITH LINEAR REGRESSION
I like to use at least 10 days of data and develop a forecast for the high, low
and close. The five-day regression is a good choice for short-term trading. You
can use any length of regression you like. Here are the calculations with the
daily close in a spreadsheet format:
1 Perform a linear regression with the first five days of data to obtain the slope
m and constant c such that
X Value Daily Close
1 Day 1
2 Day 2
....
5 Day 5
2 Forecast the next day's close with the slope m and constant c from step 1:
(2) Forecast close (Day 6) = 6m + c
3 Record m, c and r 2 on the same line as Day 5. Record the forecast from step
2 one day ahead, with
Day 6. Note when we are using five days' data, the first forecast is for Day 6.
4 Step the calculation ahead one day such that
5 Record m, c and r 2 as in step 3.
6 Calculate the regression forecast oscillator, %F, as
(3)
%F = ((Y-Yforecast)/Y)*100

378
where Y is the close for Day 6 and Y(Forecast) is the forecast for Day 6 from
step 2 (from Day 5).
7 Record the oscillator on the same line as Day 6.
8 Step the calculations ahead one day at a time until the most recent day.
Technically, we can use the linear regression to develop a point forecast
(single value) for the next day (as in step 2) or a range (interval) of values with
a certain confidence level. The interval widens, greater the variation in the
data and greater the desired confidence level.
I use the forecast oscillator, %F, to determine if my forecast is above or below
the actual market data. Since
%F = ((Y-Yforecast)/Y)*100
where Y can be any market variable for stocks, indices or commodities, %F
measures the percent deviation of the actual value from its forecast. In a
trading market, %F changes its sign before a significant trend change. In
trending markets, %F tends to change sign early in the trend. I interpret %F in
the context of the r 2 Of the regression. A low value of r 2 plus a change in
sign of %F is a good signal of a change in trend. Market extremes and
periodicity can also be observed on the %F charts.
DEVELOPING A TRADING PLAN
You can use the forecasts to develop a specific trading plan to suit your
trading style. I use the forecasts in several ways.
Forecasts as stops. I use the high and the low as action points. If the market
exceeds the forecast high, it wants to go up. To trade with the trend, I put a
buy stop a few ticks above the high. If the market falls below the forecast low,
it wants to go down. Hence, I set a sell stop a few ticks below the forecast low.
If you want to trade against the trend, sell short near the forecast high and buy
near the forecast low.
Forecasts as intraday range scale. The forecasts provide a scale for
evaluating the trading day. The market can stay within the expected range or
go outside. On a down day, the intraday high is well below the forecast high
and may be below the forecast close. On an up day, the market stays well
above the forecast low and often above the forecast close.
General rules for trading with forecasts. Here are some general rules:
• Use the forecasts only if r 2 is greater than 0.1. Higher the value of r 2 , the
greater the confidence in the forecasts.
• A trend change is imminent when r 2 falls below 0.1. Prepare to close longs.
• A trend is in place if r 2 is greater than 0.6. As a trend follower, you could
wait for this value to be exceeded before opening positions. This would keep
you out of short-term fluctuations.

379
• An early warning of a trend change is provided by a zero-crossing of %F, the
forecast oscillator.
Prepare to tighten stops and look for changes in slope and coefficient of
determination for
confirmation.
•A change in trend is confirmed by a change in slope of the regression. Open
positions in direction of trend change. To trade against the trend, look for
peaks in slope and strength of the linear trend.
•The trend will usually change in the direction of %F.
•Always be prepared for a market move against the forecast. Use stops!
A SAMPLE TRADING PLAN
I have developed a forecast for the high, low and close for January 20, 1992,
from the previous five trading days, seen in Figure 1. The market was making
new highs the previous week. Was a downward movement imminent? Let's
look at the data from Friday, January 17, 1992:
The market was trending moderately (0.4<= r 2 <0.6), but the forecast
oscillator %F was negative for high, low and close, warning of a possible
change in trend. The relatively small slope of the regression for the high meant
the market was meeting resistance. The slope of the regression for the close
had turned down from the high values during the recent strong uptrend. The
forecast, however, called for a strong close near the highs of the day, but that
seemed doubtful, given the low slopes in a moderating trend. The plan was to
watch for a change in trend. If the market opened weak, a bearish strategy was
called for. For example, I would consider buying the Standard & Poor's 100
Index OEX January 390 puts, or selling short the S&P 500 March futures
contract.
The high daily volume of OEX index options traded makes the S&P
100 index an interesting application of me regression forecast approach.
The market opened at the Friday close and weakness was evident at the open,
as the S&P 500 futures opened lower. It was clear in early trading that the
trend would be down, as the market traded well below the forecast high and
close. Clearly, the forecast range provided a good scale, since it reinforced the
concept that the market was weaker than the trend of the prior five days. A
bearish stance would have been profitable.
THE NATURE OF REGRESSION FORECASTS
The high daily volume of OEX index options traded makes the S&P 100 index
an interesting application of the regression forecast approach. I have examined
a time period from early October 1991 to mid-January 1992. The OEX close
and its forecast are in Figure 2; the r 2 values in Figure 3; %F in Figure
4, and Figure 5 has %F around the mid-November plunge.

380
Several observations can be made from the OEX analysis. First, the forecast
lags the OEX in an uptrend or in a downtrend. Second, the close and the
forecast cross over several days before a trend change. This crossover can be
seen as a zero crossing in the %F chart. Significant trend changes are preceded
by trendless periods with values of r 2 near zero. Strong trends are
accompanied by high values of r 2 and regression slope. These observations
support the general rules of interpretation noted above. As Figure 5 shows, %F
provided a timely warning of an impending trend change just before the OEX
fell 15.68 points.
I have included data for wheat (cash) from 1989 to indicate the use of this
approach with commodities.
The market showed significant trends during this period with good periodicity,
as shown in Figures 6, 7
and 8. The %F zero crossings were timely indicators of trend change. Features
observed with OEX charts are also seen here; note in particular how %F can
be used to identify extremes in the market from Figures 4 and 8.
Simple linear regression yields forecasts of the high, low and close for stocks,
indices or commodities. These forecasts can be used to develop a trading plan.
You can trade with the trend, against the trend, intraday or interday. The
forecast oscillator, %F, provides early warning of trend changes taken together
with the regression slope and coefficient of determination. This approach
works best in trending markets or trading range markets; it is only moderately
useful in volatile markets with choppy price action. These objective forecasts
will let you trade less emotionally and more mechanically. Profits will look up
when you can look ahead.
Tushar Chande holds a doctorate in engineering from the University of
Illinois and a master's degree in business administration from the University
of Pittsburgh.
REFERENCES
Lafferty, Patrick [ 1991 ]. "A regression-based oscillator," Technical Analysis
of STOCKS & COMMODITIES,
Volume 9: September.
Merrill, Arthur [1991]. "Fitting a trendline by least squares," Technical
Analysis of STOCKS & COMMODITIES,
Volume 9: December.
Pfaffenberger, Roger, and James Patterson [1987]. Statistical Methods for
Business and Economics, Irwin.
-----Original Message-----
From: owner-metastock@metastock.com [mailto:owner-
metastock@metastock.com]On Behalf Of Steve Karnish
Sent: Thursday, January 10, 2002 10:34 AM
To: metastock@metastock.com

381
Subject: Forecast Oscillator

List,

Does anyone have the math formula for Chande's Forecast Oscillator?

Thanks,

Steve

382
Steve,

I believe this is it.

J.

{Forecast Osc-Chande}
{from jseed}
Pds:=Input("Time Periods",1,1000,5);
Fld:=Input("Price Field 1=C 2=O 3=H 4=L",1,4,1);
PFld:=If(Fld=1,C,If(Fld=2,O,If(Fld=3,H,L)));
Sig:=Input("Signal MA Periods",1,200,3);
ForO:=((Pfld-(Ref(LinearReg(Pfld,Pds),-1)+
Ref(LinRegSlope(Pfld,Pds),-1)))*100)/Pfld;
ForO;
Mov(ForO,Sig,E);
{end}

From: "Steve Karnish" <kernish@turbonet.com


Reply-To: metastock@metastock.com
To: <metastock@metastock.com

383
Subject: Forecast Oscillator
Date: Thu, 10 Jan 2002 08:34:12 -0700

List,

Does anyone have the math formula for Chande's Forecast Oscillator?

Thanks,

Steve

Not sure if this is what you are looking for but ...
Peter Gialames
Here is the text from S&C V. 10:5 (220-224): Forecasting Tomorrow's Trading
Day by Tushar S. Chande, Ph.D.
Using linear regression as a crystal ball for forecasting the market? After all, if you
were to be able to
determine tomorrow's high, low and close for trend changes and placement of stop
points, it would
simplify your life immeasurably. Can it work? Tushar Chande explains how it can be
done.
Wouldn't you trade better It you could "see" the future? A simple linear regression can
provide an
objective forecast for the next day's high, low and close. These ingredients are
essential for a trading
game plan, which can help you trade more mechanically and less emotionally. Best of
all, a regression
forecast oscillator, %F, gives early warning of impending trend changes. The linear
regression method is
well known for finding a "best-fit" straight line for a given set of data. The output of
the regression are
the slope (m) and constant (c) of the equation
(1)Y = mX + c
Here, m and c are derived from a known set of values of the independent variable X
and dependent
variable Y. The relative strength of the linear relationship between X and Y is
measured by the
coefficient of determination r 2 , which is the ratio of the variation explained by the
regression line to the
total variation in Y. Here is a table to help interpret the values of r 2 , which range
from 0 to 1:
The coining of the term "regression" can be attributed to Sir Francis Galton, who
observed in the late

384
1800s that tall fathers appeared to have as a rule short sons, while short fathers
appeared to have as a rule
tall sons. Galton suggested that the heights of the sons "regressed" or reverted to the
average. Technician
Arthur Merrill also had a good explanation in a recent issue of STOCKS &
COMMODITIES, and Patrick
Lafferty recently wrote on an application of multiple regression to gold trading.
Virtually all introductory
books on statistics have a detailed discussion of the linear regression method.
Successful professional traders emphasize the importance of having a trading plan. A
trading game plan,
much like that of a football team, clearly defines specific actions under different
conditions. The linear
regression method is very useful in developing a forecast for the next trading day's
high, low and close
based on the last five trading sessions. The method is general and broad-based enough
so that it can be
used with stocks, indices or commodities. The forecast is the basis of my trading plan:
I can define what I
should do if the market rises above the forecast high, falls below the forecast low or
stays within the
forecast range. This way, I can avoid being emotional and trade as mechanically as
possible by having a
plan to rely on.
FORECASTING WITH LINEAR REGRESSION
I like to use at least 10 days of data and develop a forecast for the high, low and close.
The five-day
regression is a good choice for short-term trading. You can use any length of
regression you like. Here
are the calculations with the daily close in a spreadsheet format:
1 Perform a linear regression with the first five days of data to obtain the slope m and
constant c such
that
X Value Daily Close
1 Day 1
2 Day 2
....
5 Day 5
2 Forecast the next day's close with the slope m and constant c from step 1:
(2) Forecast close (Day 6) = 6m + c
3 Record m, c and r 2 on the same line as Day 5. Record the forecast from step 2 one
day ahead, with
Day 6. Note when we are using five days' data, the first forecast is for Day 6.
4 Step the calculation ahead one day such that
5 Record m, c and r 2 as in step 3.
6 Calculate the regression forecast oscillator, %F, as
(3)
%F = ((Y-Yforecast)/Y)*100
where Y is the close for Day 6 and Y(Forecast) is the forecast for Day 6 from step 2
(from Day 5).

385
7 Record the oscillator on the same line as Day 6.
8 Step the calculations ahead one day at a time until the most recent day.
Technically, we can use the linear regression to develop a point forecast (single value)
for the next day
(as in step 2) or a range (interval) of values with a certain confidence level. The
interval widens, greater
the variation in the data and greater the desired confidence level.
I use the forecast oscillator, %F, to determine if my forecast is above or below the
actual market data.
Since
%F = ((Y-Yforecast)/Y)*100
where Y can be any market variable for stocks, indices or commodities, %F measures
the percent
deviation of the actual value from its forecast. In a trading market, %F changes its
sign before a
significant trend change. In trending markets, %F tends to change sign early in the
trend. I interpret %F in
the context of the r 2 Of the regression. A low value of r 2 plus a change in sign of %F
is a good signal of a
change in trend. Market extremes and periodicity can also be observed on the %F
charts.
DEVELOPING A TRADING PLAN
You can use the forecasts to develop a specific trading plan to suit your trading style.
I use the forecasts
in several ways.
Forecasts as stops. I use the high and the low as action points. If the market exceeds
the forecast high, it
wants to go up. To trade with the trend, I put a buy stop a few ticks above the high. If
the market falls
below the forecast low, it wants to go down. Hence, I set a sell stop a few ticks below
the forecast low. If
you want to trade against the trend, sell short near the forecast high and buy near the
forecast low.
Forecasts as intraday range scale. The forecasts provide a scale for evaluating the
trading day. The
market can stay within the expected range or go outside. On a down day, the intraday
high is well below
the forecast high and may be below the forecast close. On an up day, the market stays
well above the
forecast low and often above the forecast close.
General rules for trading with forecasts. Here are some general rules:
• Use the forecasts only if r 2 is greater than 0.1. Higher the value of r 2 , the greater
the confidence in the
forecasts.
• A trend change is imminent when r 2 falls below 0.1. Prepare to close longs.
• A trend is in place if r 2 is greater than 0.6. As a trend follower, you could wait for
this value to be
exceeded before opening positions. This would keep you out of short-term
fluctuations.

386
• An early warning of a trend change is provided by a zero-crossing of %F, the
forecast oscillator.
Prepare to tighten stops and look for changes in slope and coefficient of determination
for
confirmation.
•A change in trend is confirmed by a change in slope of the regression. Open
positions in direction of
trend change. To trade against the trend, look for peaks in slope and strength of the
linear trend.
•The trend will usually change in the direction of %F.
•Always be prepared for a market move against the forecast. Use stops!
A SAMPLE TRADING PLAN
I have developed a forecast for the high, low and close for January 20, 1992, from the
previous five trading days, seen in Figure 1. The market was making new highs the
previous week. Was a downward movement imminent? Let's look at the data from
Friday, January 17, 1992: The market was trending moderately (0.4<= r 2 <0.6), but
the forecast oscillator %F was negative for high, low and close, warning of a possible
change in trend. The relatively small slope of the regression for the high meant the
market was meeting resistance. The slope of the regression for the close had turned
down from the high values during the recent strong uptrend. The forecast, however,
called for a strong close near the highs of the day, but that seemed doubtful, given the
low slopes in a moderating trend. The plan was to watch for a change in trend. If the
market opened weak, a bearish strategy was called for. For example, I would consider
buying the Standard & Poor's 100 Index OEX January 390 puts, or selling
short the S&P 500 March futures contract.
The high daily volume of OEX index options traded makes the S&P
100 index an interesting application of me regression forecast
approach.
The market opened at the Friday close and weakness was evident at the open, as the
S&P 500 futures
opened lower. It was clear in early trading that the trend would be down, as the
market traded well below
the forecast high and close. Clearly, the forecast range provided a good scale, since it
reinforced the
concept that the market was weaker than the trend of the prior five days. A bearish
stance would have
been profitable.
THE NATURE OF REGRESSION FORECASTS
The high daily volume of OEX index options traded makes the S&P 100 index an
interesting application
of the regression forecast approach. I have examined a time period from early October
1991 to
mid-January 1992. The OEX close and its forecast are in Figure 2; the r 2 values in
Figure 3; %F in Figure
4, and Figure 5 has %F around the mid-November plunge.
Several observations can be made from the OEX analysis. First, the forecast lags the
OEX in an uptrend
or in a downtrend. Second, the close and the forecast cross over several days before a
trend change. This

387
crossover can be seen as a zero crossing in the %F chart. Significant trend changes are
preceded by
trendless periods with values of r 2 near zero. Strong trends are accompanied by high
values of r 2 and
regression slope. These observations support the general rules of interpretation noted
above. As Figure 5
shows, %F provided a timely warning of an impending trend change just before the
OEX fell 15.68 points.
I have included data for wheat (cash) from 1989 to indicate the use of this approach
with commodities.
The market showed significant trends during this period with good periodicity, as
shown in Figures 6, 7
and 8. The %F zero crossings were timely indicators of trend change. Features
observed with OEX charts
are also seen here; note in particular how %F can be used to identify extremes in the
market from Figures
4 and 8.
Simple linear regression yields forecasts of the high, low and close for stocks, indices
or commodities.
these forecasts can be used to develop a trading plan. You can trade with the trend,
against the trend,
intraday or interday. The forecast oscillator, %F, provides early warning of trend
changes taken together
with the regression slope and coefficient of determination. This approach works best
in trending markets
or trading range markets; it is only moderately useful in volatile markets with choppy
price action. These
objective forecasts will let you trade less emotionally and more mechanically. Profits
will look up when
you can look ahead.
Tushar Chande holds a doctorate in engineering from the University of Illinois and a
master's degree in
business administration from the University of Pittsburgh.
REFERENCES
Lafferty, Patrick [ 1991 ]. "A regression-based oscillator," Technical Analysis of
STOCKS & COMMODITIES,
Volume 9: September.
Merrill, Arthur [1991]. "Fitting a trendline by least squares," Technical Analysis of
STOCKS & COMMODITIES,
Volume 9: December.
Pfaffenberger, Roger, and James Patterson [1987]. Statistical Methods for Business
and Economics,
Irwin.
-----Original Message-----
From: owner-metastock@metastock.com [mailto:owner-
metastock@metastock.com]On Behalf Of Steve Karnish
Sent: Thursday, January 10, 2002 10:34 AM
To: metastock@metastock.com
Subject: Forecast Oscillator

388
List,

Does anyone have the math formula for Chande's Forecast Oscillator?

Thanks,

Steve

From my archives.....I found three different formulas for the True Strength Index:
1. rr:= Input("first smoothing r" ,1 ,100 ,25 );
ss:= Input("second smoothing s" ,1 ,100 ,13 );
uu:= Input("third smoothing u",1,100,1);
numerator:=100*(Mov(Mov(Mov(ROC(C,1,$),rr,E),ss,E),uu,E));
denominator:=Mov(Mov(Mov(Abs(ROC(C,1,$)),rr,E),ss,E),uu,E);
If(denominator<0,numerator/denominator,0);
2.
100*(Mov(Mov(ROC(C,1,$),40,E),20,E)/Mov(Mov(Abs(ROC(C,1,$)),40,E),20,E))
3. rc:=Mov(Mov(ROC(C,1,$),40,E),20,E);
rc1:=If(rc=0,1,Mov(Mov(Abs(ROC(C,1,$)),40,E),20,E));
100*(rc/rc1)
Take your pick. <g
Claud
neo wrote:
Would you mind posting the formula?Thanks
-----Original Message-----
From: owner-metastock@metastock.com [mailto:owner-
metastock@metastock.com]On Behalf Of William Gross
Sent: Wednesday, January 02, 2002 2:23 PM
To: metastock@metastock.com
Subject: True Strength Index
Has anyone system tested to see if the 25/13 periods used in the formula for
theTrue Strength Index in the Active Trader Magazine article this month is
better or worse than some alternatives (like 17/9)? Especially on a 15 minute
chart... William GrossVenice CA

389
FORECAST OSCILLATOR

ForecastOsc
or
{Forecast Osc-Chande}
{from jseed}
Pds:=Input("Time Periods",1,1000,5);
Fld:=Input("Price Field 1=C 2=O 3=H 4=L",1,4,1);
PFld:=If(Fld=1,C,If(Fld=2,O,If(Fld=3,H,L)));
Sig:=Input("Signal MA Periods",1,200,3);
ForO:=((Pfld-(Ref(LinearReg(Pfld,Pds),-1)+
Ref(LinRegSlope(Pfld,Pds),-1)))*100)/Pfld;
ForO;
Mov(ForO,Sig,E);
{end}

Jeff,

Try applying this method to Nokia (8% band around the FO), Intel (7%),
Goldman Sachs (6%-see attachment). Don't forget to set system tester to -1
and open. This will initiate your trades on the opening of the following
day you trigger a signal.

Time travel into the next quarter and you will find the above issues being
traded as part of the 50-75 "single stock futures". Then, with a ~$135 in
profits (GS over the last two years), imagine how much fun it would be with
only 20% margin. I can't wait until the "series 7" idiots start to trade in
this arena.

Take care,

Steve
----- Original Message -----
From: Jeff Haferman <Jeff_Haferman@yahoo.com
To: <metastock@metastock.com
Sent: Wednesday, January 23, 2002 8:50 AM
Subject: Re: Forecast Oscillator

Thanks Steve,
I'll study this.

I'm very familiar with your site, I've been learning from it for
the last couple of years ;)

Jeff

390
Steve Karnish wrote:

Jeff,

Chande has the finest indicators (my humble, subjective opinion) I have
ever
"eyeballed". Unfortunately, I have never read or seen anything that
would
suggest that Chande knows how to apply "rules" to his fine work. I'm
sure
he uses them well, but I can find nothing that hints at his approach.

The Forecast Oscillator can be a real gem. I like to use a 13 period FO.
Typically, stocks that fluctuate more than 10% from the Forecast
Oscillator
seem to perform the best under testing. A simple optimisation would look
like:

Enter Long:
Cross(opt1,ForecastOsc(CLOSE,opt3))

Close Long:
Cross(ForecastOsc(CLOSE,opt3),opt2)

I like to use 13 as a default for opt3 (or you can test). opt1 is the
trigger level to trigger a long trade and opt2 triggers the sell to
offset
the position. If you are testing commodities or the Q's, just change the
"Close Long" to Enter Short. If I know a stock ranges up to 15% from the
linear regression formed by the Forecast Oscillator, I will test for
points
between 1 and 15, stepping up a point (1) and -1 to -15. Because of the
way
the formula is written, you must change the optimisation levels for each
test. Some stocks don't trade beyond a percent or two of their price.
Testing whole numbers above "one" wouldn't do you any good (under those
circumstances).

Attached is a chart of ERTS (I trade the stock publicly, at my site, with


different rules), showing the FO13 and triggers of +10/-10 (I only use
symmetrical triggers). During the last two years, it has triggered 11
winners and one loser.

Anyway, this is just one way to use it.

Take care,

Steve

391
CHANDE'S DYNAMIC MOMENTUM INDEX

'DMI is a momentum index that uses a variable length (number of days)


determined by the volatility
'in price. If volatility is low, the calculation uses a long period. If
volatility is high, the
'calculation uses a short period.
'
'The number of days is determined as follows:
'
'Std5 = Standard Deviation of the Close over past 5 days
'AvgStd = 10 day Average of Std5
'V = Today 's Std5 / AvgStd
'TD = Int(14 / V)
'
'Note that if the Std5 is greater than AvgStd then V will be greater than 1
and Td will be
'less than 14. If Std5 is less than AvgStd then V will be less than 1 and Td
will be greater
'the 14. Td is limited to the range 5 to 30.
'
'Td is used as the period for calculating RSI ( Relative Strength Index ).
'
'Reference:
'Chande, Tushar S. and Kroll, Stanley.

392
'The New Technical Trader, New York: John Wiley, 1994.

HTH, Andreas

-----Ursprungliche Nachricht-----
Von: owner-metastock@metastock.com
[mailto:owner-metastock@metastock.com]Im Auftrag von rudolf stricker
Gesendet: Sonntag, 3. Februar 2002 17:38
An: metastock@metastock.com
Betreff: Re: momentum indicators, using also o-h-l

On Thu, 31 Jan 2002 06:09:07 +0000, you wrote:

Check your Metastock Manual for interpretation of Qstick. It


has about a
page of discussion. The manual says that Qstick is the moving
average of
the difference between the open and close.

So Qstick seemingly is rather a trend indicator than a momentum


indicator, (which I'm looking for, see the subject).
Maybe, I should start with a given momentum indicator e.g. Chande's
"Dynamic Momentum Index", and integrate o-h-l in an appropriate manner
into it...

Is the formula for the DMI available somewhere?

mfg rudolf stricker


| Disclaimer: The views of this user are strictly his own.

393
ADAPTIVE SYSTEMS

----- Original Message -----


From: "John Manasco" <john@manasco.net
To: <metastock@metastock.com
Sent: Wednesday, February 06, 2002 8:01 PM
Subject: Re: adaptive systems - how to define appropriate time windows ?
Here is a discussion from another email list on adaptive systems.

Adaptive systems is pretty complicated matter. There are several known ways of
doing it, at least about 4. The math is not too complicated but arcane and the concept
is hard to comprehend. There are several questions:
• what does adaptive system mean?
• what do you adapt it to?
• what to adapt?
• what do you adapt it based on? how do you do it?
• what is the math?
• how to you implement it in code?
• is it doable?

Adaptive means the system's algorithm tunes itself up as the "market footprint"
changes to maximise the performance criterion which is max reward at min risk. If
you want to discuss adaptive first you have to discuss non adaptive systems like the
ones you can code in TSs. The main objective of any system is to find the balance in
between the risk and the reward - which is the main criteria. in TS we do that by
running optimisation and finding the suitable peak in the optimisation function.
Optimisation function (OF) has a dependent and independent variables. Dependent
variables are Max Profit (MP) and Min Risk (MR), independent are your parameters /
inputs ( I )
example: if you have 3 inputs 3 Is your OF will is 4 or 5 dimensional ( 3 Is + MR +
MP ). this could be graphically representing as a multidimensional surface. the key is
to find the peak of that surface( that's why if system has more
than 3 inputs I toss it ) - hard to do because it's hard to visualise. You can see now that
if a system does not adapt you have to find the peak manually or you have to
compromise. *most systems fail because they are not
adaptive - curvefitted!!!

So, the purpose of adaptive system is to find that peak in OF in real time. To know the
peak you need to know the OF. to know OF you have to know: MR, MP, and all Is.
let's break it down. MR and MP: you have to calculate systems performance in real
time. But the system does not know how it performs itself. it needs some criteria to go
by. how can a system know if it works on all cylinders and bangs out max profit at
min reward or just barely making it? you have to give it a reference to go by. this ref
performance is called system efficiency (SE). SE is calculated in % by comparing in
real time the performance of real system to the performance of ideal system. Another
term needs to be introduced - ideal system. Ideal system buys the very top and sells
the very bottom. you can easily calculate that buy coding a function that will sell and
buy in hindsight and give you max possible profit at zero risk. now, then you take

394
ideal system as 100% efficiency, then your SE = real performance / ideal
performance. say your average SE = 30% that means you are pulling out 30% or what
you can pull out of the market. this becomes the criterion to go by in adaptation or
Max SE. this can fluctuate from Min allowable SE say 20% to 100% ( will never be
100%). Based on statistical runs you can then calculate mean SE to go by, say 30%.
now you know what to adapt to.

next is what to adapt:


well, obviously you have to adapt your parameters or inputs - your Is. you have to
tune your inputs to get the highest SE. that's where it gets real tricky. to be able to do
that you need OF- you need that curve to tell you what the parameters should be to get
max SE. let's leave this out for a second. next is what do you adapt based on:
you adapt based on changing market conditions or what I call changing "market
footprint". every instrument traded out there has it's own particular market footprint
which is: a compilation of statistical variables common
to all instruments, like: average true range ( bar velocity), average volatility, volatility
std, average volume, liquidity and so on. footprint is a set of statistical parameters that
you can use as fingerprints To identify and differentiate between different instruments
you trade. this footprint will change in real time... volatility will fluctuate, so will
volume, average bar range, etc. one day SP can trade real narrow range with low
volume, the next day volatility can explode - market footprint changed.

Next is how to adapt it. well, the first thing that should pop into your mind is that you
need a feedback loop of some sort. The rational loop is this:
footprint changed -adjust parameters -
to maximise SE ratio -if SE drops means
footprint changed -repeat.
if you examine this loop you'll notice that
you need at least 2 functions ( transfer functions )
to do that:
1. parameters = f ( footprint )
2. SE = f( parameters )
of you can rewrite it as:
SE = f ( f ( footprint ) ); tells you systems
efficiency will fluctuate based on changing
market conditions.
so where do you get those functions:

a. from a sample run: you do a pass over data, build your OF function and then build
your parameter = f( footprint ) function. log it in and use it for the real time run. you
can keep updating those functions in real time. this is similar to manual optimisation
where you do sample runs but in addition to that the OF gets updated in real time.

b. ramp up period. you start with a ramp up period and update your 1 and 2 functions
as you go along
your SE will start with 0% and will be improving as those functions will be more and
more accurate.
the system like this will start trading real bad and then improve it's performance as it
adapts and learns to trade better and better. the performance will taper off and
stabilise as those functions are saturated.

395
c. multiple parallel models: you run multiple systems based on different parameters
and find the best performing one under changing market footprint and trade that best
one. This approach however does not guarantee that the best performing current
model will continue to be the best tomorrow.

John Clayburg implemented this approach by running parallel performance functions


in TS. It showed a little bit of improvement but not much. The reason again that you
are chasing the best performing model that will not necessarily continue to perform
good tomorrow ( best fit today is not necessarily will be the best fit tomorrow )

d. my approach. since I already went through all of the bs in paragraphs a through c


what I do is the direct analytical approach - a shortcut. I ask myself a question – how
this specific market variable will affect my SE ( systems efficiency, performance ) or
my P&L through direct math. First I try to tie as many parameters to market footprint
( market variable ) it allows me to make a shortcut and I don't have to find parameter
= f ( market footprint ) function. market footprint becomes the parameter itself. Next,
I try to answer the question of how will this market variable affect my PL analytically
- I try to find SE = f ( footprint ) function by studying how, say, volatility affects my
PL in the signal generator. if market becomes noisy how will it affect my PL in the
system. the answer is simple: more noise you got less money you make. Last step is to
measure market variable ( market footprint ) and through those functions adjust your
algorithm to pump up your SE. This is the right approach and the best one. In short,
your adaptive techniques should be built right into your trading algorithm.

define market footprint ( which market variables hurt or improve your systems
performance ) then:
• use those as your parameters so that the market will itself adjust those for you then

• define your signal generating algorithm to include


• those parameters and specify how those will affect your systems performance.
-specify how your trading algorithm should change based on that parameter.
that's it. it becomes self adaptive.
an example:
• market footprint = noise level
• noise level = your parameter
• more noise -less profit
• less noise -more profit.
if more noise then increase risk and lengthen time horizon to maximise profit
and minimise loss.
if less noise then decrease risk and shorten time horizon to maximise profit
and minimise
loss.

a common parameter is lookback. in MA. Well, going by what is said is MA


lookback has anything to do with a market footprint market variable - nope.
You can't differentiate markets by MA lookback - toss it.
another common lookback variable - ATR ( lookback ) –defines a lookback in
average true range calculation. Can ATR be used as a market variable to

396
define market footprint? possibly can. that's why ATR often referred to as
"adaptive" variable - changing. but even ATR can vary based on lookback
used. so, it's semi adaptive, you still have the lookback to deal with.

It is self evident that the first step in designing adaptive systems is to define market
footprint in variables that require no parameters or allow only parameters will not
affect variable measurement itself. If you try to define noise through ATR then ATR
is dependent on lookback unless the lookback value is high. If lookback value is high,
ATR will not be sensitive to it's most recent change. :-) go figure.

Volatility also requires lookback. Almost everything there needs a damn lookback or
a factor. However if you isolate the most recent swing (current trade) in the price and
find pivot high and pivot low and find the duration of that swing and use that duration
as a lookback then what your saying is that I only want to measure noise during the
most current trade that I am in.. This becomes adaptive lookback and ATR becomes
adaptive. then your market variable can be called - ATR of last tradable swing... and
not ATR of some arbitrary lookback that you think is suitable.

At the end it all comes down to about 4-5 market variables that you need to define and
most of them have to do with
volatility in one form of the other. Volatility is the main market variable!

• untradable volatility = noise = risk = lag


• min tradable volatility = vector deviation = min signal = reward = profit or loss
differential.
• max tradable volatility = vector volatility = max signal = trend = sum of all
positive and negative profit differentials ( profitable and unprofitable trades - risk
and reward )= your total P&L.
• find noise then you can find the signal
• find the signal then you can find the trend.
• find the trend then you are done just don't use any fixed lookbacks and factors :-)

This is pretty much it without any hard math thrown in.


bilo.
P.S. markets are dynamic, most systems are static that's why most systems don't
work. and if you add irrational buy and sell rules on top of many input parameters,
they don't work at all.

----- Original Message -----


From: "rudolf stricker" <lists@tbus-muc.de
To: <metastock@metastock.com
Sent: Wednesday, February 06, 2002 12:16 PM
Subject: adaptive systems - how to define appropriate time windows ?

List,

using an adaptive system for day-to-day trading of DAX options, I wonder, which

397
criteria might be helpful to define "the best" time window to deal with ...
Presently, I use a 5 years window, where the rating criteria to select an appropriate
system are weighted something like exponentially over time.

But at these rapidly changing markets, I get some unsatisfactory results: While my
system shows nice results e.g. for long puts over the last year or so, this potential
couldn't be used: my money management (based on 5 years) nearly stops me out
from trading these system results, because the strategy working well for the last
year
doesn't show good results for at least some of the years before.

So my questions are:

• What time period may be appropriate to construct a(n adaptive) trading system for
a given equity?
• What criterions (to read from the equity's historical data) could help to define "the
best" time period?
• What other aspects may be important to define an appropriate time window?

Any hint is welcome ...

mfg rudolf stricker


| Disclaimer: The views of this user are strictly his own.

I'm not sure what you're looking for. What are you trying to adapt to? If you are trying
to adapt your system to the current cycle length look at some of Dr. John Elhers
indicators that measure cycle length. If you're trading
options why not make the system adaptive to current or historical volatility.
Personally I don't believe a "best" time period exists. That is too restrictive for me. A
strongly trending stock will probably have a long cycle length while that same stock
may have a very short cycle length if it is in a trading range. The problem with cycle
lengths is that they are based on the past and not the future but they may provide a
best guess as to the future cycle length.

398
ON BALANCE VOLUME

You will get a better feeling for open interest influence if you combine it with
an on-balance-volume indicator. The best combination I found is OBVtd=
OBVyest.+((
Close-open/ high-low)*VOLtoday). Try it, you'll like it. Ira

Stewart Taylor wrote:

Hi Stig;

My interpretation of the OI drop is a bit different than yours. I consider


a drop in OI as potentially bullish when it accompanies a violent/spike low
or after a long trend.. hthe main requirement is that it occur over a
relatively short period of time... My interpretation is that the last long
that needed to capitulate capitulated and made the low and now buyers can
begin to operate.

Over a long period (like on the gold chart) I suspect that it is more an
indication of lack of interest than anything else... funds don't employ
margin in markets that are in trading ranges and markets in long-long
trading ranges don't attract the trading publics attention.

The good news... low levels of OI suggest that there is margin available to
be deployed and support the trend (which ever way it materializes).

Just another interpretation...

Stew.

At 04:24 AM 2/8/2002 , StigO wrote:


part II
Technical indicators is, in my opinion very bullish.

I brushed up on Drummond this morning to check open Interest. And he is very clear
when he says that falling OI at bottoms are very bullish (all the shorts are closing their
poitions and new longs don't have the courage to buy - yet)
Check out the lower histogram and how OI has declined since the 1999 low The
middle indicator STRSI shows a very promising "hidden Divergence" very reliable
and bullish.

The pink histogram is Robert Miners Dynamic time Projection, which projects trend
changes with the help if past tops/bottom and fib ratios. Looks like the next top will
be around March 15 (Spring Equinox March 20 which is notorious for trend changes
in Gold!!)

So all in Medium term bullish for Gold.

The June Gold contract is next.

399
To cut out the noise I have used closing prices, which gave sone surprising result not
evident on Bar charts.

The chart suggests we have broken many levels.


1. The 38,2 fib retracement og the AC decline
2. The 50% retracement of the BC decline which O associate to the 3 tops which
also has been broken
3. No matter how you draw the trendlines they have been broken 3 days ago - 2 days
ago they were tested and yesterday we took off again
4. If we break the 61.8% retracement level (at 302)of the BC decline it looks VERY
promising (we are at 306 right now)
5. 2 forks with 50% offset (black and blue) have also been broken at the trendline
level.

If you use bar charts you get quite different meaningless result -try it out. Since
most people use barcharts today (I guess), what you see in the close only chart is
not so evident. Fridays are good days for explosions - let's see what happens
today....

Thanks D for poking at me - now I am convinced - I'll keep my DROOY for a


while longer.

Regards
Stig

400
Book List

GANN

How to Trade Using the Methods of W.D. Gann. by william McLaren,


Profits in the Stock Market by H.M. Gartley
The Truth of the Stock Tape by W.D. Gann
How to Make Profits in Commodities by W.D.Gann
Tunnel Through the Air by W.D.Gann
The W.D.Gann Stock Market Course by W.D.Gann
The W.D. Gann Commodity Course by W.D.Gann

LIST OF BOOKS AND COURSES:

1997 Advanced Get Seminar manual


Advanced Get manual
K. Anand – The Science of Automatic Option Profits
G. Angell – Profitable Day Trading with Precision with audio tape
G. Angell – Advanced Breakthroughs in Day Trading
G. Angell – The Essential Secrets of Day Trading
G. Angell – Agricultural Options
G. Angell – Floor Trader’s Confidential Handbook
G. Angell – West of Wall Street
M. Arnold – Trading on tomorrow’s headlines
R. Barach – Mindtraps –Mastering the inner world of investing
R. Barnes – High Impact Day Trading
R. Barnes – Trading in a choppy market
J. Berstein – How the Futures Market Works
J. Berstein – Seasonal Trader’s Bible
J. Bernsatein Cyclic Analysis in Futures Trading
T. Bierovic – Synergetic Technical Analysis 3 vols plus 3 audio tapes
W. Bressert – The Power of Oscillator/Cycle Combination
M. Boucher – The Science of Trading – manual plus 11 audio tapes
- RSI course
K. Calhoun – 5VBTP manual plus indicators on TS
K. Calhoun - Commodity Trading Manual – Eight $10k trading Systems
K. Calhoun – 5 commodity lesssons video tape
D. Caplan – The new options secret volatility
D. Caplan – Opportunities in Options – Options Strategy Guide
D. Cassiday – It is when you sell that counts
C. Alexander - Five Start Future Trades
L. Connors & B. Hayward – Investment Secrets of a Hedge Fund Manager
L. Connors Connors on Advanced Trading Strategies plus indicators on TS
L. Connors & L. Raschke – Street Smart plus indicators on TS
J. Conway – Rhythm of Markets: Ed Moore’s Trading Methodology
T. Crabel – Day trading with Short Term Price Patterns

401
J. Crane – A Traders Handbook – The Reversal Day Phenomenon
J. Cooper – Hit & Run I plus indicators on TS
J. Cooper – Hit & Run II
J. Cooper – 5 Day Momentum Method plus indicators on TS
B. Cowan _ Geometry of the Markets _ 4 vols
J. Cuddy – Market Turning Point Detection
J. DiNapoli – Trading DiNapoli’s levels plus software
M. Douglas – The Disciplined Trader
J. Duffy – Pulsar Trading System
J. Duffy – Turning Point Analysis in Price & Time
Dynamic Gann Levels manual
A. Elder – Trading for a Living Book
A. Elder – Trading for a Living Guide
W. Eng – The Day Trader’s Manual
B. Farrell – Day Trade Online
D. Fishback – ODDS – The Key to 90% Winners booklet
G. Fontanils – Optionetics – manual plus 11 audio tapes
M. Friedfertig – The Electronic Day Trader
N. Gandevani – The Winning Edge Day Trading System
N. Gandevani – Winning Edge Advanced Trading Strategies
W. Garrett – Torque Analysis
L. Gettess- Scorpion – my personal trading system
A. Gietzen – Real-Time Futures Trading
C. Gilmore – Dynamic Time & Price Analysis of Market Trends
C. Goslin - Intelligent Futures Trading

G. Heffernan – Accutrader system


E. Hurwitz – Visual Trading Method H.E.L.P. seminar manual plus 2 audio tapes
J. Hyerczyk – Pattern Price and Time Inversion Point System
J. Jackson – Detecting High Profits Day Trades in Futures Markets
M. Jenkins – Chart Reading for Professional Traders
M. Jenkins – The Geometry of Stock Market Profits
D. Jobman – The Handbook of Technical Analysis
E. C. Kase – Trading with the odds plus indicators on TS
P.J. Kaufman Trading systems and methods
P.J. Kaufman Smarter trading
R. Kinsman – Hidden Patterns
R. Krausz - The Gann Treasury Discovered
R. Jones – Eight Secrets to Amassing $1 Million within 5 years
M. Jurik – Computerized trading
S. Krieger – How to become real time commodity futures trader
J. Krutsinger – Trading Systems – Secrets of the Masters
H. Lloyd – The RSL Market Timing System
G. Marisch's "W.D Gann Method of Trading
McMillan – McMillan on Options
R. Miner – Dynamic Trader trading Course
R. Miner – Dynamic Trading
T. Mitchell – How to Profitably and Consistently Make Money Day Trading S&P –
manual + video tapes
E. Moore – Rhythm of the Markets: Option Magic

402
A. Namrevo – The S.I.M.P.L.E. system
S. Nison – Beyond Candlesticks
S. Nison – Japanese Candlesticks Charting Techniques
H. Neill _- The Art of Contrarian Thinking
G. Noble – The Trader’s Edge plus audio tape
W. O’Neil – How to make money in stocks
O’ Shaugnessy – What works on Wall Street
L. Pesavento – Fibonacci Ratios with Pattern Recognition
L. Pesavento – Planetary harmonics of speculative markets
R. Pardo – Design, testing and optimization of trading systems
The Pitbull Investor – Guide to Shorting Hi-Performance Stocks
- The Eagle – I Options Speculator
- Stock market Crash Forecaster
- A Disciplined Tactical Stock Investment System
F. Putt – Using Easy Language

G. Raff – Trading the Regression Channel


K. Roberts – The World’s most powerful money manual
J. Ross – TNT I
J. Ross – TNT II
J. Ross – How to Place Trading Orders – manual + 4 audio tapes
J. Ross – Trading is a business
J. Ross – Trading by the minute
J. Ross – Trading by the book
J. Ross – Trading Options and Futions
J. Ross – Trading the Ross Hook
J. Ross – Trading Spreads and Seasonals
G. Rudd – Stock Patterns for Day trading vol. 1

R. Sands – Turtle Secrets


N. Sambul – Top Trader’s Guide to Technical Analysis
P. Shaughnessy – 1992 P&L seminar ( Drummond Geometry)
M. Silber& J. Bernstein – Stochastic Fantastic
G. Smith – Live the Dream by Profitably Day Trading Stock Futures
J. Snyder – The Way of the Hunter Warrior
V. Sperandeo – Trader Vic II
K. Staley – The Art of Short Selling
P. Steidlmayer – Steidlmayer on Markets

GD Taylor The Taylor Trading Technique


H. Taylor – Mastering Foreign Exchange & Currency Options
The Tradehard.com- Guide to Conquering the Trading Markets
M. Turner – Day Trading into the Millennium

R. Vince – The New Money Managament


D. Vodopich – Trading for Profits with Precision Timing

J. Walker – Short Selling

403
M. Walker – How to identify High Profit Elliott Wave Trades in Real Time
B. Warrick – Event Trading
R. Wasendorf – Foreign Currency Trading
D. Weis – Trading with Elliott Wave Principle
N. Weintraub – Tricks of floor trader
R. Weist – You can’t loose trading commodities
W. Wilder – The Delta Phenomenon Book plus software
B. Williams – Trading Chaos
B. Williams – New Trading Dementions
L. Williams – Long Term Secrets to Short – Term Trading
L. Williams – Sure Thing Commodity Trading
L. Williams – How I made 1 million trading commodities
L. Williams – The Money Tree course
L. Williams – The secret of selecting stocks for immediate and substantial gains
L. Williams – The Definitive Guide to Futures Trading vol. 1
L. Williams – The Definitive Guide to Futures Trading vol. 2
B & B Wolfe – Seeing the Future ( Trading the Wolfe Wave)
C. Wright – Trading is a business

404
RWI

Purpose: Calculates the high and low Random Walk Indicator

Description: The Random walk indicator is used to determine if an issue is trending


or in a random trading range. It attempts to do this by first determining an issue's
trading range. The next step is to calculate a series of RWI indexes for the maximum
look-back period. The largest index move in relation to a random walk is used as
today's index. An issue is trending higher if the RWI of highs is greater than 1, while
a downtrend is indicated if the RWI of lows is greater than 1.

PowerScript: RWI (ByVal term As Integer, hiArray As Object, loArray As Object)


As Integer Parameters:

Formula: ATR = Average Trading Range


RWI high = (High - LowN) / ATR * n sqrt(n)
RWI low = (HighN- Low) / ATR * n sqrt(n) Interpretation:

405
KNewPeakindicator

Inputs: f(2), password(5),n1(8),n2(65);

value50 = kpo(password,n1,n2);
value1= (AVERAGE(absvalue(value50),50))
+ (F*(StdDev(absvalue(value50),50)));

value4 = maxlist(100,value1);
value2 =minlist(100,value1);

Plot1(value50, "PeakOsc");

if value50 > 0 then value6 = value4 else value6 = -value4;


Plot2(value6,"PeakOut");

if value50[1] > 0 and value50[1] >value50 and value50[1] >= value50[2] and
value50[1] >= value4 then begin
plot3(value50[1],"PeakConfirm");
end;

if value50[1] < 0 and value50[1] < value50 and value50[1] <= -value4 and
value50[1] <= value50[2] then begin
plot3(value50[1],"PeakConfirm");
end;

if value50 > 0 then value23 = value2 else value23 = -value2;


Plot4(value23,"PeakMin");

KPeak Oscillator

Inputs: f(2), password(5);

value50 = xpo(password);
value1= (AVERAGE(absvalue(value50),50)) + (F*(StdDev(absvalue(value50),50)));

value4 = maxlist(100,value1);
value2 =minlist(100,value1);

Plot1(value50, "PeakOsc");

if value50 > 0 then value6 = value4 else value6 = -value4;


Plot2(value6,"Peak-Out");

if value50[1] > 0 and value50[1] >value50 and value50[1] >= value50[2] and
value50[1] >= value4 then begin
plot3(value50[1],"PeakConfirm");

406
end;

if value50[1] < 0 and value50[1] < value50 and value50[1] <= -value4 and
value50[1] <= value50[2] then begin
plot3(value50[1],"PeakConfirm");
end;

OKS & PeakOscillator

Inputs: f(2), password(5);


value50 = xpo(password);
value1= (AVERAGE(absvalue(value50),50)) + (F*(StdDev(absvalue(value50),50)));
value4 = maxlist(90,value1);

if value50 >0 then begin


Plot1(value50, "PeakOsc");
end;

if value50 <0 then begin


Plot3(value50, "PeakOsc");
end;

if value50 > 0 then value6 = value4 else value6 = -value4;


Plot2(value6,"Peak-Out");

if value50 > 0 then value23 = value1 else value23 = -value1;


Plot4(value23,"Peak-Outx");

KCD Indicator

Inputs:password(5);

value1 = xkcd(password);

if value1 >0 then begin


Plot1(value1, "KaseCD");
end;

if value1 < 0 then begin


Plot2 (value1, "KaseCD");
end;

407
Kperm Fn

Inputs:LENGTH(9),X(5),password(5);

Plot1(XPermLong(LENGTH,X,PASSWORD), "PermLong");
Plot2(XPermShort(LENGTH,X,PASSWORD),"PermShort");

1st Class Shorts

Inputs:password(5);
if xAvg(password) = 011784021852 then begin
Vars: TrK(0),TrDF(0), TrDS(0),factor(0);
Value1 = Lowest(Low,(5*9));
Value2 = Highest(High,(5*9)) - Value1;
Value3 = Close;

If Value2 > 0 then


TrK = (Value3 - Value1) / Value2 * 100
Else
TrK = 0;

If CurrentBar <= 1 then begin


Factor = 2 / (3 + 1);
TrDF = TrK;
End
Else
TrDF = TrDF[5] + (Factor * (TrK - TrDF[5]));

If CurrentBar <= 1 then TrDS = TrDF


Else
TrDS= ((TrDS[5] * 2) + TrDF) / 3;

value1 =average(average(trDS,3),2);
value2 =average(average(TrDF,3),2);

condition1 = value1>85 and value2>85 and (absvalue(value2-value1) <2);


condition2 = value1<(100-85) and value2<(100-85) and ((value2-value1) > 2);
condition3 = value2>(100-85) and ( value2>value1);

if condition1 = true or condition2 = true or condition3 = true then value8 = 10 else


value8 = 0;

value99 = MACD(Close,5,34) -
XAverage(MACD(Close,5,34),8);

VALUE98 = (RSI(CLOSE,9)) - (AVERAGE(RSI(CLOSE,9),15));

408
if value98<0 and value8 = 0 then ploT1(HIGH,"short");

value50 = slowk(21);
value51 = slowd(21);

if value99<0 and value8 = 0 then plot2(low,"short");


condition11 = value50>85 and value51>85 and (absvalue(value50-value51) <2);
condition12 =value51<(100-85) and value50<(100-85) and ((value50-value51) > 2);
condition13 = value50>(100-85) and ( value50>value51);
if condition11 = true or condition12 = true or condition13 = true then value18 = 10
else value18 = 0;
if value18 = 0 and value8 = 0 then plot3(medianprice,"short");
end;

1st class longs

Inputs:password(5);
Vars: TrK(0),TrDF(0), TrDS(0),factor(0);
if xAvg(password) = 011784021852 then begin
Value1 = Lowest(Low,(5*9));
Value2 = Highest(High,(5*9)) - Value1;
Value3 = Close;

If Value2 > 0 then


TrK = (Value3 - Value1) / Value2 * 100
Else
TrK = 0;

If CurrentBar <= 1 then begin


Factor = 2 / (3 + 1);
TrDF = TrK;
End
Else
TrDF = TrDF[5] + (Factor * (TrK - TrDF[5]));

If CurrentBar <= 1 then TrDS = TrDF


Else
TrDS= ((TrDS[5] * 2) + TrDF) / 3;
value1 =average(average(trDS,3),2);
value2 =average(average(TrDF,3),2);
condition1 = value1>85 and value2>85 and (absvalue(value2-value1) <2);
condition2 = value1<(100-85) and value2<(100-85) and ((value2-value1) > 2);
condition3 = value2>(100-85) and ( value2>value1);
if condition1 = true or condition2 = true or condition3 = true then value8 = 10 else
value8 = 0;

value99 = MACD(Close,5,34) -

409
XAverage(MACD(Close,5,34),8);
VALUE98 = (RSI(CLOSE,9)) - (AVERAGE(RSI(CLOSE,9),15));
value50 = slowk(21);
value51 = slowd(21);

condition11 = value50>85 and value51>85 and (absvalue(value50-value51) <2);


condition12 =value51<(100-85) and value50<(100-85) and ((value50-value51) > 2);
condition13 = value50>(100-85) and ( value50>value51);
if condition11 = true or condition12 = true or condition13 = true then value18 = 10
else value18 = 0;

if value99>0 and value8 = 10 then plot1(high,"long");


if value18 = 10 and value8 =10 then plot2(MedianPrice,"long");
if value98>0 and value8 = 10 then plot3(LOW,"long");

end;

KCDL Piercing

Inputs:Thold(75),password(5);
Vars:BodySize(0),x(0);
if xavg(password)= 011784021852 then begin
x = 0.2*Average((high-low),5);

{============================================================
===}
if open < close then value1 = close;
if open < close then value2 = open;
if open > close then value1 = open;
if open > close then value2 = close;
if open = close then value1 = open;
if open = close then value2 = open;

{BULLISH PIERCING}

value99 = (value1 - value2);


BodySize = Average(value99,50);

if value99 = (bodysize/2) or value99 > (bodysize/2) then begin


if slowk(13) <(100 - Thold) and
close > open and
open < value2[1] and
close > ((value2[1] + value1[1])/2)
AND CLOSE < VALUE1[1] then
plot1(low-x,"piercing");

410
{BEARISH PIERCING}
if slowk(13) >(Thold) and
close < open and
open > value1[1] and
close < ((value2[1] + value1[1])/2)
AND CLOSE > VALUE2[1]then
plot2(high+x,"piercing");
end;
end;

KSDangerLong & Short

inputs:password(5);

if XD(password) = 1 then plot3(MedianPrice,"long");


if XD(password)= -1 then plot4(medianprice,"short");

KS2 Longs & Warning

Inputs: password(5);

Vars: TrK(0),TrDF(0), TrDS(0),factor(0);


if xAvg(password) = 011784021852 then begin
Value1 = Lowest(Low,(5*9));
Value2 = Highest(High,(5*9)) - Value1;
Value3 = Close;

If Value2 > 0 then


TrK = (Value3 - Value1) / Value2 * 100
Else
TrK = 0;
If CurrentBar <= 1 then begin
Factor = 2 / (3 + 1);
TrDF = TrK;
End
Else
TrDF = TrDF[5] + (Factor * (TrK - TrDF[5]));

If CurrentBar <= 1 then TrDS = TrDF


Else
TrDS= ((TrDS[5] * 2) + TrDF) / 3;

value1 =average(average(trDS,3),2);
value2 =average(average(TrDF,3),2);

411
{from the top}
condition4 = value2 > value1 + (11.5);
if value2>(100-25) and ((condition4[1] = true and value2 < value2[1]) or
(condition4[2] = true and value2 + 4 < value2[2])) then value10 = 10 else value10 =
0;
{from the bottom}
condition14 = value2 < value1- (11.5);
if value2 < 25 and ( (condition14[1] = true and value2 > value2[1]) or
(condition14[2] = true and value2 - 4 > value2[2])) then value11 = 10 else value11=0;

value3 = close/100;

value99 = MACD(Close,5,34) -
XAverage(MACD(Close,5,34),8);

VALUE98 = (RSI(CLOSE,9)) - (AVERAGE(RSI(CLOSE,9),15));


condition11 = SlowK(21)>85 and slowD(21)>85 and (absvalue(SlowK(21)-
slowD(21)) <2);
condition12 =slowD(21)<(100-85) and SlowK(21)<(100-85) and ((SlowK(21)-
slowD(21)) > 2);
condition13 = SlowK(21)>(100-85) and ( SlowK(21)>slowD(21));

if condition11 = true or condition12 = true or condition13 = true then value18 = 10


else value18 = 0;

if value98>0 and value11 = 10 then plot3(LOW,"long");


if value18 = 10 and value11 =10 then plot2(MedianPrice,"long");
if value99>0 and value11 = 10 then plot1(high,"long");

if VALUE98<0 AND VALUE18 = 0 AND VALUE99<0 AND value11 = 10


then plot4(low - value3,"warnsht");

end;

KS2 Shorts & Warning

Inputs:password(5);

Vars: TrK(0),TrDF(0), TrDS(0),factor(0);


if xAvg(password) = 011784021852 then begin
Value1 = Lowest(Low,(5*9));
Value2 = Highest(High,(5*9)) - Value1;
Value3 = Close;

If Value2 > 0 then


TrK = (Value3 - Value1) / Value2 * 100
Else

412
TrK = 0;

If CurrentBar <= 1 then begin


Factor = 2 / (3 + 1);
TrDF = TrK;
End
Else
TrDF = TrDF[5] + (Factor * (TrK - TrDF[5]));

If CurrentBar <= 1 then TrDS = TrDF


Else
TrDS= ((TrDS[5] * 2) + TrDF) / 3;

value1 =average(average(trDS,3),2);
value2 =average(average(TrDF,3),2);

{from the top}


condition4 = value2 > value1 + (11.5);
if value2>(100-25) and ((condition4[1] = true and value2 < value2[1]) or
(condition4[2] = true and value2 + 4 < value2[2])) then value10 = 10 else value10 =
0;
{from the bottom}
condition14 = value2 < value1- (11.5);
if value2
< 25 and ( (condition14[1] = true and value2 > value2[1]) or
(condition14[2] = true and value2 - 4 > value2[2])) then value11 = 10 else value11=0;

value3 = close/100;

value99 = MACD(Close,5,34) -
xAverage(MACD(Close,5,34),8);
VALUE98 = (RSI(CLOSE,9)) - (AVERAGE(RSI(CLOSE,9),15));

condition11 = SlowK(21)>85 and slowD(21)>85 and (absvalue(SlowK(21)-


slowD(21)) <2);
condition12 =slowD(21)<(100-85) and SlowK(21)<(100-85) and ((SlowK(21)-
slowD(21)) > 2);
condition13 = SlowK(21)>(100-85) and ( SlowK(21)>slowD(21));
if value98<0 and value10 =10 then ploT1(HIGH,"short");

if value99<0 and value10 = 10 then plot2(low,"short");


if condition11 = true or condition12 = true or condition13 = true then value18 = 10
else value18 = 0;
if value18 = 0 and value10 = 10 then plot3(medianprice,"short");

413
if value10 = 10 AND VALUE99>0 AND VALUE98>0 AND
VALUE18=10 then plot4(high + value3,"warnlng");

end;

Permission stochastic

Inputs : length(9), x(5),password(5);


plot1(XPermK(length,x,password),"XPermK");
plot2(XPermD(length,x,password),"XPermD");

XPERMD

Inputs: Length(numericsimple),x(numericsimple),password(numericsimple);
if xAvg(password) = 011784021852 then begin
XPermD = average(average(XTDS(length,x,password),3),2);
END;

XPERM K

Inputs: Length(numericsimple),x(numericsimple),password(numericsimple);
if xAvg(password) = 011784021852 then begin
XPermK = average(average(XTDF(length,x,password),3),2);
END;

XPERM LONG

Input:length(numeric),x(numeric),password(numericsimple);
if xAvg(password) = 011784021852 then begin
condition1 = XPermd(length,x,password)>85 and
XPermk(length,x,password)>85 and (absvalue(XPermk(length,x,password)-
XPermd(length,x,password)) <2);
condition2 = XPermd(length,x,password)<(15) and
XPermk(length,x,password)<(15) and ((XPermk(length,x,password)-
XPermd(length,x,password)) > 2);
condition3 = XPermk(length,x,password)>(15) and
( XPermk(length,x,password)>XPermd(length,x,password));

if condition1 = true or condition2 = true or condition3 = true


then XPermLong=1 else XPermLong = 0

;END;

414
XPERM Short

Input:length(numeric),x(numeric),password(numeric);
if xAvg(password) = 011784021852 then begin
condition11 = XPermd(length,x,password) < (15) and XPermk(length,x,password) <
(15) and (absvalue(XPermk(length,x,password)-XPermd(length,x,password)) <2);
condition12 = XPermd(length,x,password)>85 and XPermk(length,x,password)>85
and ((XPermd(length,x,password)-XPermk(length,x,password)) > 2);
condition13 = XPermk(length,x,password)<85 and (XPermk(length,x,password)<
XPermd(length,x,password));

if condition11 = true or condition12 = true or condition13 = true then


XPermShort = 1 else XPermShort = 0
;END;

XD

inputs: password(numeric);

if xAvg(password) = 011784021852 then begin

Vars: TrK(0),TrDF(0), TrDS(0),factor(0);


Value1 = Lowest(Low,(5*9));
Value2 = Highest(High,(5*9)) - Value1;
Value3 = Close;

If Value2 > 0 then


TrK = (Value3 - Value1) / Value2 * 100
Else
TrK = 0;

If CurrentBar <= 1 then begin


Factor = 2 / (3 + 1);
TrDF = TrK;
End
Else
TrDF = TrDF[5] + (Factor * (TrK - TrDF[5]));

If CurrentBar <= 1 then TrDS = TrDF


Else
TrDS= ((TrDS[5] * 2) + TrDF) / 3;

value1 =average(average(trDS,3),2);
value2 =average(average(TrDF,3),2);

condition1 = value1>85 and value2>85 and (absvalue(value2-value1) <2);


condition2 = value1<(100-85) and value2<(100-85) and ((value2-value1) > 2);

415
condition3 = value2>(100-85) and ( value2>value1);

if condition1 = true or condition2 = true or condition3 = true then value8 = 10 else


value8 = 0;

condition11 = SlowK(21)>85 and slowD(21)>85 and (absvalue(SlowK(21)-


slowD(21)) <2);
condition12 =slowD(21)<(100-85) and SlowK(21)<(100-85) and ((SlowK(21)-
slowD(21)) > 2);
condition13 = SlowK(21)>(100-85) and ( SlowK(21)>slowD(21));

if condition11 = true or condition12 = true or condition13 = true then value18 = 10


else value18 = 0;

if value18 = 10 and value8 = 0 then xD = 1;


if value18 = 0 and value8 =10 then xD = -1;
if (value18 = 0 and value8 = 0) or (value18 = 10 and value8 = 10) then xD = 0;
end;

XKCD

INPUTS:password(numericsimple);
if xAvg(password) = 011784021852 then begin
xkcd=
xpo(password) - average(xpo(password),8);
end;

KpermissionFn

Inputs:LENGTH(9),X(5),password(5);
Plot1(XPermLong(LENGTH,X,PASSWORD), "PermLong");
Plot2(XPermShort(LENGTH,X,PASSWORD),"PermShort");

KdevStops

Inputs : L1(30), v1(2.2), v2(3.6), L2(10), L3(21), p1(close),


p2(high),p3(low),password(5);

if XDev(L1,0,L2,L3,P1,P2,p3,password) > (p3/2) then begin


Plot1(XDev(L1,0,L2,L3,P1,P2,p3,password),"warning");
Plot2(XDev(L1,1,L2,L3,P1,P2,p3,password),"Dev1");
Plot3(XDev(L1,v1,L2,L3,P1,P2,p3,password),"Dev2");
Plot4(XDev(L1,v2,L2,L3,P1,P2,p3,password),"Dev3");
end;

416
XDEV

Inputs : L1(numericsimple), s1(numericsimple), L2(numericsimple),


L3(numericsimple), p1(numericseries),
p2(numericseries),p3(numericseries),password(numericsimple);
Vars: Avg1(P1),Avg2(P1),oscl(0);
if xAvg(password) = 011784021852 then begin

Avg1 = @Average(P1,L2);
Avg2 = @Average(P1,L3);

If CurrentBar > 1 then begin


If Avg1 > Avg2 then begin
oscl = 1;
end;
If Avg1 < Avg2 then begin
oscl = -1;
end;
End;
If (oscl[1] < 0 and oscl >0) then begin
value80 = p2;
end;
If (oscl[1] > 0 and oscl <0) then begin;
value80 = p3;
end;
If oscl > 0 then begin
if value80 < p2 then value80 = p2;
XDev = Value80 - XRev(s1,l1,p1,p2,p3,password);
end;

If oscl <0 then begin


if value80 > p3 then value80 = p3;
XDev = Value80 +XRev(s1,l1,p1,p2,p3,password);

end;

end;

XREV

inputs: s1(numericsimple), l1(numericsimple), p1(numericseries),


p2(numericseries),p3(numericseries),password(numericsimple);

Vars: TRD(P2-P3),ATR(0), DTR(0),temp(P2-P3);


if xAvg(password) = 011784021852 then begin

417
Value90 = MaxList(p2, p2[1],p1[2]);
Value92 = MinList(p3,p3[1],p1[2]);
TRD = Value90 - Value92;

if date> date[1] and datacompression < 2 and value1[1] > 0 then value1= value1[1]
else
if date > date[2] and datacompression < 2 and value1[2] > 0 then value1= value1[2]
else
value1 = trd;

ATR = Average(TRD,l1);
DTR = stddev(trd, l1);

temp = ATR + (s1* DTR);


if temp > 0 then XRev = temp else XRev = s1* (p2-p3);
end;

Larry Williams Expert

Inputs: CDDrvLet("D:\"), PctRLen(10);


Vars: TrendDirec(0), DnClose(0), UpClose(0),SlamDay(0), SlamDaydn(0),
PCTR(0),
String1(""), KRFake(False), DistDay(False), RingLow(False),
SmlRng(False),
OutDayBear(False), HTwenty(False), HFifty(False), LTwenty(False),
LFifty(False),
ExtremeUp(False), ExtremeDn(False), STTop(False), STBot(False),
InDay(False),
Decl(False), Rally(False), RallyDnC(False), TDChgBull(False),
TDChgBear(False),
PctRUp(False), PctRDn(False), SDHFail(False), SDLFail(False),
SmlRngPrev(False),
KRFakeFail(False), DistDayFail(False), RingLowFail(False),
CDDrive(""), PCTR5(0);

DefineDLLFunc: "LWCOM32.DLL",lpstr,"CreateCommentary", lpfloat, lpfloat,


lpfloat, lpfloat, lpfloat, lpfloat, Bool, Bool, Bool, Bool, Bool, Bool, Bool,
Bool, Bool, Bool,
Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool,
Bool, Bool,
Bool, Bool, lpfloat;

CDDrive=LeftStr(CDDrvLet, 1);
TrendDirec=TDirec;
Value1=Ring;
if Close<Low[1] then SlamDay=1 else SlamDay=0;
if Close>High[1] then SlamDayDn=1 else SlamDayDn=0;

418
PctR=PercentR(PctRLen);
PCTR5=PctR[3];
If Close<Close[5] then DnClose=DnClose+1
Else DnClose=0;
If Close>Close[5] then UpClose=UpClose+1
Else UpClose=0;
KRFake= High>High[1] and Low>Low[1] and Close<Open and Close[1]>Open[1];
KRFakeFail=KRFake[1] and High<High[1];
DistDay=Close > High[1] and Close<Open;
DistDayFail=DistDay[1] and High<High[1];
RingLow=Value1>=1 and Value1<=6 and Low>Low[Value1+1];
RingLowFail=RingLow[1] and RingLow=false and High<High[1];
SmlRng=Average(Range,2)<Average(Range,7);
SmlRngPrev=SmlRng[1];
OutDayBear=High > High[1] and Low < Low[1] and Close<Low[1] and
Close[1]>Open[1];
HTwenty=High=Highest(High,20);
HFifty=High=Highest(High,50);
LTwenty=Low=Lowest(Low,20);
LFifty=Low=Lowest(Low,50);
ExtremeUp=Close>=High-(range*.10) and Close>Close[5] ;
ExtremeDn=Close<=Low+(range*.10) and Close<Close[5] ;
STTop=Close>Highest(High,10)[1] and High-Close < Range*.10;
STBot=Close<Lowest(Low,10)[1] and Close-Low < Range*.10;
InDay=High<High[1] and Low>Low[1];
Decl=Low<=Low[5];
Rally=High>=High[5] and Close>Open;
RallyDnC=High>=High[5] and Close<Open;
TDChgBull=TrendDirec=1 and TrendDirec[1]<>1;
TDChgBear=TrendDirec=-1 and TrendDirec[1]<>-1;
PctRUp=PctR>Pctr[1];
PctRDn=PctR<Pctr[1];
SDHFail=SlamDay[1]=1 and High<High[1];
SDLFail=SlamDayDn[1]=1 and Low>Low[1];

If CheckCommentary and AtCommentaryBar and currentbar > 0 then begin


String1=CreateCommentary(&TrendDirec, &PctR, &SlamDay,
&SlamDayDn, &DnClose,
&UpClose, TDChgBull, PctRUp, SDHFail, TDChgBear, PctRDn,
SDLFail, SmlRng,
SmlRngPrev, OutDayBear, KRFake, KRFakeFail, HTwenty, HFifty,
LTwenty, LFifty,
ExtremeUp, ExtremeDn, StTop, StBot, DistDay, DistDayFail, InDay,
Decl, Rally,
RallyDnC, RingLow, RingLowFail, &Pctr5);
Vars: MVLoop(0), MVRef(0), MVCond(False), MVPos(0);

MVPos=1;
MVRef=MakeNewMovieRef;

419
for MVLoop=1 to (StrLen(String1)/12) begin
MVCond=
AddToMovieChain(MVRef,CDDrive+":\vid1\"+MidStr(String1,MVPos,12));
MVPos=MVPos+12;
End;
MVCond = PlayMovieChain(MVRef);
End;
if TDirec>0 then Plot1(TDirec,"TrendUp");
if TDirec<0 then Plot2(ABsValue(TDirec),"TrendDn");

DeMark Expert

{*******************************************************************
Description : This Indicator plots the Thomas DeMark Expert
Provided By : Omega Research, Inc. (c) Copyright 1999
********************************************************************}

Inputs: CDDrvLet("D"), OverBght(+45), OverSold(-45), AvgLen(10), MAtype(1),


REI_Bars(5);
DefineDLLFunc: "TDCOM32.DLL", lpstr, "createCommentary", lpstr, lpfloat,
lpfloat, lpfloat, lpfloat, lpfloat, lpfloat, lpfloat, lpfloat, bool, bool, bool, bool;

Vars: TDSEQ(0), REIval(0), REIvot(0), Counter(0), hiChannel(0), loChannel(0),


chavot(0),
Str1(""), Str2(""), Str3(""), ReiValCond1(False), ReiValCond2(False),
ChaVotCond1(False), ChaVotCond2(False), REIBars(0),
CDDrive("");
Vars: MVLoop(0), MVRef(0), MVCond(False), MVPos(0);

CDDrive=LeftStr(CDDrvLet, 1);
TDSEQ = TDC.SEQ.SetUp (4, 9, False, Close, 4, False) ;
REIval = TDC.REI (REI_Bars, 2, 7, 5, True) ;
hiChannel = TDC.Channel2.hi (High, 3, 1.0050, AvgLen) ;
loChannel = TDC.Channel2.lo (Low, 3, .9950, AvgLen) ;
REIBars=REI_Bars;
If REIval > OverBght and REIval[1] <= OverBght then Counter = 0 ;
If REIval > OverBght then Counter = Counter + 1 ;

If REIval < OverSold and REIval[1] >= OverSold then Counter = 0 ;


If REIval < OverSold then Counter = Counter + 1 ;

REIvot = 0 ;
If REIval > REIval[1] and REIval < OverSold then REIvot = -3 ;
If REIval <= REIval[1] and REIval < OverSold then REIvot = -2 ;
If REIval < REIval[1] and REIval <= OverBght and REIval >= OverSold then
REIvot = -1 ;
If REIval = REIval[1] and REIval <= OverBght and REIval >= OverSold then
REIvot = 0 ;

420
If REIval > REIval[1] and REIval <= OverBght and REIval >= OverSold then
REIvot = +1 ;
If REIval >= REIval[1] and REIval > OverBght then REIvot = +2 ;
If REIval < REIval[1] and REIval > OverBght then REIvot = +3 ;

chavot = 0 ;
If Close > hiChannel then chavot = -2 ;
If High > hiChannel and Close <= hiChannel then chavot = -1 ;
If Low < loChannel and Close >= loChannel then chavot = +1 ;
If Close < loChannel then chavot = +2 ;
ReiValCond1= REIval >= OverSold and REIval[1] < OverSold;
ReiValCond2= REIval <= OverBght and REIval[1] > OverBght;

ChaVotCond1= chavot[1] = +2 and chavot < +2;


ChaVotCond2= chavot[1] = -2 and chavot > -2;

Plot1 (REIval, "TDC.REI ") ;


Plot3 (OverBght, "OverBght") ;
Plot4 (OverSold, "OverSold") ;

If CheckCommentary and AtCommentaryBar then begin


Str1 = "" ;
Str2 = " unchanged" ;
If REIval > REIval[1] then STR2 = " and rising" ;
If REIval < REIval[1] then STR2 = " and falling" ;
Str1 = Str1 + "TD REI = " + NumToStr (REIval, 2) + Str2 +
". TD Channel II high = " + NumToStr (hiChannel, 4) +
", low = " + NumToStr (loChannel, 4) + "." +Newline+NewLine ;
Str2 = "" ;

str3="";
str3=createcommentary(Str1, &TDSEQ, &REIval, &REIvot, &REIBars,
&Counter, &hiChannel, &loChannel, &chavot,
Reivalcond1, reivalcond2, chavotcond1, chavotcond2);
Commentary(NewLine+NewLine+"For More Information on the 'DeMark
Indicators' contact: "+NewLine+"Duane Davis"+Newline+"P.O. Box
736"+NewLine+"Fairview, NC 28730"+NewLine+"(828) 628-4222
Voice"+NewLine+"(828) 628-3100 Fax");
MVPos=1;
MVRef=MakeNewMovieRef;
for MVLoop=1 to (StrLen(Str3)/12) begin
MVCond=
AddToMovieChain(MVRef,CDDrive+":\vid2\"+MidStr(Str3,MVPos,12));
MVPos=MVPos+12;
End;
MVCond = PlayMovieChain(MVRef);
End;

421
does anyone know the origin and/or background of this indicator?
seems to work but indicator looks strange. see the following:
rwi_up indicator:
Inputs: Len(NumericSimple); {Lookback period}
Vars: k(0), x(0), counter(0), AverageRange(0);
k = 0;
x = 0;
If CurrentBar <> 0 then Begin
k = LowestBar(Low,Len);
For counter = 0 to k - 1 Begin
x = TrueRange2(H,L,C)[counter] + x;
End;
If k <> 0 then
AverageRange = x / k;
If AverageRange * SquareRoot(k) <> 0 then
RWI_Up = (High[0] - Lowest(Low,Len)) / (AverageRange *
SquareRoot(k));
End;
signal:
Inputs: Len(25);

Value1 = RWI_Up(Len);
Value2 = RWI_Down(Len);
If CurrentBar > 1 then begin
If Value1 >= 1 and Value2 < 1 then Buy on close;
If Value1 < 1 and Value2 >= 1 then ExitLong;
end;
If CurrentBar > 1 then begin
If Value1 < 1 and Value2 >= 1 then Sell on close;
If Value1 >= 1 and Value2 < 1 then ExitShort;
End;

March 2002
Formula for the system dicussed in "Putting stops to the test," by Thomas Stridsman
(p. 82):
If High[1] < High[3] and Close[1] < Open[1] and Open < High[1] and High > High[1] Then
Plot1(High * 1.01, “”);
If Low[1] > Low[3] and Close[1] > Open[1] and Open > Low[1] and Low < Low[1] Then
Plot2(Low * 0.99, “”);
Inputs: TestRuns(9), ExitLevels(0);
Variables: EntryTrigger(0), LongStopLoss(0), ShortStopLoss(0), ExitTrigger(0);
EntryTrigger = IntPortion(Random(2));

422
ExitTrigger = (ExitLevels / 5 + 0.2) / 100;
If EntryTrigger = 1 and MarketPosition = 0 Then Begin
If High < High[2] and Close < Open and Open Next Bar < High Then Begin
Buy Next Bar at High Stop;
LongStopLoss = 1 - ExitTrigger;
End;
If Low > Low[2] and Close > Open and Open Next Bar > Low Then Begin
Sell Next Bar at Low Stop;
ShortStopLoss = 1 + ExitTrigger;
End;
End;
If MarketPosition = 1 Then
ExitLong Next Bar at EntryPrice * LongStopLoss Stop;
If MarketPosition = -1 Then
ExitShort Next Bar at EntryPrice * ShortStopLoss Stop;
If BarsSinceEntry = 4 Then Begin
ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;
Variables: NoTrades(0), MarPos(0), TrProfit(0), SumTrProfit(0), AvgTrade(0), TestString(""),
FileString("");
NoTrades = TotalTrades;
MarPos = MarketPosition;
If NoTrades > NoTrades[1] Then Begin
If MarPos[1] = 1 Then
TrProfit = (ExitPrice(1) - EntryPrice(1)) * 100 / EntryPrice(1);
If MarPos[1] = -1 Then
TrProfit = (EntryPrice(1) - ExitPrice(1)) * 100 / EntryPrice(1);
SumTrProfit = SumTrProfit + TfProfit;
End;
If LastCalcDate = Date + 1 Then Begin
AvgTrade = SumTrProfit / NoTrades;
TestString = LeftStr (GetSymbolName, 5) + "," + NumToStr(TestRuns, 0) + "," +
NumToStr(ExitTrigger*100, 2) + "," + NumToStr(AvgTrade, 2) + NewLine;
FileString = "D:\Temp\StopTest-" + RightStr(NumToStr(CurrentDate, 0), 4) + ".csv";
FileAppend(FileString, TestString);
End;

ZIG ZAG TREND INDICATOR

Ok, this is going to be a lengthy message, but I guess it is going to be an


interesting one, so, please read carefully. It is better not to include the
whole message in your replies. Before you hit the send button, please delete
this message from your answer, or we will all end up with very long
messages!

I had promised a version of ZigZag validity suitable for back tests.

The bad news:


Yesterday I saw that, though such an indicator is possible, its development
is a very tricky job. This is because the cases of missed signals (invisible
false zigzags of the past) do not fall into one single category but rather

423
into many different ones (for example cases of missed zigzags during
confirmed trends, cases of fluctuations of prices during doubtful trends
etc.). Now, I think that dealing with all these cases is almost as hard or
even harder than developing a new zigzag indicator from scratch.

The good news:


I think there is a much simpler solution to the problem. Instead of trying
to discover and validate each invisible zigzag, one can deal only with the
confirmed trends. After all, this is what we all want and it is much easier,
too!
Following this idea, I wrote a new binary indicator, which returns 1 for
confirmed up trends and -1 for confirmed downtrends and which is also based
on the Zigzag indicator. The idea is that the user of Zigzag does not wish
to deal with doubtful periods at all. He does not want to be mislead by
false Zig signals, but neither should he get into the trap of detecting past
invisible formations, just to reject them!

My new indicator takes advantage of Zig's ability to mark major troughs and
peaks but at the same time it avoids any premature - and thus dangerous -
evaluations about the evolving trend. In fact, it is like having an
always-valid binary Zigzag!
If what I suggest here is correct - and I do say IF - then we have a kind of
zig which is not only useful for visual inspections but can also be used in
system tests and can be even optimized like any other indicator used in
systems. I have to be precautionary because until now, almost every attempt
for a completely satisfactory confrontation of problems related to the
Zigzag indicator, at least those I am aware of, have failed. Of course this
includes my own! (Well, ZigZag validity works fine but only as far as the
LAST dynamic leg is concerned). This one seems to work equally well not only
with current prices but also with historical ones. So, all we can do for now
is wish it a better luck.

The new indicator will be called "SR ZigZag Trend".


I have tested its behavior in more than 50 cases, which include disappearing
and re-appearing of zigzags in down and up trends, in weak and strong,
gradual and abrupt moves. In all these cases it worked correctly, but it is
very early for enthusiasm because dealing with Zigzag seems like alchemy.
You never know if what you see is true. I will only be sure when my
indicator passes all the necessary tests. And there have to be hundreds of
them to convince me!
Therefore, I suggest you should consider yourselves kind of "beta testers".
Before starting to use my indicator in systems, please take the time to test
it yourselves. For testing both the ZigZag and my indicator I would suggest
the following method:

1. Use the Zigzag indicator and the SR ZigZag Trend with the same percent of
close (say 10%).
2. Add a second more sensitive Zigzag indicator (say 3 %)
3. During a long trend indicated by the 10% Zig (a long line) find a few

424
minor zigzags of the 3% Zig and mark them with vertical lines.

4. Keep a note of the dates when these marks appear and of the readings of
both the 10% ZigZag and the SR ZigZag Trend on those dates. You are making a
table with 3 columns: Date, 10%Zig (up or down), SR ZigZag Trend (1 or -1).
5. Close the chart and re-open it using the first date you have noted as the
LAST date of the chart.
6. Observe the behavior of the 10% Zigzag: In some cases it should be
heading towards the opposite direction of what you had previously noted. On
the contrary, the SR ZigZag Trend should NOT reconsider its value. If it is
like I say, then repeat steps #5 and #6 until all the dates you have marked
are examined. If you notice any revisions in the values of SR ZigZag Trend
then you have caught a mistake (bad luck for all of us but especially for
me). Take a detailed note of it, stop testing and contact me.

If everything seems ok with the cases you have examined, this still doesn't
mean that everyone else had the same experience. So, please post your
results and read what the others have to say.

You will notice that the indicator follows Zig's changes of direction with a
delay, which is necessary for the confirmation of the trend. Hopefully, once
a new trend is detected and confirmed, SR ZigZag Trend will not be revised,
until the next (opposite) trend's confirmation. Due to this delay, the
values returned by SR ZigZag Trend do not always coincide with profitable
buy and sell signals, though in many cases they really do! But this is the
old well-known sad story of any trend-following system. What is new here, is
that the fans of ZigZag, MAY have now a kind of Zig, which they can play
with harmlessly. And maybe the results are not so exciting as when playing
ball with Zig, but here one kicks a real ball not a balloon!

A few notes before going to the code. I have no reason to doubt anyone's
good will, intentions and honesty. But I have to repeat what is usually said
about intellectual property. I hope you all understand. So here we go:
Please don't change the indicator's name, its comments or its code, if in
the future you need to post it to someone. My name and e-mail address should
be present in case someone wants to contact me directly. Any changes made to
my formula should be discussed with me before being published (outside this
group). It may not be used for commercial reasons without my written
permission, neither as it is nor as part of other products. Any formulas,
systems, experts, explorations, plug-ins or stand-alone applications, which
use the whole code or important parts of it, or reference it, should mention
my name. I am not responsible for any losses.. ..blah blah, though I will
take your profits if you succeed :)

Needless to say, that I would be glad to hear any of your suggestions,


corrections, or possible improvements.
In any case I would appreciate your feedback.

Good luck

425
Spyros

Formula Name: SR ZigZag Trend

{SR ZigZag Trend}


{by Spyros Raftopoulos}
{E-mail : raftsp@otenet.gr}

{This binary indicator is based on the Metastock's Zig Zag function.


1 = confirmed uptrend, -1 = confirmed downtrend}

perc:=Input("percent",1,100,10);
tr:=ValueWhen(1,Zig(C,perc,%)>Ref(Zig(C,perc,%),-1) AND
Ref(Zig(C,perc,%),-1)<Ref(Zig(C,perc,%),-2),Ref(Zig(C,perc,%),-1));
tr:=If( (C-tr)*100/tr>= perc ,tr,0);
tr:=If( tr=0, ValueWhen(1,tr<>0,tr), tr);
pk:=ValueWhen(1,Zig(C,perc,%)<Ref(Zig(C,perc,%),-1) AND
Ref(Zig(C,perc,%),-1)>Ref(Zig(C,perc,%),-2),Ref(Zig(C,perc,%),-1));
pk:=If((C-pk)*100/pk <=-perc , pk, 0);
pk:=If( pk=0, ValueWhen(1,pk<>0,pk), pk);
res:=If(pk<>Ref(pk,-1), -1,
If(tr<>Ref(tr,-1), 1, 0));
res:=If(res=0,ValueWhen(1,res<>0,res),res);
res

JOE DUFFY TS

From: "morluk2000" <borakizilirmak@sympatico.ca>


To: <torontometastockusers@yahoogroups.com>
Sent: Friday, May 17, 2002 10:06 PM
Subject: [torontometastockusers] Re: Here is my last system

> I forgot to add fml("rel") which is simply c/p. Sorry for the
> inconvenience.
>
> --- In torontometastockusers@y..., "morluk2000"
> <borakizilirmak@s...> wrote:
> > You are going to like it. Give me a credit when you use it. Before
> > running browser for the last indicator defined below you must
> select
> > ( with your mouse) underlying index (which is becoming variable P)
> > in Metastock.
>>
> > TS_C:(If(C>=Ref(C,-11),1,-1)+
> > If(C>=Ref(C,-12),1,-1)+
> > If(C>=Ref(C,-13),1,-1)+

426
> > If(C>=Ref(C,-14),1,-1)+
> > If(C>=Ref(C,-15),1,-1)+
> > If(C>=Ref(C,-16),1,-1)+
> > If(C>=Ref(C,-17),1,-1)+
> > If(C>=Ref(C,-18),1,-1)+
> > If(C>=Ref(C,-19),1,-1)+
> > If(C>=Ref(C,-20),1,-1)+10)/20
>>
> > TS_P:(If(P>=Ref(P,-11),1,-1)+
> > If(P>=Ref(P,-12),1,-1)+
> > If(P>=Ref(P,-13),1,-1)+
> > If(P>=Ref(P,-14),1,-1)+
> > If(P>=Ref(P,-15),1,-1)+
> > If(P>=Ref(P,-16),1,-1)+
> > If(P>=Ref(P,-17),1,-1)+
> > If(P>=Ref(P,-18),1,-1)+
> > If(P>=Ref(P,-19),1,-1)+
> > If(P>=Ref(P,-20),1,-1)+10)/20
>>
> > TS_C/P:(If(Fml("rel")>=Ref(Fml("rel"),-11),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-12),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-13),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-14),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-15),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-16),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-17),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-18),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-19),1,-1)+
> > If(Fml("rel")>=Ref(Fml("rel"),-20),1,-1)+
> > If(ROC(Fml("rel"),5,%)>ROC(Ref(Fml("rel"),-5),5,%),1,-1)+
> > If(V>3*Mov(V,21,S) AND C>Ref(C,-1),1,0)+
> > If(V>3*Mov(V,21,S) AND C<Ref(C,-1),-1,0)+12)/24
>>
> > TS-Systemx:Round(100*((0.9-Fml("TS_P")/2)*Fml("TS_C")+
> > (0.1+Fml("TS_P")/2)*Fml("TS_C/P")))
>>
> > TS-Systems:If(Fml( "TS-Systemx")>=0 AND Fml( "TS-Systemx")
> <=100,Fml
> > ("TS-Systemx"),If(Fml("TS-Systemx")>100,100,0))
>>
> > The last indicator, when it crosses 50 up it is BUY and when it
> > crosses 50 down it is SELL.
>>
> > Bora KIZILIRMAK

427
Expressing Exponential averages in days
Frank Kaeberlein wrote:
>How do I "convert" a 0.2 exponential average into an equivalent period of
>days?

The formula for the exponential average weighting factor is

w = 2 / (length + 1)

Solving for length in days, we get

length = 2 / w - 1

So if w=0.2, then length = 2 / 0.2 - 1 = 9 days.

Trade Station Rank Correlation

Did anyone try to code the more complicated formula for the case where
there are ties?

ysk

On Sat, 2 Mar 2002 10:41:11 -0500


"Alex Dannenberg" <alex@pinemountaincapital.com> wrote:

> ...Also, just look in Numerical Recipes to see that the rank correln is
> equal to "value1" only when there are no ties (i.e. Ties=1). Otherwise, you
> need to compute the correln among the ranks explicitly or use a much more
> complicated expression that requires storing all the informn about ties...
> (see http://lib-www.lanl.gov/numerical/bookcpdf/c14-6.pdf)
>
> Hope this helps.
>
> -Alex
>
> -----Original Message-----
> From: Alex Dannenberg [mailto:alex@pinemountaincapital.com]
> Sent: Saturday, March 02, 2002 10:24 AM
> To: Michael E Songer; Omega-list (E-mail)
> Subject: RE: Rank Correlation Function for Arrays
>

428
>
> ...Just to make the thing a bit more efficient, you can replace
>
>
> If Ties=1 then myRank=HiCount;
> If Ties>1 then begin
> Tot=0;
> For z=1 to Ties-1 begin
> Num=HiCount+1;
> Tot=Tot+Num;
> HiCount=Num;
> End;
> myRank=Tot/(Ties-1);
> End;
>
>
> with
>
> myRank=HiCount+(Ties-1)/2
>
> -Alex
>
>
> -----Original Message-----
> From: Michael E Songer [mailto:songer@speedsite.com]
> Sent: Friday, March 01, 2002 2:16 PM
> To: Omega-list (E-mail)
> Subject: Rank Correlation Function for Arrays
>
>
> List,
> Several people expressed an interest in a rank correlation function to be
> used with arrays. Here is the function: msCorrel_Rank_a. I have also
> included a sample indicator.
> Mike
>
>
> {SAMPLE INDICATOR}
>
{********************************************************************
*****}
> Arrays: IndArray[50](0), DepArray[50](0);
> VARS: x(0);
>
>
> for x=0 to 50 begin
> IndArray[x]=c[x] of data2;
> DepArray[x]=c[x] of data1;
> End;

429
>

> value1=msCorrel_Rank_a(DepArray, IndArray);


>
> plot1(value1,"rankCor");
> plot2(0,"zero");
>
>
{********************************************************************
******}
>
>
>
>
> {FUNCTION}
>
{********************************************************************
*****
>
> Fill [0] element in array being evaluated.
> Limit 100 elements. Change to larger value if you like.
>
> Michael E. Songer
> songer@speedsite.com
>
*********************************************************************
****}
>
>
> INPUTS: DepArray[Dsize](NumericArrayRef),
IndArray[Isize](NumericArrayRef);
> VARS: x(0),y(0),z(0),HiCount(0),Ties(0),myRank(0),Tot(0),Num(0);
> VARS:Sum(0),Diff(0),Diff2(0),N(0);
> ARRAYS: DepRankArray[100](0),IndRankArray[100](0);
>
>
> {Fill DepRankArray}
> For x = 0 to Dsize Begin
> HiCount=1;
> Ties=0;
> For y= 0 to Dsize begin
> If DepArray[x]>DepArray[y] then HiCount=HiCount+1;
> If DepArray[x]=DepArray[y] then Ties=Ties+1;
> End;
> If Ties=1 then myRank=HiCount;
> If Ties>1 then begin
> Tot=0;
> For z=1 to Ties-1 begin
> Num=HiCount+1;
> Tot=Tot+Num;

430
> HiCount=Num;
> End;

> myRank=Tot/(Ties-1);
> End;
> DepRankArray[x]=myRank;
> End;
>
> {Fill IndRankArray}
> For x = 0 to Isize Begin
> HiCount=1;
> Ties=0;
> For y= 0 to Isize begin
> If IndArray[x]>IndArray[y] then HiCount=HiCount+1;
> If IndArray[x]=IndArray[y] then Ties=Ties+1;
> End;
> If Ties=1 then myRank=HiCount;
> If Ties>1 then begin
> Tot=0;
> For z=1 to Ties-1 begin
> Num=HiCount+1;
> Tot=Tot+Num;
> HiCount=Num;
> End;
> myRank=Tot/(Ties-1);
> End;
> IndRankArray[x]=myRank;
> End;
>
> {CALCULATE RANK CORRELATION}
> Sum=0;
> For x=0 to Dsize begin
> Diff=IndRankArray[x]-DepRankArray[x];
> Diff2=square(Diff);
> Sum=Sum+Diff2;
> End;
> N=Dsize+1;
>
> value1= 1 - ( ( 6*Sum ) / ( N*(square(N)-1) ) );
>
> msCorrel_Rank_a=value1;
>
>
{*******************************************************************}
>

Loops & Max Bars Back – Bug

431
Hi all,

Thanks to all who responded to my earlier post with the subject line:
"Brain teasers (are these known TradeStation bugs?"

I thought I'd let folks know what I discovered about one of the three
problems (and hopefully save others from tripping across an obscure
TradeStation bug).

In my earlier post, I said:


>> (TS2000i and TS6): The following error shows up (only
>> occasionally): "Infinite loop detected in this analysis
>> technique. Check all 'FOR' and/or 'WHILE' loops for proper
>> termination conditions."
>> The study in question uses only two simple "for i=1 to 5"
>> loops.

Well, I was wrong about the loops. It turns out my study was
making a call to a function I wrote to implement Dick Arms' Volume
Adjusted Moving Average. That function _does_ contain a WHILE loop
of the form:

Line 1: Index = 0;
Line 2: RemainingIncr = Length;
Line 3: while RemainingIncr > 0 begin
Line 4: VolRatio = Volume[Index] / VolIncr;
Line 5: Factor = MinList(VolRatio, RemainingIncr);
Line 6: Sum = Sum + Factor * Price[Index];
Line 7: RemainingIncr = RemainingIncr - Factor;
Line 8: Index = Index + 1;
Line 9: end;

When I dug into the problem, what I discovered is that the


"auto-detect" feature that is supposed to determine the max bars back
that a function will reference only "mostly works".

By scattering print statements within the code, I was able to see that
the infinite loop occurs when the value of Index is equal to 34. At
that point, on Line 4 the loop is supposed to calculate:

VolRatio = Volume[Index] / VolIncr;

However, because of a bug in the "auto-detect" feature, TradeStation


doesn't realize that Volume[34] would exceed the previous max bars
back value for the study and recalculate the study using a larger max
bars back. Instead, it just returns a bogus value for Volume[Index] on
this and subsequent iterations through the loop. The value returned is
Volume[0] (instead of Volume[34], Volume[35], ...). Since that volume
happens to be zero, the loop condition is never met and the "infinite
loop" error happens. It looks like the "auto-detect max bars back"

432
feature doesn't work if the previous max bars back is exceeded while
within a loop.

Since, the actual max bars back value for the function depends on the
length of the volume adjusted average and the volume values
themselves, I can't just assign a fixed max bars back value to the
study. In order to get the auto-detect facility to work, I ended up
adding the following assignment to a dummy variable right after the
end of the loop:

Line 10: Dummy = Volume[3*Index];

Since this assignment is outside the loop, the auto detect mechanism
works. It's not pretty but I no longer see infinite loop errors when
applying the study to a chart.

If anyone has suggestions for a better workaround, I'd love to hear


them. In any event, I hope this post saves somebody else some
debugging time. This problem appears to be in both TS2000i and TS6.

Cheers,
Rich

Heat Maps

¾ >Has anyone developed the EL code to export the appropriate


> >data to do 3D analysis on the input parameters under test?
>
> The problem is that you have to convert a sequential list of
> optimization results into a 2-D table of optimization results.
> I guess one could write a macro to search through the list and
> populate a table which you then plot using a 3-D surface plot.

I did it a little differently, since originally I tried to do it


without macros. Doing it with a macro might have produced a smaller
spreadsheet, and maybe I'll change it some day, but what I do works
OK.

You can download it from http://www.frii.com/~fritz/trading,


HeatMap.zip.

> >I was led http://www.rinafinancial.com/3DSmartView.asp , to


> >look at the 3DSmartView product.
> Well, Excel's 3-D capabilities really suck, in my opinion. Excel
> will do a 3-D surface plot, but you don't have much control over
> color gradations or scaling. If you have "too much" data you get a

433
> sea of black because Excel insists on drawing a thick outline
> around every square cell on the surface.

My HeatMap spreadsheet addresses those problems.

> If you don't already have access to something like MatLab or


> LabView, then this 3DSmartView software may be the way to go.
> You'd probably spend over $500 of your time implementing the same
> functionality in Excel.

I sure did. :-\ Anybody who wants to send me $500 for this is
welcome to do so!! :-)

Gary

System Quality

{Function _SystemQuality
by Alex Matulich
Copyright (c) 2002 by Unicorn Research Corporation.
All rights reserved.

This function allows you to optimize on an objective measure of


quality of strategy performance. The results can be used to
compare objectively the quality of different strategies, or the
same strategy with different input parameters.

TradeStation does not offer a way to optimize a strategy against


some arbitrary user-defined result. It lets you optimize only
against a selection of canned results such as Net Profit or
win/loss ratio. These, unfortunately, are not objective measures
of system quality. This function builds an Excel file while an
optimization is running. The last column contains the quality
score of the strategy.

In the book _Trade Your Way To Financial Freedom_, Van K. Tharp


describes the use of an objective quality score, defined as

quality = expectancy * opportunities

where
expectancy = (AW*PW + AL*PL) / AL
= expected profit per dollar risked

opportunities = NST * (365 / studydays)


= opportunities to trade in a year

AW = average winning trade (excluding maximum win)


PW = probability of winning (total wins / opportunities)
AL = average losing trade (negative, excluding scratch
losses)
PW = probability of losing (nonscratch losses/opportunities)

434
NST = number of non-scratch trades (a scratch trade loses
commission+slippage or less)
studydays = number of days of history being tested

Examples of equivalent-quality systems would be:


* a market maker earning 1 cent per $1 risked, 50 times/day.
* a daytrader earning 10 cents per $1 risked, 5 times/day.
* a position trader earning $1 per $1 risked, 2-3 times/week.

(In reality the market maker earns something like 5 cents per $1
risked, 100 times a day. A market maker's quality score is
sky-high, higher than anything else, which is why they cannot
be beaten.)

To use this function:

0. If your strategy contains position-sizing rules, disable them.


We're not trying for maximum equity growth in this optimization,
but rather risk-normalized performance on constant-quantity
orders. Position sizing rules destroy the measurement. After
finding the optimum quality this way, re-enabling the position
sizing rules will result in better performance than before,
especially if the sizing is a function of trade risk and equity.

1. Just insert a call to this function at the end of your signal,


passing the strategy input parameters of interest, as well as the
file name to output. The file name should have a .CSV extension
so that Excel will read it readily. The file name should not
contain anything TS would interpret as "jump commands" or you'll
get an error. See the warning in the input declaration below.

2. If you use the same strategy in different markets or different


workspaces, be sure to add a filename input parameter to your
strategy's signal, so you don't have multiple things writing to
the same file!

3. Make sure the output file is deleted. Every time your strategy
is recalculated the output file grows. You want to delete it to
start afresh before running an optimization. Also, setting the
filename parameter to "" (empty string) will disabled the output.

4. Run the optimization. Try to set up your parameters so that


less than 65,535 results are generated (you will have to import
it all into Excel).

5. When the optimization completes, load your file into Excel and
sort by the last column, the one you want optimized, in descending
order. The top result will be the optimum. The columns in the
file are:

p1, p2,...(input parameters),


#wins, GrossProfit, #losses, GrossLoss, #scratches, ScratchLoss,
MaxIDDrawdown, Expectancy, QualityScore

Be aware that the optimum strategy found this way is objectively


and mathematically optimum. It may not be PSYCHOLOGICALLY
optimum, however. For example, the optimum combination of
parameters giving the highest score may have 25% winning trades.
You may be bothered by losing 3 out of 4 times. If such is the
case for you, you can compromise by multiplying the score by your
personal subjective measure of "psychological quality." In this

435
case we would multply the score by the percent of winning trades,
and re-sort the spreadsheet. If you're sensitive to drawdown, you
might try multiplying the score by AL/DD. You might find that the
resulting highest score represents a good compromise between your
psychology and the objective best strategy.

See _Trade Your Way To Financial Freedom_ by Van K. Tharp for


a detailed explanation of trading system expectancy. This function
calculates a more conservative version that Tharp's: It ignores
the maximum profit as an outlier, and it uses the average loss
rather than the minimum loss as the standard of risk.
}

inputs:
filename(string), {full pathname for .csv file}
dontsave(NumericSimple),{don't save scores less than this}

{WARNING: avoid \hb, \he, \pb, \pe, \wb, or \we, in the file
name. TS interprets these as "jump commands." For example,
the filenames "c:\hello.csv" or "c:\data\performance.csv"
will
result in an error message because they contain \he and \pe,
respectively.}

p1(NumericSimple), {strategy input parameters}


p2(NumericSimple),
p3(NumericSimple),
p4(NumericSimple), p5(NumericSimple), p6(NumericSimple),
p7(NumericSimple), p8(NumericSimple), p9(NumericSimple),
p10(NumericSimple), p11(NumericSimple), p12(NumericSimple),
p13(NumericSimple), p14(NumericSimple), p15(NumericSimple),
p16(NumericSimple), p17(NumericSimple), p18(NumericSimple);

vars: nclosed(0), wins(0), losses(0), scratches(0), scratchloss(0),


scratchtrade(0), studystart(0), studydays(0),
p(0), j(0), k(0), AW(0), PW(0), AL(0), PL(0), expectancy(0),
expectancyscore(0);

{Initializations to occur on first bar}

if currentbar <= 1 then begin


nclosed = 0;
wins = 0;
losses = 0;
scratches = 0;
scratchloss = 0;
studystart = DateToJulian(Date);

{The maximum loss amount for a "scratch" trade will be a


round-turn commission and slippage.
Set Commission and Slippage in Format -> Strategy -> Costs.}

scratchtrade = -1.5 * (commission + slippage);


end;

{Do the following whenever a position is closed}

if totaltrades > nclosed then begin


k = totaltrades - nclosed;
for j = 1 to k begin {loop over multiple simultaneous closed
trades}

436
p = PositionProfit(j);
if p <= 0 then begin
if p >= scratchtrade then begin
scratches = scratches + 1;
scratchloss = scratchloss + p;
end else
losses = losses + 1;
end else
wins = wins + 1;
end;
nclosed = totaltrades;
end;

{Finally, at the last bar, output the result to be optimized}

if LastBarOnChart and losses>0 and StrLen(filename)>0 then begin


studydays = DateToJulian(Date) - studystart;
if studydays < 1 then studydays = 1;

{Calculate results to be optimized, and output them}


if wins > 1 and losses > 0 then begin
j = wins - 1 + losses; {total trades excl scratches &
max win}
AW = (GrossProfit-LargestWinTrade)/(wins-1); {avg
win}
PW = (wins-1) / j; {%
wins}
AL = (GrossLoss - scratchloss) / losses; {avg
loss}
PL = losses / j; {%
losses}
end else begin {handle division by zero cases}
j = wins + losses;
if wins <= 1 then AW = 0 else AW = GrossProfit;
if j = 0 then begin
PW = 0; PL = 0;
end else begin
PW = wins / j; PL = losses / j;
end;
if losses = 0 then AL = 0
else AL = (GrossLoss - scratchloss) / losses;
end;

if AL = 0 then expectancy = AW*PW


else expectancy = (AW*PW + AL*PL) / (-AL);
expectancyscore = expectancy * j * 365/studydays;

if expectancyscore >= dontsave then begin

{Append the strategy input parameters to a file}


FileAppend(filename,

numtostr(p1,3)+","+numtostr(p2,3)+","+numtostr(p3,3)+","+

numtostr(p4,3)+","+numtostr(p5,3)+","+numtostr(p6,3)+","+

numtostr(p7,3)+","+numtostr(p8,3)+","+numtostr(p9,3)+","+

numtostr(p10,3)+","+numtostr(p11,3)+","+numtostr(p12,3)+","+

numtostr(p13,3)+","+numtostr(p14,3)+","+numtostr(p15,3)+","+

437
numtostr(p16,3)+","+numtostr(p17,3)+","+numtostr(p18,3)+",");

{Append win and loss data as desired}


FileAppend(filename,
numtostr(wins,0)+","+numtostr(GrossProfit,2)+","+
numtostr(losses,0)+","+numtostr(GrossLoss,2)+","+

numtostr(scratches,0)+","+numtostr(scratchloss,2)+","+

numtostr(LargestWinTrade,2)+","+numtostr(LargestLosTrade,2)+"
,"+
numtostr(MaxIDDrawDown,2)+",");

{Append expectancy and expectancy score}


FileAppend(filename,
numtostr(expectancy, 3) + "," +
numtostr(expectancyscore, 3));

FileAppend(filename, NewLine); {lastly append a


carriage return}
end;
end;
_SystemQuality = 1; {dummy return value}

System History
{_SystemHistory
by Alex Matulich
Copyright (c) 2002 by Unicorn Research Corporation.
All rights reserved.

Don't call this function during an optimization!


It will produce a huge file.

This function Output the profit, initial risk, initial volatility,


and maximum adverse excursion (MAE) for every closed position.
Units output are in dollars, not market units, although inputs
*are* in market units.
}

inputs:
filename(string), {full pathname for .csv file}

{WARNING: avoid \hb, \he, \pb, \pe, \wb, or \we, in the file
name. TS interprets these as "jump commands." For example,
the filenames "c:\hello.csv" or "c:\data\performance.csv"
will
result in an error message because they contain \he and \pe,
respectively.}

tstop(NumericSeries), {current stop}


mktvolatility(NumericSeries), {current volatility}
execute_next_bar(TrueFalse); {true=entry from previous bar's
order}

vars: risk(0), mktvolat(0), nclosed(0), MAE(0);

if StrLen(filename) > 0 then begin

438
{Initializations to occur on first bar}

if currentbar <= 1 then nclosed = 0;

{Do the following while a position is open}

if marketposition<>0 then begin


if BarsSinceEntry=0 then begin {first bar of the open
position}
if execute_next_bar then begin
risk = AbsValue(EntryPrice - tstop[1]) *
BigPointValue;
mktvolat = mktvolatility[1] * BigPointValue;
if marketposition>0 then
MAE = MinList(BigPointValue*(Low -
EntryPrice), 0)
else
MAE =
MinList(BigPointValue*(EntryPrice - High), 0);
end else begin
MAE = MinList(positionprofit, 0);
risk = AbsValue(EntryPrice - tstop) *
BigPointValue;
mktvolat = mktvolatility * BigPointValue;
end;
end else begin {we're past the first bar in the open
position}
risk = risk[1]; {save initial
risk}
mktvolat = mktvolat[1]; {save initial
volatility}
if marketposition>0 then {calculate new MAE}
MAE = MinList(MAE[1], BigPointValue*(Low -
EntryPrice), 0)
else
MAE = MinList(MAE[1],
BigPointValue*(EntryPrice - High), 0);
end;
end;
nclosed = nclosed[1];

{Do the following whenever a position is closed}

if totaltrades > nclosed then begin


FileAppend(filename,
numtostr(PositionProfit(1),2)+","+
{output profit}
numtostr(risk[1],2)+","+ {output
initial risk}
numtostr(mktvolat[1],2)+","+ {output
initial volatilty}

numtostr(MinList(MAE[1],positionprofit(1)),2) {output MAE}


+NewLine);
nclosed = totaltrades;
end;

end;
_SystemHistory = 1; {dummy return value}

439
Linear Regression Slope Super Fast Calc

{_LinRegSlopeSFC - Linear Regression Slope Super Fast Calc


by Alex Matulich
Copyright (c) 2002 by Unicorn Research Corporation. All rights
reserved.

This is a super-efficient version of Mark Simms' Linear Regression


Slope Fast Calc algorithm. Here, a loop gets executed only once
during initialization, rather than at every bar.}

Inputs: Price(NumericSeries), Length(NumericSimple);

Vars: xLen(0), ix(0), m1(0), m2(0), sumP(0), sumIP(0);

if xLen <> Length or CurrentBar <= Length then begin


xLen = Length;
m1 = 6 / (Length * (Length + 1));
m2 = 2 / (Length - 1);
sumP = 0; sumIP = 0;
for ix = 0 to length-1 begin
sumP = sumP + Price[ix];
sumIP = sumIP + ix * Price[ix];
end;
end else begin
sumIP = sumIP + sumP - Length * Price[Length];
sumP = sumP + Price - Price[Length];
end;
_LinRegSlopeSFC = m1 * (sumP - m2 * sumIP);

exponential linear regression slope

{_xLinRegSlope - exponential linear regression slope


by Alex Matulich, Unicorn Research Corporation}

Inputs: Price(NumericSeries), Len(NumericSimple);

Variables: x(0), sumX(0), sumY(0), sumXY(0), sumX2(0), w(0);


w = 2 / (Len + 1); {exponential weighting factor}

{calculate sums over all X values (bars) and over all X^2 values}

sumX = 0.5 * Len * (2*CurrentBar - Len + 1);


sumX2 = Len*(CurrentBar*(CurrentBar+1-Len)+(1-2*Len)*(1-Len)/6);

{calculate sum of Y values and sum of X*Y values}

if CurrentBar <= 1 then begin {initialize to eliminate settling


time}
sumY = Price * Len;
for x = 2-Len to 1 begin sumXY = sumXY + x*Price; end;
end else begin
sumY = w*Price*Len + (1-w)*sumY[1];
sumXY = w*CurrentBar*Price*Len + (1-w)*sumXY[1];
end;

440
_xLinRegSlope = (Len*sumXY - sumX*sumY) / (Len*sumX2 - sumX*sumX);

xStdDev Exponential moving standard deviation


{_xStdDev Exponential moving standard deviation
by Alex Matulich alex@unicorn.us.com 7/2002}

Inputs:
price(NumericSeries), {price}
length(NumericSimple); {"lookback" length}
Vars: w(0);
w = 2 / (length + 1);
_xStdDev = SquareRoot(w*price*price + (1-w)*_xStdDev[1]*_xStdDev[1]);

xAverage - Exponential Moving Average that allows for


variable lookback.

{_xAverage - Exponential Moving Average that allows for


variable lookback.
by Alex Matulich, Unicorn Research Corporation}

Inputs: Price(NumericSimple), Length(NumericSimple);

Variables: w(0), xlen(0);


if xlen <> xlen[1] or CurrentBar <= 1 then begin
w = 2 / (Length + 1);
xlen = Length;
end;
_xAverage = w * Price + (1 - w) * _xAverage[1];

441
FIBONACCI FORMULAS

Hi Shashi,

Many thanks for your help. I've come up with the following - not exactly to
your suggestion in every detail, but hopefully in the spirit of it. I
haven't tested it much yet - all feedback and improvements welcome (coding
is not my strong point!). Anyone testing it please vary V1 especially to
your preference - I have it set very low for a 5-minute chart.

V1:=0.5; {ZigZag reversal amount}


V2:=0.50; {Minimum Retracement %}
V3:=0.618; {Maximum Retracement %}

C1:=Peak(1,C,V1) - Trough(1,C,V1); {Swing amount, i.e. price difference


between previous peak and previous trough}

C2:=Peak(1,C,V1) - C; {price difference between previous peak and current


close}

PeakBars(1,C,V1) <
TroughBars(1,C,V1) {the previous peak is later than the previous trough}

AND

C < Peak(1,C,V1) {price dropped below last Peak}

AND

C= LowestSince(1, C=Peak(1,C,V1), C)

AND

C2 C1*V2 {retracement minimum}

AND

C2 < C1*V3 {retracement < maximum}

Thanks again,
Nick

----- Original Message -----


From: "Shashi Aggarwal" <shashiag@swbell.net
To: "Metastock Digest (E-mail)" <metastock@listserv.equis.com
Sent: Sunday, February 03, 2002 10:26 AM
Subject: Re: Fibonacci formula

442
Nick, Maurice, Kush and others,

At one time I had created a pullback/ Fib. retracement formula but can't
seem to find it now. I then gave up using it, not because it didn't work
(it
did!), but I could never tell in real time whether the retracement would
be
38%, 50%, or 62% (the commonest ratios)! Thus, for example, I would buy on
a
38% retracement just to see it fall to 62% retracement. Or I would buy at
62% retracement just to see it fall even further and the trend get
reversed.
I guess that's a limitation we have to live with; of course, once the
trend
resumes, it is very easy with 20/20 hindsight to see how much the
retracement was.

Enough said. The logic was as follows:


1) Define trend. e.g. for an uptrend, you would specify the most recent
swing high/low (#1) be higher than the prior swing high/low (#2). You NEED
to use the Peak & Trough functions for this, which depend on the zigzag
indicator. As for the % amount you would choose, that depends on your
trading time frame - larger % for longer time frame and vice versa. (Note:
zigzag is a tricky function; read the online help. In particular, note
this
section from online help: "Be forewarned, that the last leg (i.e.,
segment)
of the Zig Zag is dynamic, meaning that it can change. Therefore, be
careful when designing system tests, experts, etc. based on the Zig Zag
indicator". But don't let this scare you. I got used to it over time, and
so
can you.)
2) Define a recent high implying that the trend is continuing e.g.
HHV(C,20)
most recent swing high (e.g. HHV(C,20) Peak(1,C,10)).
3) Define a pullback e.g. C < HHV(C,20)
4) Define most recent swing e.g. Swing:= HHV(C,20) - Trough(1,C,10) (using
10% swing as an example);
4) Define extent of pullback e.g. for a pullback between 50% & 68% of
recent
swing, it would be something like: C < (Trough(1,C,10) + 0.51*Swing) AND C

(Trough(1,C,10) + 0.31*Swing).
Use filters as needed.

There you have it. Metastock programming is not very easy, but its not
rocket science either. Once you start doing it yourself, AND UNDERSTAND

443
THE

LOGIC BEHIND YOUR ARGUMENTS, you will catch on pretty fast. Try it - I
have
done most of the work for you above. Just make sure you use the parameters
appropriate for your trading.

Shashi
----------------------------------------------------------
----- Original Message -----=20
From: Maurice Cruz=20
To: metastock@metastock.com=20
Sent: Friday, February 01, 2002 6:46 AM
Subject: Fibonacci Formulas

Group,

I would also be interested in this, or any other


fibonacci-related indicators.

Maurice

----- Original Message -----=20


From: Nick Channon=20
To: metastock@metastock.com=20
Sent: Thursday, January 31, 2002 8:53 PM
Subject: Fibonacci Formulas

Hi Group,

I wonder if anyone has a formula to detect a Fibonacci Retracement? =


If so, kindly post. If not, any suggestions on how best to construct =
one? Would it be feasible to base it on zigzag?

Many thanks,
Nick

JOE DINAPOLI - DINAPOLI TREND FORMULA

From: Krzysztof.Kowczur@brebank.com.pl
Subject: "Joe DiNapoli - DiNapoli Trend formula
Date: 30/01/2002 11:35:09
To: metastock@metastock.com

444
Hi Guys
Does anyone have this system formula???

Dinapoli Trends

{UP}C=Ref(Mov(C,3,S),-3) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))=(PREV+(0.199*((Mov(
CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))-PREV))) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))=Ref((Mov( CLOSE, 8.3896,
E) - Mov( CLOSE, 17.5185, E)),-1)
{DOWN}{DOWN}C<=Ref(Mov(C,3,S),-3) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))<=(PREV+(0.199*((Mov(
CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))-PREV))) AND
(Mov( CLOSE, 8.3896, E) - Mov( CLOSE, 17.5185, E))<=Ref((Mov( CLOSE,
8.3896, E) - Mov( CLOSE, 17.5185, E)),-1){jimt}

This message was sent through MyMail http://www.mymail.com.au

Thanks Peter,
I use this formula much differently than Chande suggests. I've had a lot of
success with a 13 period FO. I plot the formula and establish equidistant
levels (from zero) that trigger buy and sell signals. Simple, but effective. This
approach is graphically displayed in the attachment. I like the FO because it
can be somewhat "adaptive" (and it can pull twenty bucks out of crude).
Thanks again, Equis doesn't "trust" us with the formula. If you "click" on the
little "arrow&?", on the task bar, in MetaStock and drop it on the Forecast
Oscillator you get the following blurb:
"The oscillator is above zero when the forecast price is greater than the actual
price. Conversely, it's less than zero if its below."
Of course, this is totally false (the opposite is true). Which of edition of
MetaStock do you believe they might correct their mistake?
Take Care,
Steve
----- Original Message -----
From: Peter Gialames To: metastock@metastock.com Cc:
kernish@turbonet.com Sent: Thursday, January 10, 2002 9:45 AM Subject:
RE: Forecast Oscillator

Not sure if this is what you are looking for but ...

Peter Gialames

Here is the text from S&C V. 10:5 (220-224): Forecasting Tomorrow's


Trading Day by Tushar S. Chande, Ph.D.

445
Using linear regression as a crystal ball for forecasting the market? After all,
if you were to be able to determine tomorrow's high, low and close for trend
changes and placement of stop points, it would simplify your life
immeasurably. Can it work? Tushar Chande explains how it can be done.
Wouldn't you trade better It you could "see" the future? A simple linear
regression can provide an objective forecast for the next day's high, low and
close. These ingredients are essential for a trading game plan, which can help
you trade more mechanically and less emotionally. Best of all, a regression
forecast oscillator, %F, gives early warning of impending trend changes. The
linear regression method is well known for finding a "best-fit" straight line for
a given set of data. The output of the regression are the slope (m) and constant
(c) of the equation
(1)Y = mX + c
Here, m and c are derived from a known set of values of the independent
variable X and dependent variable Y. The relative strength of the linear
relationship between X and Y is measured by the coefficient of determination
r 2 , which is the ratio of the variation explained by the regression line to the
total variation in Y. Here is a table to help interpret the values of r 2 , which
range from 0 to 1:
The coining of the term "regression" can be attributed to Sir Francis Galton,
who observed in the late 1800s that tall fathers appeared to have as a rule short
sons, while short fathers appeared to have as a rule tall sons. Galton suggested
that the heights of the sons "regressed" or reverted to the average. Technician
Arthur Merrill also had a good explanation in a recent issue of STOCKS &
COMMODITIES, and Patrick Lafferty recently wrote on an application of
multiple regression to gold trading. Virtually all introductory books on
statistics have a detailed discussion of the linear regression method.
Successful professional traders emphasize the importance of having a trading
plan. A trading game plan, much like that of a football team, clearly defines
specific actions under different conditions. The linear regression method is
very useful in developing a forecast for the next trading day's high, low and
close based on the last five trading sessions. The method is general and broad-
based enough so that it can be used with stocks, indices or commodities. The
forecast is the basis of my trading plan: I can define what I should do if the
market rises above the forecast high, falls below the forecast low or stays
within the forecast range. This way, I can avoid being emotional and trade as
mechanically as possible by having a plan to rely on.
FORECASTING WITH LINEAR REGRESSION
I like to use at least 10 days of data and develop a forecast for the high, low
and close. The five-day regression is a good choice for short-term trading. You
can use any length of regression you like. Here are the calculations with the
daily close in a spreadsheet format:
1 Perform a linear regression with the first five days of data to obtain the slope
m and constant c such that

446
X Value Daily Close
1 Day 1
2 Day 2
....
5 Day 5
2 Forecast the next day's close with the slope m and constant c from step 1:
(2) Forecast close (Day 6) = 6m + c
3 Record m, c and r 2 on the same line as Day 5. Record the forecast from step
2 one day ahead, with
Day 6. Note when we are using five days' data, the first forecast is for Day 6.
4 Step the calculation ahead one day such that
5 Record m, c and r 2 as in step 3.
6 Calculate the regression forecast oscillator, %F, as
(3)
%F = ((Y-Yforecast)/Y)*100
where Y is the close for Day 6 and Y(Forecast) is the forecast for Day 6 from
step 2 (from Day 5).
7 Record the oscillator on the same line as Day 6.
8 Step the calculations ahead one day at a time until the most recent day.
Technically, we can use the linear regression to develop a point forecast
(single value) for the next day (as in step 2) or a range (interval) of values with
a certain confidence level. The interval widens, greater the variation in the
data and greater the desired confidence level.
I use the forecast oscillator, %F, to determine if my forecast is above or below
the actual market data. Since
%F = ((Y-Yforecast)/Y)*100
where Y can be any market variable for stocks, indices or commodities, %F
measures the percent deviation of the actual value from its forecast. In a
trading market, %F changes its sign before a significant trend change. In
trending markets, %F tends to change sign early in the trend. I interpret %F in
the context of the r 2 Of the regression. A low value of r 2 plus a change in
sign of %F is a good signal of a change in trend. Market extremes and
periodicity can also be observed on the %F charts.
DEVELOPING A TRADING PLAN

447
You can use the forecasts to develop a specific trading plan to suit your
trading style. I use the forecasts in several ways.
Forecasts as stops. I use the high and the low as action points. If the market
exceeds the forecast high, it wants to go up. To trade with the trend, I put a
buy stop a few ticks above the high. If the market falls below the forecast low,
it wants to go down. Hence, I set a sell stop a few ticks below the forecast low.
If you want to trade against the trend, sell short near the forecast high and buy
near the forecast low.
Forecasts as intraday range scale. The forecasts provide a scale for
evaluating the trading day. The market can stay within the expected range or
go outside. On a down day, the intraday high is well below the forecast high
and may be below the forecast close. On an up day, the market stays well
above the forecast low and often above the forecast close.
General rules for trading with forecasts. Here are some general rules:
• Use the forecasts only if r 2 is greater than 0.1. Higher the value of r 2 , the
greater the confidence in the forecasts.
• A trend change is imminent when r 2 falls below 0.1. Prepare to close longs.
• A trend is in place if r 2 is greater than 0.6. As a trend follower, you could
wait for this value to be exceeded before opening positions. This would keep
you out of short-term fluctuations.
• An early warning of a trend change is provided by a zero-crossing of %F, the
forecast oscillator.
Prepare to tighten stops and look for changes in slope and coefficient of
determination for
confirmation.
•A change in trend is confirmed by a change in slope of the regression. Open
positions in direction of trend change. To trade against the trend, look for
peaks in slope and strength of the linear trend.
•The trend will usually change in the direction of %F.
•Always be prepared for a market move against the forecast. Use stops!
A SAMPLE TRADING PLAN
I have developed a forecast for the high, low and close for January 20, 1992,
from the previous five trading days, seen in Figure 1. The market was making
new highs the previous week. Was a downward movement imminent? Let's
look at the data from Friday, January 17, 1992:
The market was trending moderately (0.4<= r 2 <0.6), but the forecast
oscillator %F was negative for high, low and close, warning of a possible
change in trend. The relatively small slope of the regression for the high meant
the market was meeting resistance. The slope of the regression for the close

448
had turned down from the high values during the recent strong uptrend. The
forecast, however, called for a strong close near the highs of the day, but that
seemed doubtful, given the low slopes in a moderating trend. The plan was to
watch for a change in trend. If the market opened weak, a bearish strategy was
called for. For example, I would consider buying the Standard & Poor's 100
Index OEX January 390 puts, or selling short the S&P 500 March futures
contract.
The high daily volume of OEX index options traded makes the S&P
100 index an interesting application of me regression forecast approach.
The market opened at the Friday close and weakness was evident at the open,
as the S&P 500 futures opened lower. It was clear in early trading that the
trend would be down, as the market traded well below the forecast high and
close. Clearly, the forecast range provided a good scale, since it reinforced the
concept that the market was weaker than the trend of the prior five days. A
bearish stance would have been profitable.
THE NATURE OF REGRESSION FORECASTS
The high daily volume of OEX index options traded makes the S&P 100 index
an interesting application of the regression forecast approach. I have examined
a time period from early October 1991 to mid-January 1992. The OEX close
and its forecast are in Figure 2; the r 2 values in Figure 3; %F in Figure
4, and Figure 5 has %F around the mid-November plunge.
Several observations can be made from the OEX analysis. First, the forecast
lags the OEX in an uptrend or in a downtrend. Second, the close and the
forecast cross over several days before a trend change. This crossover can be
seen as a zero crossing in the %F chart. Significant trend changes are preceded
by trendless periods with values of r 2 near zero. Strong trends are
accompanied by high values of r 2 and regression slope. These observations
support the general rules of interpretation noted above. As Figure 5 shows, %F
provided a timely warning of an impending trend change just before the OEX
fell 15.68 points.
I have included data for wheat (cash) from 1989 to indicate the use of this
approach with commodities.
The market showed significant trends during this period with good periodicity,
as shown in Figures 6, 7
and 8. The %F zero crossings were timely indicators of trend change. Features
observed with OEX charts are also seen here; note in particular how %F can
be used to identify extremes in the market from Figures 4 and 8.
Simple linear regression yields forecasts of the high, low and close for stocks,
indices or commodities. These forecasts can be used to develop a trading plan.
You can trade with the trend, against the trend, intraday or interday. The
forecast oscillator, %F, provides early warning of trend changes taken together
with the regression slope and coefficient of determination. This approach

449
works best in trending markets or trading range markets; it is only moderately
useful in volatile markets with choppy price action. These objective forecasts
will let you trade less emotionally and more mechanically. Profits will look up
when you can look ahead.
Tushar Chande holds a doctorate in engineering from the University of
Illinois and a master's degree in business administration from the University
of Pittsburgh.
REFERENCES
Lafferty, Patrick [ 1991 ]. "A regression-based oscillator," Technical Analysis
of STOCKS & COMMODITIES,
Volume 9: September.
Merrill, Arthur [1991]. "Fitting a trendline by least squares," Technical
Analysis of STOCKS & COMMODITIES,
Volume 9: December.
Pfaffenberger, Roger, and James Patterson [1987]. Statistical Methods for
Business and Economics, Irwin.
-----Original Message-----
From: owner-metastock@metastock.com [mailto:owner-
metastock@metastock.com]On Behalf Of Steve Karnish
Sent: Thursday, January 10, 2002 10:34 AM
To: metastock@metastock.com
Subject: Forecast Oscillator

List,

Does anyone have the math formula for Chande's Forecast Oscillator?

Thanks,

Steve

Steve,

I believe this is it.

J.

{Forecast Osc-Chande}

450
{from jseed}
Pds:=Input("Time Periods",1,1000,5);
Fld:=Input("Price Field 1=C 2=O 3=H 4=L",1,4,1);
PFld:=If(Fld=1,C,If(Fld=2,O,If(Fld=3,H,L)));
Sig:=Input("Signal MA Periods",1,200,3);
ForO:=((Pfld-(Ref(LinearReg(Pfld,Pds),-1)+
Ref(LinRegSlope(Pfld,Pds),-1)))*100)/Pfld;
ForO;
Mov(ForO,Sig,E);
{end}

From: "Steve Karnish" <kernish@turbonet.com


Reply-To: metastock@metastock.com
To: <metastock@metastock.com
Subject: Forecast Oscillator
Date: Thu, 10 Jan 2002 08:34:12 -0700

List,

Does anyone have the math formula for Chande's Forecast Oscillator?

Thanks,

Steve

451
Not sure if this is what you are looking for but ...
Peter Gialames
Here is the text from S&C V. 10:5 (220-224): Forecasting Tomorrow's Trading
Day by Tushar S. Chande, Ph.D.
Using linear regression as a crystal ball for forecasting the market? After all, if you
were to be able to
determine tomorrow's high, low and close for trend changes and placement of stop
points, it would
simplify your life immeasurably. Can it work? Tushar Chande explains how it can be
done.
Wouldn't you trade better It you could "see" the future? A simple linear regression can
provide an
objective forecast for the next day's high, low and close. These ingredients are
essential for a trading
game plan, which can help you trade more mechanically and less emotionally. Best of
all, a regression
forecast oscillator, %F, gives early warning of impending trend changes. The linear
regression method is
well known for finding a "best-fit" straight line for a given set of data. The output of
the regression are
the slope (m) and constant (c) of the equation
(1)Y = mX + c
Here, m and c are derived from a known set of values of the independent variable X
and dependent
variable Y. The relative strength of the linear relationship between X and Y is
measured by the
coefficient of determination r 2 , which is the ratio of the variation explained by the
regression line to the
total variation in Y. Here is a table to help interpret the values of r 2 , which range
from 0 to 1:
The coining of the term "regression" can be attributed to Sir Francis Galton, who
observed in the late
1800s that tall fathers appeared to have as a rule short sons, while short fathers
appeared to have as a rule
tall sons. Galton suggested that the heights of the sons "regressed" or reverted to the
average. Technician
Arthur Merrill also had a good explanation in a recent issue of STOCKS &
COMMODITIES, and Patrick
Lafferty recently wrote on an application of multiple regression to gold trading.
Virtually all introductory
books on statistics have a detailed discussion of the linear regression method.
Successful professional traders emphasize the importance of having a trading plan. A
trading game plan,
much like that of a football team, clearly defines specific actions under different
conditions. The linear

452
regression method is very useful in developing a forecast for the next trading day's
high, low and close
based on the last five trading sessions. The method is general and broad-based enough
so that it can be
used with stocks, indices or commodities. The forecast is the basis of my trading plan:
I can define what I
should do if the market rises above the forecast high, falls below the forecast low or
stays within the
forecast range. This way, I can avoid being emotional and trade as mechanically as
possible by having a
plan to rely on.
FORECASTING WITH LINEAR REGRESSION
I like to use at least 10 days of data and develop a forecast for the high, low and close.
The five-day
regression is a good choice for short-term trading. You can use any length of
regression you like. Here
are the calculations with the daily close in a spreadsheet format:
1 Perform a linear regression with the first five days of data to obtain the slope m and
constant c such
that
X Value Daily Close
1 Day 1
2 Day 2
....
5 Day 5
2 Forecast the next day's close with the slope m and constant c from step 1:
(2) Forecast close (Day 6) = 6m + c
3 Record m, c and r 2 on the same line as Day 5. Record the forecast from step 2 one
day ahead, with
Day 6. Note when we are using five days' data, the first forecast is for Day 6.
4 Step the calculation ahead one day such that
5 Record m, c and r 2 as in step 3.
6 Calculate the regression forecast oscillator, %F, as
(3)
%F = ((Y-Yforecast)/Y)*100
where Y is the close for Day 6 and Y(Forecast) is the forecast for Day 6 from step 2
(from Day 5).
7 Record the oscillator on the same line as Day 6.
8 Step the calculations ahead one day at a time until the most recent day.
Technically, we can use the linear regression to develop a point forecast (single value)
for the next day
(as in step 2) or a range (interval) of values with a certain confidence level. The
interval widens, greater
the variation in the data and greater the desired confidence level.
I use the forecast oscillator, %F, to determine if my forecast is above or below the
actual market data.
Since
%F = ((Y-Yforecast)/Y)*100
where Y can be any market variable for stocks, indices or commodities, %F measures
the percent

453
deviation of the actual value from its forecast. In a trading market, %F changes its
sign before a
significant trend change. In trending markets, %F tends to change sign early in the
trend. I interpret %F in
the context of the r 2 Of the regression. A low value of r 2 plus a change in sign of %F
is a good signal of a
change in trend. Market extremes and periodicity can also be observed on the %F
charts.
DEVELOPING A TRADING PLAN
You can use the forecasts to develop a specific trading plan to suit your trading style.
I use the forecasts
in several ways.
Forecasts as stops. I use the high and the low as action points. If the market exceeds
the forecast high, it
wants to go up. To trade with the trend, I put a buy stop a few ticks above the high. If
the market falls
below the forecast low, it wants to go down. Hence, I set a sell stop a few ticks below
the forecast low. If
you want to trade against the trend, sell short near the forecast high and buy near the
forecast low.
Forecasts as intraday range scale. The forecasts provide a scale for evaluating the
trading day. The
market can stay within the expected range or go outside. On a down day, the intraday
high is well below
the forecast high and may be below the forecast close. On an up day, the market stays
well above the
forecast low and often above the forecast close.
General rules for trading with forecasts. Here are some general rules:
• Use the forecasts only if r 2 is greater than 0.1. Higher the value of r 2 , the greater
the confidence in the
forecasts.
• A trend change is imminent when r 2 falls below 0.1. Prepare to close longs.
• A trend is in place if r 2 is greater than 0.6. As a trend follower, you could wait for
this value to be
exceeded before opening positions. This would keep you out of short-term
fluctuations.
• An early warning of a trend change is provided by a zero-crossing of %F, the
forecast oscillator.
Prepare to tighten stops and look for changes in slope and coefficient of determination
for
confirmation.
•A change in trend is confirmed by a change in slope of the regression. Open
positions in direction of
trend change. To trade against the trend, look for peaks in slope and strength of the
linear trend.
•The trend will usually change in the direction of %F.
•Always be prepared for a market move against the forecast. Use stops!
A SAMPLE TRADING PLAN
I have developed a forecast for the high, low and close for January 20, 1992, from the
previous five

454
trading days, seen in Figure 1. The market was making new highs the previous week.
Was a downward
movement imminent? Let's look at the data from Friday, January 17, 1992:
The market was trending moderately (0.4<= r 2 <0.6), but the forecast oscillator %F
was negative for
high, low and close, warning of a possible change in trend. The relatively small slope
of the regression
for the high meant the market was meeting resistance. The slope of the regression for
the close had turned
down from the high values during the recent strong uptrend. The forecast, however,
called for a strong
close near the highs of the day, but that seemed doubtful, given the low slopes in a
moderating trend. The
plan was to watch for a change in trend. If the market opened weak, a bearish strategy
was called for. For
example, I would consider buying the Standard & Poor's 100 Index OEX January 390
puts, or selling
short the S&P 500 March futures contract.
The high daily volume of OEX index options traded makes the S&P
100 index an interesting application of me regression forecast
approach.
The market opened at the Friday close and weakness was evident at the open, as the
S&P 500 futures
opened lower. It was clear in early trading that the trend would be down, as the
market traded well below
the forecast high and close. Clearly, the forecast range provided a good scale, since it
reinforced the
concept that the market was weaker than the trend of the prior five days. A bearish
stance would have
been profitable.
THE NATURE OF REGRESSION FORECASTS
The high daily volume of OEX index options traded makes the S&P 100 index an
interesting application
of the regression forecast approach. I have examined a time period from early October
1991 to
mid-January 1992. The OEX close and its forecast are in Figure 2; the r 2 values in
Figure 3; %F in Figure
4, and Figure 5 has %F around the mid-November plunge.
Several observations can be made from the OEX analysis. First, the forecast lags the
OEX in an uptrend
or in a downtrend. Second, the close and the forecast cross over several days before a
trend change. This
crossover can be seen as a zero crossing in the %F chart. Significant trend changes are
preceded by
trendless periods with values of r 2 near zero. Strong trends are accompanied by high
values of r 2 and
regression slope. These observations support the general rules of interpretation noted
above. As Figure 5
shows, %F provided a timely warning of an impending trend change just before the
OEX fell 15.68 points.

455
I have included data for wheat (cash) from 1989 to indicate the use of this approach
with commodities.
The market showed significant trends during this period with good periodicity, as
shown in Figures 6, 7
and 8. The %F zero crossings were timely indicators of trend change. Features
observed with OEX charts
are also seen here; note in particular how %F can be used to identify extremes in the
market from Figures
4 and 8.
Simple linear regression yields forecasts of the high, low and close for stocks, indices
or commodities.
these forecasts can be used to develop a trading plan. You can trade with the trend,
against the trend,
intraday or interday. The forecast oscillator, %F, provides early warning of trend
changes taken together
with the regression slope and coefficient of determination. This approach works best
in trending markets
or trading range markets; it is only moderately useful in volatile markets with choppy
price action. These
objective forecasts will let you trade less emotionally and more mechanically. Profits
will look up when
you can look ahead.
Tushar Chande holds a doctorate in engineering from the University of Illinois and a
master's degree in
business administration from the University of Pittsburgh.
REFERENCES
Lafferty, Patrick [ 1991 ]. "A regression-based oscillator," Technical Analysis of
STOCKS & COMMODITIES,
Volume 9: September.
Merrill, Arthur [1991]. "Fitting a trendline by least squares," Technical Analysis of
STOCKS & COMMODITIES,
Volume 9: December.
Pfaffenberger, Roger, and James Patterson [1987]. Statistical Methods for Business
and Economics,
Irwin.
-----Original Message-----
From: owner-metastock@metastock.com [mailto:owner-
metastock@metastock.com]On Behalf Of Steve Karnish
Sent: Thursday, January 10, 2002 10:34 AM
To: metastock@metastock.com
Subject: Forecast Oscillator

List,

Does anyone have the math formula for Chande's Forecast Oscillator?

Thanks,

Steve

456
From my archives.....I found three different formulas for the True Strength Index:
1. rr:= Input("first smoothing r" ,1 ,100 ,25 );
ss:= Input("second smoothing s" ,1 ,100 ,13 );
uu:= Input("third smoothing u",1,100,1);
numerator:=100*(Mov(Mov(Mov(ROC(C,1,$),rr,E),ss,E),uu,E));
denominator:=Mov(Mov(Mov(Abs(ROC(C,1,$)),rr,E),ss,E),uu,E);
If(denominator<0,numerator/denominator,0);
2.
100*(Mov(Mov(ROC(C,1,$),40,E),20,E)/Mov(Mov(Abs(ROC(C,1,$)),40,E),20,E))
3. rc:=Mov(Mov(ROC(C,1,$),40,E),20,E);
rc1:=If(rc=0,1,Mov(Mov(Abs(ROC(C,1,$)),40,E),20,E));
100*(rc/rc1)
Take your pick. <g
Claud
neo wrote:
Would you mind posting the formula?Thanks
-----Original Message-----
From: owner-metastock@metastock.com [mailto:owner-
metastock@metastock.com]On Behalf Of William Gross
Sent: Wednesday, January 02, 2002 2:23 PM
To: metastock@metastock.com
Subject: True Strength Index
Has anyone system tested to see if the 25/13 periods used in the formula for
theTrue Strength Index in the Active Trader Magazine article this month is
better or worse than some alternatives (like 17/9)? Especially on a 15 minute
chart... William GrossVenice CA

FORECAST OSCILLATOR

ForecastOsc
or
{Forecast Osc-Chande}
{from jseed}

457
Pds:=Input("Time Periods",1,1000,5);
Fld:=Input("Price Field 1=C 2=O 3=H 4=L",1,4,1);
PFld:=If(Fld=1,C,If(Fld=2,O,If(Fld=3,H,L)));
Sig:=Input("Signal MA Periods",1,200,3);
ForO:=((Pfld-(Ref(LinearReg(Pfld,Pds),-1)+
Ref(LinRegSlope(Pfld,Pds),-1)))*100)/Pfld;
ForO;
Mov(ForO,Sig,E);
{end}

Jeff,

Try applying this method to Nokia (8% band around the FO), Intel (7%),
Goldman Sachs (6%-see attachment). Don't forget to set system tester to -1
and open. This will initiate your trades on the opening of the following
day you trigger a signal.

Time travel into the next quarter and you will find the above issues being
traded as part of the 50-75 "single stock futures". Then, with a ~$135 in
profits (GS over the last two years), imagine how much fun it would be with
only 20% margin. I can't wait until the "series 7" idiots start to trade in
this arena.

Take care,

Steve
----- Original Message -----
From: Jeff Haferman <Jeff_Haferman@yahoo.com
To: <metastock@metastock.com
Sent: Wednesday, January 23, 2002 8:50 AM
Subject: Re: Forecast Oscillator

Thanks Steve,
I'll study this.

I'm very familiar with your site, I've been learning from it for
the last couple of years ;)

Jeff

Steve Karnish wrote:

Jeff,

Chande has the finest indicators (my humble, subjective opinion) I have
ever

458
"eyeballed". Unfortunately, I have never read or seen anything that

would
suggest that Chande knows how to apply "rules" to his fine work. I'm
sure
he uses them well, but I can find nothing that hints at his approach.

The Forecast Oscillator can be a real gem. I like to use a 13 period FO.
Typically, stocks that fluctuate more than 10% from the Forecast
Oscillator
seem to perform the best under testing. A simple optimisation would look
like:

Enter Long:
Cross(opt1,ForecastOsc(CLOSE,opt3))

Close Long:
Cross(ForecastOsc(CLOSE,opt3),opt2)

I like to use 13 as a default for opt3 (or you can test). opt1 is the
trigger level to trigger a long trade and opt2 triggers the sell to
offset
the position. If you are testing commodities or the Q's, just change the
"Close Long" to Enter Short. If I know a stock ranges up to 15% from the
linear regression formed by the Forecast Oscillator, I will test for
points
between 1 and 15, stepping up a point (1) and -1 to -15. Because of the
way
the formula is written, you must change the optimisation levels for each
test. Some stocks don't trade beyond a percent or two of their price.
Testing whole numbers above "one" wouldn't do you any good (under those
circumstances).

Attached is a chart of ERTS (I trade the stock publicly, at my site, with


different rules), showing the FO13 and triggers of +10/-10 (I only use
symmetrical triggers). During the last two years, it has triggered 11
winners and one loser.

Anyway, this is just one way to use it.

Take care,

Steve

459
CHANDE'S DYNAMIC MOMENTUM INDEX

'DMI is a momentum index that uses a variable length (number of days)


determined by the volatility
'in price. If volatility is low, the calculation uses a long period. If
volatility is high, the
'calculation uses a short period.
'
'The number of days is determined as follows:
'
'Std5 = Standard Deviation of the Close over past 5 days
'AvgStd = 10 day Average of Std5
'V = Today 's Std5 / AvgStd
'TD = Int(14 / V)
'
'Note that if the Std5 is greater than AvgStd then V will be greater than 1
and Td will be
'less than 14. If Std5 is less than AvgStd then V will be less than 1 and Td
will be greater
'the 14. Td is limited to the range 5 to 30.
'
'Td is used as the period for calculating RSI ( Relative Strength Index ).
'
'Reference:
'Chande, Tushar S. and Kroll, Stanley.
'The New Technical Trader, New York: John Wiley, 1994.

HTH, Andreas

-----Ursprungliche Nachricht-----
Von: owner-metastock@metastock.com
[mailto:owner-metastock@metastock.com]Im Auftrag von rudolf stricker
Gesendet: Sonntag, 3. Februar 2002 17:38
An: metastock@metastock.com
Betreff: Re: momentum indicators, using also o-h-l

On Thu, 31 Jan 2002 06:09:07 +0000, you wrote:

Check your Metastock Manual for interpretation of Qstick. It


has about a
page of discussion. The manual says that Qstick is the moving
average of
the difference between the open and close.

So Qstick seemingly is rather a trend indicator than a momentum


indicator, (which I'm looking for, see the subject).
Maybe, I should start with a given momentum indicator e.g. Chande's
"Dynamic Momentum Index", and integrate o-h-l in an appropriate manner
into it...

460
Is the formula for the DMI available somewhere?

mfg rudolf stricker


| Disclaimer: The views of this user are strictly his own.

ADAPTIVE SYSTEMS

----- Original Message -----


From: "John Manasco" <john@manasco.net
To: <metastock@metastock.com
Sent: Wednesday, February 06, 2002 8:01 PM
Subject: Re: adaptive systems - how to define appropriate time windows ?
Here is a discussion from another email list on adaptive systems.

Adaptive systems is pretty complicated matter. There are several known ways of
doing it, at least about 4. The math is not too complicated but arcane and the concept
is hard to comprehend. There are several questions:
• what does adaptive system mean?
• what do you adapt it to?
• what to adapt?
• what do you adapt it based on? how do you do it?
• what is the math?
• how to you implement it in code?
• is it doable?

Adaptive means the system's algorithm tunes itself up as the "market footprint"
changes to maximise the performance criterion which is max reward at min risk. If
you want to discuss adaptive first you have to discuss non adaptive systems like the
ones you can code in TSs. The main objective of any system is to find the balance in
between the risk and the reward - which is the main criteria. in TS we do that by
running optimisation and finding the suitable peak in the optimisation function.
Optimisation function (OF) has a dependent and independent variables. D dependent
variables are Max Profit (MP) and Min Risk (MR), independent are your parameters /
inputs ( I )
example: if you have 3 inputs 3 Is your OF will is 4 or 5 dimensional ( 3 Is + MR +
MP ). this could be graphically representing as a multidimensional surface. the key is
to find the peak of that surface( that's why if system has more
than 3 inputs I toss it ) - hard to do because it's hard to visualise. You can see now that
if a system does not adapt you have to find the peak manually or you have to
compromise. *most systems fail because they are not
adaptive - curvefitted!!!

So, the purpose of adaptive system is to find that peak in OF in real time. To know the
peak you need to know
the OF. to know OF you have to know: MR, MP, and all Is. let's break it down.

461
MR and MP: you have to calculate systems performance in real time. But the system
does not know how
it performs itself. it needs some criteria to go by. how can a system know if it works
on all cylinders and bangs
out max profit at min reward or just barely making it? you have to give it a reference
to go by. this ref performance
is called system efficiency (SE). SE is calculated in % by comparing in real time the
performance of real system to
the performance of ideal system. Another term needs to be introduced - ideal system.
Ideal system buys the very top and sells the very bottom. you can easily calculate that
buy coding a function that will sell and buy in hindsight and give you max possible
profit at zero risk. now, then you take ideal system as 100% efficiency, then your
SE = real performance / ideal performance. say your average SE = 30% that means
you are pulling out 30% or what you can pull out of the market. this becomes the
criterion to go by in adaptation or Max SE. this can fluctuate from Min allowable SE
say 20% to 100% ( will never be 100%). Based on statistical runs you can then
calculate
mean SE to go by, say 30%. now you know what to adapt to.

next is what to adapt:


well, obviously you have to adapt your parameters or inputs - your Is. you have to
tune your inputs to get the highest
SE. that's where it gets real tricky. to be able to do that you need OF- you need that
curve to tell you what the parameters should be to get max SE. let's leave this out for a
second. next is what do you adapt based on:
you adapt based on changing market conditions or what I call changing "market
footprint". every instrument traded out there has it's own particular market footprint
which is: a compilation of statistical variables common
to all instruments, like: average true range ( bar velocity), average volatility, volatility
std, average volume,
liquidity and so on. footprint is a set of statistical parameters that you can use as
fingerprints
To identify and differentiate between different instruments you trade. this footprint
will change in real time... volatility will fluctuate, so will volume, average bar range,
etc. one day SP can trade real narrow range with low volume, the next day volatility
can explode - market footprint changed.

Next is how to adapt it. well, the first thing that should pop into your mind is that you
need a feedback loop of some sort. The rational loop is this:
footprint changed -adjust parameters -
to maximise SE ratio -if SE drops means
footprint changed -repeat.
if you examine this loop you'll notice that
you need at least 2 functions ( transfer functions )
to do that:
1. parameters = f ( footprint )
2. SE = f( parameters )
of you can rewrite it as:
SE = f ( f ( footprint ) ); tells you systems

462
efficiency will fluctuate based on changing

market conditions.
so where do you get those functions:

a. from a sample run: you do a pass over data, build your OF function and then build
your parameter = f( footprint ) function. log it in and use it for the real time run. you
can keep updating those functions in real time. this is similar to manual optimisation
where you do sample runs but in addition to that the OF gets updated in real time.

b. ramp up period. you start with a ramp up period and update your 1 and 2 functions
as you go along
your SE will start with 0% and will be improving as those functions will be more and
more accurate.
the system like this will start trading real bad and then improve it's performance as it
adapts and learns to trade better and better. the performance will taper off and
stabilise as those functions are saturated.

c. multiple parallel models: you run multiple systems based on different parameters
and find the best performing one under changing market footprint and trade that best
one. This approach however does not guarantee that the best performing current
model will continue to be the best tomorrow.

John Clayburg implemented this approach by running parallel performance functions


in TS. it showed a little bit of improvement but not much. the reason again that you
are chasing the best performing model that will not necessarily continue to perform
good tomorrow ( best fit today is not necessarily will be the best fit tomorrow )

d. my approach. since I already went through all of the bs in paragraphs a through c


what I do is the direct analytical approach - a shortcut. I ask myself a question – how
this specific market variable will affect my SE ( systems efficiency, performance ) or
my P&L through direct math. first I try to tie as many parameters to market footprint (
market variable ) it allows me to make a shortcut and I don't have to find parameter =
f ( market footprint ) function. market footprint becomes the parameter itself. Next, I
try to answer the question of how will this market variable affect my PL analytically -
I try to find SE = f ( footprint ) function by studying how, say, volatility affects my
PL in the signal generator. if market becomes noisy how will it affect my PL in the
system. the answer is simple: more noise you got less money you make. Last step is to
measure market variable ( market footprint ) and through those functions adjust your
algorithm to pump up your SE. This is the right approach and the best one. In short,
your adaptive techniques should be built right into your trading algorithm.

define market footprint ( which market variables hurt or improve your systems
performance ) then:
• use those as your parameters so that the market will itself adjust those for you then

• define your signal generating algorithm to include


• those parameters and specify how those will affect your systems performance.
-specify how your trading algorithm should change based on that parameter.

463
that's it. it becomes self adaptive.
an example:
• market footprint = noise level
• noise level = your parameter
• more noise -less profit
• less noise -more profit.
if more noise then increase risk and lengthen time horizon to maximise profit
and minimise loss.
if less noise then decrease risk and shorten time horizon to maximise profit
and minimise
loss.

a common parameter is lookback. in MA. well, going by what is said is MA


lookback has anything
to do with a market footprint market variable - nope. You can't differentiate
markets by MA lookback - toss it.
another common lookback variable - ATR ( lookback ) –defines a lookback in
average true range calculation. Can ATR be used as a market variable to
define market footprint? possibly can. that's why ATR often referred to as
"adaptive" variable - changing. but even ATR can vary based on lookback
used. so, it's semi adaptive, you still have the lookback to deal with.

It is self evident that the first step in designing adaptive systems is to define market
footprint in variables that require no parameters or allow only parameters will not
affect variable measurement itself. If you try to define noise through ATR then ATR
is dependent on lookback unless the lookback value is high. If lookback value is high,
ATR will not be sensitive to it's most recent change. :-) go figure.

Volatility also requires lookback. Almost everything there needs a damn lookback or
a factor. However if you isolate the most recent swing (current trade) in the price and
find pivot high and pivot low and find the duration of that swing and use that duration
as a lookback then what your saying is that I only want to measure noise during the
most current trade that I am in.. This becomes adaptive lookback and ATR becomes
adaptive. then your market variable can be called - ATR of last tradable swing... and
not ATR of some arbitrary lookback that you think is suitable.

At the end it all comes down to about 4-5 market variables that you need to define and
most of them have to do with
volatility in one form of the other. Volatility is the main market variable!

• untradable volatility = noise = risk = lag


• min tradable volatility = vector deviation = min signal = reward = profit or loss
differential.
• max tradable volatility = vector volatility = max signal = trend = sum of all
positive and negative profit differentials ( profitable and unprofitable trades - risk
and reward )= your total P&L.
• find noise then you can find the signal
• find the signal then you can find the trend.

464
• find the trend then you are done just don't use any fixed lookbacks and factors :-)

This is pretty much it without any hard math thrown in.


bilo.
P.S. markets are dynamic, most systems are static that's why most systems don't
work. and if you add irrational buy and sell rules on top of many input parameters,
they don't work at all.

----- Original Message -----


From: "rudolf stricker" <lists@tbus-muc.de
To: <metastock@metastock.com
Sent: Wednesday, February 06, 2002 12:16 PM
Subject: adaptive systems - how to define appropriate time windows ?

List,

using an adaptive system for day-to-day trading of DAX options, I wonder, which
criteria might be helpful to define "the best" time window to deal with ...
Presently, I use a 5 years window, where the rating criteria to select an appropriate
system are weighted something like exponentially over time.

But at these rapidly changing markets, I get some unsatisfactory results: While my
system shows nice results e.g. for long puts over the last year or so, this potential
couldn't be used: my money management (based on 5 years) nearly stops me out
from trading these system results, because the strategy working well for the last
year
doesn't show good results for at least some of the years before.

So my questions are:

• What time period may be appropriate to construct a(n adaptive) trading system for
a given equity?
• What criterions (to read from the equity's historical data) could help to define "the
best" time period?
• What other aspects may be important to define an appropriate time window?

Any hint is welcome ...

mfg rudolf stricker


| Disclaimer: The views of this user are strictly his own.

I'm not sure what you're looking for. What are you trying to adapt to? If you are trying
to adapt your system to the current cycle length look at some of Dr. John Elhers
indicators that measure cycle length. If you're trading
options why not make the system adaptive to current or historical volatility.
Personally I don't believe a "best" time period exists. That is too restrictive for me. A

465
strongly trending stock will probably have a long cycle length while that same stock
may have a very short cycle length if it is in a trading range. The problem with cycle
lengths is that they are based on the past and not the future but they may provide a
best guess as to the future cycle length.

ON BALANCE VOLUME

You will get a better feeling for open interest influence if you combine it with
an on-balance-volume indicator. The best combination I found is OBVtd=
OBVyest.+((
Close-open/ high-low)*VOLtoday). Try it, you'll like it. Ira

Stewart Taylor wrote:

Hi Stig;

My interpretation of the OI drop is a bit different than yours. I consider


a drop in OI as potentially bullish when it accompanies a violent/spike low
or after a long trend.. hthe main requirement is that it occur over a
relatively short period of time... My interpretation is that the last long
that needed to capitulate capitulated and made the low and now buyers can
begin to operate.

Over a long period (like on the gold chart) I suspect that it is more an
indication of lack of interest than anything else... funds don't employ
margin in markets that are in trading ranges and markets in long-long
trading ranges don't attract the trading publics attention.

The good news... low levels of OI suggest that there is margin available to
be deployed and support the trend (which ever way it materializes).

Just another interpretation...

Stew.

At 04:24 AM 2/8/2002 , StigO wrote:


part II
Technical indicators is, in my opinion very bullish.

I brushed up on Drummond this morning to check open Interest. And he is very clear
when he says that falling OI at bottoms are very bullish (all the shorts are closing their
poitions and new longs don't have the courage to buy - yet)
Check out the lower histogram and how OI has declined since the 1999 low The
middle indicator STRSI shows a very promising "hidden Divergence" very reliable
and bullish.

466
The pink histogram is Robert Miners Dynamic time Projection, which projects trend
changes with the help if past tops/bottom and fib ratios. Looks like the next top will
be around March 15 (Spring Equinox March 20 which is notorious for trend changes
in Gold!!)

So all in Medium term bullish for Gold.

The June Gold contract is next.


To cut out the noise I have used closing prices, which gave sone surprising result not
evident on Bar charts.

The chart suggests we have broken many levels.


6. The 38,2 fib retracement og the AC decline
7. The 50% retracement of the BC decline which O associate to the 3 tops which
also has been broken
8. No matter how you draw the trendlines they have been broken 3 days ago - 2 days
ago they were tested and yesterday we took off again
9. If we break the 61.8% retracement level (at 302)of the BC decline it looks VERY
promising (we are at 306 right now)
10. 2 forks with 50% offset (black and blue) have also been broken at the trendline
level.

If you use bar charts you get quite different meaningless result -try it out. Since
most people use barcharts today (I guess), what you see in the close only chart is
not so evident. Fridays are good days for explosions - let's see what happens
today....

Thanks D for poking at me - now I am convinced - I'll keep my DROOY for a


while longer.

Regards
Stig

MARKET COMMENTARY

In TS2000i and TS6 you can cut and past the following code for the "Analysis
Commentary" which helps for debugging.

====================================
Commentary("", newline, newline ,
"timetrade=", timetrade, newline,
"marketposition =", marketposition , newline,
"TradeOK=", TradeOK, newline,
"date =", date , newline,
"date[1] =", date[1], newline,
"High =", High , newline,

467
"Low =", Low, newline,
"condition50-Volume =", condition50 , newline,
"totaltrades =", totaltrades , newline, );
=================================

1- apply the code to the bottom of an indicator, a showme, a paintbar, a


function, or a strategy.
2- apply the indicator, showme, etc. to a chart.
3- with the chart open, activate the "Analysis Commentary" button on the
toolbar. It looks like a printed page and is to the left of the
"drawing objects" button.
4- the cursor changes to a small pointer with the icon like a printed page
near it.
5- click on the small pointer on the particular bar in which you want to see
the indicator, etc. values for debugging purposes.

Note: the commentary above has several components.


A- the side on the left, which has words (such as "marketposition=") and
than an = sign.
B- the middle--- after the second quote mark, and between the two
commas ---- to the left of the word 'newline'
C- the side on the right with the word 'newline' followed by a comma

1- the left side is a label that appears on the chart when you
activate the "Analysis Commentary". It identifies the value that will print
out
on the chart. Just change the words, but keep the quotes and
keep the = sign.
2- the middle is the condition, or variable or piece of info you want
the value of.
3- the word 'newline' is just a line carriage to make the "Analysis
Commentary" more readable when you open it on the chart.

ACTIVE TRADER MAGAZINE CODE

September 2000 Trading System Lab (variation):


Inputs: LookBack(9), WhereToBuy(0.5);
Variables: HighValue(0), LowValue(99999), BuyValue(0);

LowValue = Lowest(Low, LookBack);


HighValue = Highest(High, LookBack);

BuyValue = (HighValue - LowValue) * WhereToBuy ;

If MarketPosition = 0 Then Begin


Buy tomorrow at BuyValue + LowValue Stop;

468
If Close < LowValue[1] Then
ExitLong at Open;

If BarsSinceEntry = 9 and OpenPositionProfit < 0 Then


ExitLong on Open;

For "Pivotal Trading" by John Ehlers in the September 2000 issue:


Vars: Pivot(0), S1(0), S2(0), R1(0), R2(0);
Pivot = (H[1] + L[1] + C[1]) / 3;
R1 = 2*Pivot - L[1];
S1 = 2*Pivot - H[1];
R2 = Pivot + (R1 - S1);
S2 = Pivot - (R1 - S1);
Plot1(R1, "R1");
Plot2(S1, "S1");

October 2000
The following TradeStation code is from "Moving beyond the closing price" in the
issue.
For TradeStation users, the EasyLanguage code is:
Inputs: LookBack(20);

Variable: PercChange(0),
NewLevel(0),
AvgPercChange(0);

PercChange = (Close -
Close[1])/Close[1];

AvgPercChange =
Average(PercChange,20);

NewLevel = Close *
(1 + AvgPercChange);
Plot1[1](NewLevel,þþ);

**

Inputs: StDevs(1);

Variable:StdDevChange(0),
UpLevel(0), DownLevel(0);

StdDevChange =
StdDev(PercChange, 20);

UpLevel = Close *
(1 + AvgPercChange +
StDevs * StdDevChange);

DownLevel = Close *
(1 + AvgPercChange -
StDevs * StdDevChange);
Plot2[-1](UpLevel,þþ);
Plot3[-1](DownLevel,þþ);

469
**

HighPercChange = (High - Close[1])/Close[1];

**

Input: VSStd(1);

Vars: SumVS(0), AvgVS(0), DiffVS(0), StdVS(0), SetArr(0),


SumArr(0), DiffArr(0), VSLow(0), VSMid(0), VSHigh(0);

{First we define the array}

Array: VS[20](0);

{Then we‰re using a loop function to fill it with the different price changes}

For SetArr = 0 To 4 Begin

VS[SetArr * 4 + 0] = (O[SetArr] - C[SetArr + 1]) / C[SetArr + 1];

VS[SetArr * 4 + 1] = (H[SetArr] - C[SetArr + 1]) / C[SetArr + 1];

VS[SetArr * 4 + 2] = (L[SetArr] - C[SetArr + 1]) / C[SetArr + 1];

VS[SetArr * 4 + 3] = (C[SetArr] - C[SetArr + 1]) / C[SetArr + 1];

End;

For SumArr = 0 To 19 Begin

If SumArr = 0 Then

SumVS = 0;

SumVS = SumVS + VS[SumArr];

If SumArr = 19 Then

{Here we calculate the average price change over the period}

AvgVS = SumVS / 20;

For DiffArr = 0 To 19 Begin

If DiffArr = 0 Then

DiffVS = 0;

{Then we calculate the standard deviation}

DiffVS = DiffVS + Square(VS[DiffArr] - AvgVS);

If DiffArr = 19 Then

StdVS = SquareRoot(DiffVS / 20);

End;

End;

{Finally, we add the moving average (and the standard deviations) to the latest close for an
indication of tomorrow‰s trading range}

470
VSLow = C * (1 + (AvgVS - StdVS * VSStd));

VSMid = C * (1 + AvgVS);

VSHigh = C * (1 + (AvgVS + StdVS * VSStd));

Plot1[-1](VSLow, ‹VS Lowþ);

Plot2[-1](VSMid, ‹VS Midþ);

Plot3[-1](VSHigh, ‹VS Highþ);

October 2000 Trading System Lab:

Variables: RelStr(0), AvgRelStr(0), CalcRelStr(0), AvgOBV(0), CalcOBV(0),


CalcStr(0);

RelStr = IFF(AvgPrice = 0, 0, AvgPrice / AvgPrice Data2);


AvgRelStr = Average(RelStr, 5);
CalcRelStr = IFF(RelStr = 0, 0, RelStr / AvgRelStr);

AvgOBV = Average(OBV, 5);


CalcOBV = IFF(OBV = 0, 0, OBV / AvgOBV);

CalcStr = CalcRelStr * CalcOBV;

If CalcStr Crosses Above 1.0 and MarketPosition = 0 Then


Buy on Close;
If CalcStr Crosses Below 1 Then
ExitLong on Close;
If Close < EntryPrice * 0.96 Then
ExitLong on Close;

November 2000 Trading System Lab:

Condition1 = MarketPosition = 0 and Close Average(Close, 50) and High


High[1] and
(close[1] < close[2] and close[2] < close[3]);

If Condition1 = True Then


Buy tomorrow at Market;
ExitLong ("Stop") tomorrow at Lowest(Low, 2) Stop;
If PositionProfit 0 Then
ExitLong ("Exit") tomorrow at Market;

December 2000 issue:


For "Trading the momentum of market breadth:"
{Data1 = Either the SPY S&P 500 index tracking stock or the S&P 500 commodity futures
contract.

Data2 = Advancing issues of the Nyse.}

Inputs: RL(7), BZ(3), SZ(1);

If ROC(Close Data2, RL) > BZ Then Buy;

If ROC(Close Data2, RL) < SZ Then Sell;

471
For "Doubly adaptive profit targets:"

Vars: TrendIndicator(0), RiskReward(0);

If ADX(14) > ADX(14)[1] Then


TrendIndicator = 4;
If ADX(14) <= ADX(14)[1] Then
TrendIndicator = 2;

Condition1 = MarketPosition = 0 and Close > Average(Close, 50) and Open


Tomorrow > High and TrendIndicator = 4;

If Condition1 Then Begin


Buy Tomorrow at High Limit;
RiskReward = AvgTrueRange(20);
End;

If MarketPosition = 1 Then Begin


ExitLong ("Profit") Tomorrow at (EntryPrice + RiskReward * TrendIndicator)
Limit;
ExitLong ("Loss") Tomorrow at (EntryPrice - RiskReward * TrendIndicator)
Stop;
If Close < Average(Close, 50) Then ExitLong ("Trend") at Market;
End;

Jan./Feb. 2001
From "Better System Performance measures," p. 62.
Vars: TotTr(0), Prof(0), TradeStr2(“”), CumProf(1), ETop(0), TradeStr2(""),CumProf(1),
EBot(0), EDraw(0), TradeStr2("");

TotTr = TotalTrades;

If TotTr > TotTr[1] Then Begin

Prof = 1 + PositionProfit(1) / (EntryPrice(1) * BigPointValue);

CumProf = CumProf * Prof;

ETop = MaxList(ETop, CumProf);

EBot = MinList(EBot, CumProf);

EDraw = CumProf / ETop;

TradeStr2 = NumToStr((Prof - 1) * 100, 2) + “,” + NumToStr((CumProf - 1) * 100, 2) + "," +


NumToStr((ETop - 1) * 100, 2) + “,” + NumToStr((EBot - 1) * 100, 2) + "," + NumToStr((EDraw
- 1) * 100, 2) + NewLine;

{Make sure that you have a temp directory on your hard drive, or re-write the path
inside the FileAppend command to an exsisting directory of your choice.}
FileAppend("C:\Temp\Chap1-2.csv", TradeStr2);

End;

For the Trading System Lab page:


Vars: SumVS(0), AvgVS(0), DiffVS(0), StdVS(0), SetArr(0), SumArr(0), DiffArr(0), VSLow(0),
VSMid(0), VSHigh(0), RiskReward(0);

472
Array: VS[20](0);

For SetArr = 0 To 4 Begin

VS[SetArr * 4 + 0] = (Open[SetArr] - AvgPrice[SetArr + 1]) / AvgPrice[SetArr + 1];

VS[SetArr * 4 + 1] = (High[SetArr] - AvgPrice[SetArr + 1]) / AvgPrice[SetArr + 1];

VS[SetArr * 4 + 2] = (Low[SetArr] - AvgPrice[SetArr + 1]) / AvgPrice[SetArr + 1];

VS[SetArr * 4 + 3] = (Close[SetArr] - AvgPrice[SetArr + 1]) / AvgPrice[SetArr + 1];

End;

For SumArr = 0 To 19 Begin

If SumArr = 0 Then

SumVS = 0;

SumVS = SumVS + VS[SumArr];

If SumArr = 19 Then

AvgVS = SumVS / 20;

For DiffArr = 0 To 19 Begin

If DiffArr = 0 Then

DiffVS = 0;

DiffVS = DiffVS + Square(VS[DiffArr] - AvgVS);

If DiffArr = 19 Then

StdVS = SquareRoot(DiffVS / 20);

End;

End;

VSLow = AvgPrice * (1 + (AvgVS - StdVS * 2));

VSMid = AvgPrice * (1 + AvgVS);

VSHigh = AvgPrice * (1 + (AvgVS + StdVS * 2));

If MarketPosition = 0 Then Begin

Buy ("Buy") Tomorrow at VSLow Limit;

RiskReward = VSMid-VSLow;

End;

If MarketPosition = 1 Then

ExitLong ("PT") Tomorrow At VSHigh Limit;

If MarketPosition = 1 Then

ExitLong ("TS") Tomorrow At VSLow Stop;

473
If Open Tomorrow >= VSLow Then

ExitLong ("SLa") From Entry ("Buy") At (VSLow-(VSMid-VSLow)) Stop;

If Open Tomorrow < VSLow Then

ExitLong ("SLb") From Entry ("Buy") At (Open Tomorrow-(VSMid-VSLow)) Stop;

March 2001
For the Trading System Lab:
Vars: MaLen(21), Ratio2(0), Ratio3(0), MaRatio2(0), MaRatio3(0), DiffMaRatio2(0),
DiffMaRatio3(0), ProdDiff(0), UpperProdDiff(0), LowerProdDiff(0);

Ratio2 = C / C Data2;
Ratio3 = C / C Data3;

MaRatio2 = Average(Ratio2, MaLen);


MaRatio3 = Average(Ratio3, MaLen);

DiffMaRatio2 = Ratio2 / MaRatio2;


DiffMaRatio3 = Ratio3 / MaRatio3;

ProdDiff = DiffMaRatio2 * DiffMaRatio3;


UpperProdDiff = 1 + StdDev(ProdDiff, MaLen) * 1;
LowerProdDiff = 1 - StdDev(ProdDiff, MaLen) * 2;

If MarketPosition = 0 and BarsSinceExit(1) > 1 and ProdDiff > UpperProdDiff and ProdDiff >
ProdDiff[2] Then
Buy ("Go Long") at Close;

If MarketPosition = 1 and ProdDiff < ProdDiff[4] Then


ExitLong ("End Long") at Market;
ExitLong ("Trailing Long") tomorrow at Lowest(Low, 2) Stop;

If MarketPosition = 0 and BarsSinceExit(1) > 1 and ProdDiff < LowerProdDiff and ProdDiff <
ProdDiff[2] Then
Sell ("Go Short") at Close;

If MarketPosition = -1 and ProdDiff > ProdDiff[4] Then


ExitShort ("End Short") at Market;
ExitShort ("Trailing Short") tomorrow at Highest(High, 2) Stop;

If BarsSinceEntry = 8 and OpenPositionProfit < 0 Then Begin


ExitLong at Market;
ExitShort at Market;
End;

April 2001
"Trading the VIX," by Price Headley: This is the system code (written in
EasyLanguage for TradeStation), where Data1 is the OEX and Data2 is the VIX
index.

{Code by Price Headley, BigTrends.com}

If Close of Data1 > Average(Close of Data1, 10) and Close of Data2[5] < BollingerBand(Close
of Data2, 21, 2)[5] and Close of Data2[6] > BollingerBand(Close of Data2, 21, 2)[6] Then
Buy on Close of Data1;

474
If BarsSinceEntry = 5 and Close of Data1 < Close of Data1[5] Then
ExitLong on Close of Data1;

If Close of Data1 < Average(Close of Data1, 10) and Close of Data2[10] >
BollingerBand(Close of Data2, 21, -2)[10] and Close of Data2[11] < BollingerBand(Close of
Data2, 21, -2)[11] Then
Sell on Close of Data1;

If BarsSinceEntry = 5 and Close of Data1 > Close of Data1[5] Then


ExitShort on Close of Data1;

May 2001
Avoiding system testing traps
Inputs: Len(63);

Vars: PointRange(0), SumPosRange(0), SumNegRange(0), AvgPosRange(0),


AvgNegRange(0);

PointRange = High - Low;


If Close > Close[1] Then
SumPosRange = SumPosRange * (Len - 1) / Len + PointRange;
If Close < Close[1] Then
SumNegRange = SumNegRange * (Len - 1) / Len + PointRange;

AvgPosRange = SumPosRange / Len;


AvgNegRange = SumNegRange / Len;

{Plot statements to use in indicator only}


Plot1(AvgPosRange, "");
Plot2(AvgNegRange, "");

{Buy/sell statements to use in system only}


{This identifies the up trend}
If PosRange > NegRange and MarketPosition = 0 Then
Buy on O;
If PosRange < NegRange Then
ExitLong ("Down Trend") on Open;

{This identifies the down trend}


If NegRange > PosRange * 1.06 and NegRange >= NegRange[1] and PosRange <
PosRange[1] and MarketPosition = 0 Then
Sell on O;
If NegRange < PosRange * 1.06 Then
ExitShort ("Up Trend") on O;

{This is the short-term trading rules within the up trend}


If BarsSinceEntry >=1 Then Begin
ExitLong ("Loss Long") tomorrow at EntryPrice - NegRange stop;
ExitLong ("Trail Long") tomorrow at Open tomorrow - NegRange stop;
ExitLong ("Profit Long 2") tomorrow at Open tomorrow + 3*PosRange limit;
ExitLong ("Profit Long 1") tomorrow at EntryPrice + 6*PosRange limit;
End;

{This is the short-term trading rules within the down trend}


If BarsSinceEntry >=1 Then Begin
ExitShort ("Loss Short") tomorrow at EntryPrice + PosRange stop;
ExitShort ("Trail Short") tomorrow at Open tomorrow + PosRange stop;
ExitShort ("Profit Short 2") tomorrow at Open tomorrow - 2*NegRange limit;

475
ExitShort ("Profit Short 1") tomorrow at EntryPrice - 4*NegRange limit;
End;

Spreadsheet for "Building a better trend indicator."


June 2001
For the Trading System Lab:

Input: VSStd(1);
Vars: SumVS(0), AvgVS(0), DiffVS(0), StdVS(0), SetArr(0), SumArr(0), DiffArr(0), VSLow(0),
VSMid(0), VSHigh(0), RiskReward(0);
Array: VS[20](0);
For SetArr = 0 To 4 Begin
VS[SetArr * 4 + 0] = (O[SetArr] - C[SetArr + 1]) / C[SetArr + 1];
VS[SetArr * 4 + 1] = (H[SetArr] - C[SetArr + 1]) / C[SetArr + 1];
VS[SetArr * 4 + 2] = (L[SetArr] - C[SetArr + 1]) / C[SetArr + 1];
VS[SetArr * 4 + 3] = (C[SetArr] - C[SetArr + 1]) / C[SetArr + 1];
End;
For SumArr = 0 To 19 Begin
If SumArr = 0 Then
SumVS = 0;
SumVS = SumVS + VS[SumArr];
If SumArr = 19 Then
AvgVS = SumVS / 20;
For DiffArr = 0 To 19 Begin
If DiffArr = 0 Then
DiffVS = 0;
DiffVS = DiffVS + Square(VS[DiffArr] - AvgVS);
If DiffArr = 19 Then
StdVS = SquareRoot(DiffVS / 20);
End;
End;
VSLow = C * (1 + (AvgVS - StdVS * VSStd));
VSMid = C * (1 + AvgVS);
VSHigh = C * (1 + (AvgVS + StdVS * VSStd));

If MarketPosition = 0 and BarsSinceExit(1) > 1 Then Begin


If Average(Close, 80) > Average(Close, 80)[11] Then
Buy ("Buy") tomorrow at VSLow limit;
If Average(Close, 80) < Average(Close, 80)[11] Then
Sell tomorrow at VSHigh limit;
End;

If BarsSinceEntry >= 1 Then Begin


ExitLong on Close;
ExitShort on Close;
End;

From "Measuring Trend Momentum:"


{Tushar Chande 2001: VIDYA/CDMA}

Input: Len(10);
Vars: Diff(0), MyConst(0), MyAdx(0), Varma(0), EmaIndex(0);

{… Index of EMA …}
If Len > 0 then EmaIndex = (2 / (1 + Len)) else EmaIndex = 0.20;

{… Stochastic oscillator using ADX …}

476
MyAdx = ADX(20);
Diff = Highest(MyAdx, 20) - Lowest(MyAdx, 20);
If Diff > 0 then MyConst = (MyAdx - Lowest(MyAdx, 20))/Diff else MyConst = EmaIndex;

{… Clamp length to that implied by input value of Len …}


If MyConst > EmaIndex then MyConst = EmaIndex;

{… Create the variable MA …}


If CurrentBar < 50 then Varma = Close else Varma = (1 - MyConst) * Varma[1] + MyConst *
Close;

Plot1(Varma, “VarMA”) ;
Plot2(XAverage(Close, Len), ”XAvg”

July 2001
Trading System Lab: Volume-weighted average

Vars: MaLen(9), AvgVolume(0), Turbo(0), InvTurbo(0), MaWeight(0), TurboMA(0);

AvgVolume = Average(V, MaLen);

Turbo = (AvgVolume - Lowest(AvgVolume, MaLen)) / (Highest(AvgVolume, MaLen) -


Lowest(AvgVolume, Malen));
InvTurbo = 1 - Turbo;

If MaLen > 2 Then MaWeight = (2 / (1 + MaLen)) Else MaWeight = 0.67;

TurboMA = TurboMA * InvTurbo + AvgPrice * Turbo;

If Date < 1000401 Then Begin


If MarketPosition = 0 and C < TurboMA and TurboMA < TurboMA [1] Then
Buy Tomorrow on Highest(High, 2) Stop;
End;

If MarketPosition = 1 and C < TurboMA Then Begin


ExitLong on Close;
ExitLong Tomorrow on EntryPrice * 0.96 Stop;
End;

If Date >= 1000401 Then Begin


If MarketPosition = 0 and C > TurboMA and TurboMA > TurboMA [1] Then
Sell Tomorrow on Lowest(Low, 2) Stop;
End;

If MarketPosition = -1 and C > TurboMA Then Begin


ExitShort on Close;
ExitShort Tomorrow on EntryPrice * 1.04 Stop;
End;

August 2001
Trading System Lab:
If (Maxlist(High[3], Close[4]) > High[4] Or
Maxlist(High[3], Close[4]) > High[2] Or
Maxlist(High[3], Close[4]) > High[1]) and
Close < Close[1] and
Open Tomorrow <= High[3] Then
Buy 1 Contract Tomorrow on (Maxlist(High[3], Close[4]) * 1.001) Stop;

477
If (Minlist(Low[3], Close[4]) < Low[4] Or
Minlist(Low[3], Close[4]) < Low[2] Or
Minlist(Low[3], Close[4]) < Low[1]) and
Close > Close[1] and
Open Tomorrow >= Low[3] Then
Sell 1 Contract Tomorrow on (Minlist(Low[3], Close[4]) * 0.999) Stop;

If EntryPrice > 0 Then Begin


If MarketPosition = 1 Then Begin
ExitLong on EntryPrice * 0.96 Stop;
ExitLong on EntryPrice * 1.12 Limit;
End;
If MarketPosition = -1 Then Begin
ExitShort on EntryPrice * 1.04 Stop;
ExitShort on EntryPrice * 0.88 Limit;
End;
End;

If BarsSinceEntry >= 3 Then SetExitOnClose;


ExitLong on Close;
ExitShort on Close;
End;

September 2001
ADX spreadsheet from Indicator Insight

Beta values spreadsheet (Note: If prompted to update links within the spreadsheet when
Excel opens, click "No.")

Programming code for 3L-R and GAP-2H patterns (from "Keeping it simple," by Michael
Harris).

{*****************************************************
Description : 3L-R Pattern Entry Signal
Developed By : Michael Harris, Tradingpatterns.com
*****************************************************}

if l[1] < l[2] and l[2] < l[3] and h[0] > h[3] then
buy ("3L-R") next bar on the open;

{*****************************************************
Description : 3L-R Pattern Long Exit Signal
Developed By : Michael Harris, Tradingpatterns.com
Comments: ptarget and stopl are in percentage terms
*****************************************************}
variables: profitprice(0), stopprice(0);
input: ptarget(8), stopl(8);

profitprice = entryprice*(1+ptarget/100);
stopprice = entryprice*(1-stopl/100);

if marketposition =1 then begin


exitlong ("3L-R Exit") at profitprice limit;
exitlong ("3L-R Stop") at stopprice stop;
end;

**

{***********************************************
Description : GAP-2H Pattern Entry Signal
Developed By : Michael Harris, Tradingpatterns.com

478
***********************************************}
if h[0] > h[1] and h[2] > l[2] and l[0] > l[1] and l[1] > h[2] and
h[1] > l[0] then
buy ("GPA-2H") next bar on the open;

{***********************************************
Description : GAP-2H Pattern Long Exit Signal
Developed By : Michael Harris, Tradingpatterns.com
Comments: ptarget and stopl are in percentage terms
***********************************************}
variables: profitprice(0), stopprice(0);
input: ptarget(7), stopl(7);

profitprice = entryprice*(1+ptarget/100);
stopprice = entryprice*(1-stopl/100);

if marketposition =1 then begin


exitlong ("GAP-2H Exit") at profitprice limit;
exitlong ("GAP-2H Stop") at stopprice stop;
end;

**
October 2001
Formula for the Beta Value system found in the Trading System Lab (p. 82)

Inputs: DepPrice(Close of data1), IndPrice(Close of data2);


Vars: Length(63), iBeta(1), Ind(0), Dep(0), SumX(0), SumY(0), SumXY(0), SumXsq(0), j(0);

Dep = (DepPrice - DepPrice[1]) / DepPrice[1];


Ind = (IndPrice - IndPrice[1]) / IndPrice[1];

If CurrentBar >= Length Then Begin

SumX = Summation(Ind, Length);


SumXY = 0;
SumY = Summation(Dep, Length);
SumXsq = 0;

For j = 0 to Length - 1 Begin


SumXY = SumXY + (Ind[j] * Dep[j]);
SumXsq = SumXsq + Square(Ind[j]);
End;

If SumXY <> 0 and SumX <> 0 Then


iBeta = ((Length * SumXY) - (SumX * SumY)) / ((Length * SumXsq) - Square(SumX));

If IndPrice > Average(IndPrice, Length) and iBeta > 1 and MarketPosition <> 1 Then
Buy 1 Contract Tomorrow at Lowest(Low, 5) Limit;
If IndPrice < Average(IndPrice, Length) and iBeta < 1 and MarketPosition <> -1 Then
SellShort 1 Contract Tomorrow at Highest(High, 5) Limit;

If EntryPrice > 0 Then Begin


If Close < EntryPrice * 0.96 or Close > EntryPrice * 1.12 Then
Sell Tomorrow at Market;
If Close > EntryPrice * 1.04 or Close < EntryPrice * 0.88 Then
BuyToCover Tomorrow at Market;
End;

End;

479
November 2001
Formula for the Harris 3L-R pattern variation system found in the Trading System Lab
(p. 74)

Inputs: PTarget(12), StopL(4);


Variables: ProfitPrice(0), StopPrice(0);

If L[1] < L[2] and L[2] < L[3] and H[0] > H[3] Then
Buy ("3L-R") Next Bar on Open;

ProfitPrice = EntryPrice * (1 + PTarget / 100);


StopPrice = EntryPrice * (1 - PTarget / 100);

If MarketPosition = 1 Then Begin


Sell ("3L-R Exit") Next Bar at ProfitPrice Limit;
Sell ("3L-R Stop") Next Bar at StopPrice Stop;
End;

December 2001
Formula for the Deep Pockets system found in the Trading System Lab (p. 58)

Inputs: MaxLength(5);
Variables: MarPos(0), LongLoss(0), ShortLoss(0);
If BarsSinceEntry >= (MaxLength - 2) Then
SetExitOnClose;
If MarketPosition <> 1 and Close < AvgPrice and AvgPrice < AvgPrice[5] Then Begin
If Open Tomorrow < AvgPrice Then Begin
Buy ("Long") tomorrow at AvgPrice Stop;
End;
End;
If MarketPosition <> -1 and Close > AvgPrice and AvgPrice > AvgPrice[5] Then Begin
If Open Tomorrow > AvgPrice Then Begin
SellShort ("Short") tomorrow at AvgPrice Stop;
End;
End;
MarPos = MarketPosition;
If MarPos <> MarPos[1] and MarPos = 1 Then
LongLoss = Low[1];
If MarPos <> MarPos[1] and MarPos = -1 Then
ShortLoss = High[1];
If EntryPrice > 0 Then Begin
If BarsSinceEntry >= 1 Then Begin
LongLoss = MaxList(LongLoss, Low);
ShortLoss = MinList(ShortLoss, High);
End
Else Begin
LongLoss = MaxList(LongLoss, Low);
ShortLoss = MinList(ShortLoss, High);
End;
If MarketPosition = 1 Then Begin
Sell ("LS") tomorrow at LongLoss Stop;
Sell ("LT") tomorrow at Highest(High, 5) Limit;
End;
If MarketPosition = -1 Then Begin
BuyToCover ("SS") tomorrow at ShortLoss Stop;
BuyToCover ("ST") tomorrow at Lowest(Low, 5) Limit;
End;
End;

480
January 2002
Formula for the Pair-trade system found in the Trading System Lab

Variables: LenRC(5), TradeLenRC(5), RiskCalc(0),


RC1(0), RC2(0), RC3(0), RC4(0), RC5(0), RC6(0), RC7(0), RC8(0), RC9(0), RC10(0);

RC1 = RateOfChange(Close Data1, LenRC);


RC2 = RateOfChange(Close Data2, LenRC);
RC3 = RateOfChange(Close Data3, LenRC);
RC4 = RateOfChange(Close Data4, LenRC);
RC5 = RateOfChange(Close Data5, LenRC);
RC6 = RateOfChange(Close Data6, LenRC);
RC7 = RateOfChange(Close Data7, LenRC);
RC8 = RateOfChange(Close Data8, LenRC);
RC9 = RateOfChange(Close Data9, LenRC);
RC10 = RateOfChange(Close Data10, LenRC);

If MarketPosition = 0 and RC1 = MinList(RC1,RC2,RC3,RC4,RC5,RC6,RC7,RC8,RC9,RC10)


Then Begin
Buy Next Bar at Market;
RiskCalc = AvgTrueRange(5);
End;

If MarketPosition = 0 and RC1 =


MaxList(RC1,RC2,RC3,RC4,RC5,RC6,RC7,RC8,RC9,RC10) Then Begin
Sell Next Bar at Market;
RiskCalc = AvgTrueRange(5);
End;

If BarsSinceEntry >= TradeLenRC Then Begin


ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

Formula for the True Strength Index (TSI):

TSI(close,r,s) = 100*EMA(EMA(mtm,r),s)/EMA(EMA(|mtm|,r),s)

where mtm = closetoday - closeyesterday

EMA(mtm,r) = exponential moving average of mtm with alpha = r

EMA(EMA(mtm,r),s) = exponential moving average of EMA(mtm,r) with alpha = s

|mtm| = absolute value of mtm

r = 25, s = 13

**
For MetaStock, use the Indicator Builder:

100*(Mov(Mov((CLOSE - Ref(CLOSE,-1)),25,E),13,E))/(Mov(Mov(Abs(CLOSE - Ref(CLOSE,-


1)),25,E),13,E))

For CQGNet, you first create the momentum (MTM) value, then create the TSI indicator
in the custom studies module.

Under the User Values tab create a new User Value "MTM" (Figure 2):

Close(@) - Close (@)[-1]

481
Next, under the Custom Studies tab create the new Custom Study TSI (Figure 3):

100*( MA(MA( V.mtm(@),Exp,25.000),Exp,13.000) )/( MA(MA( Abs(


V.mtm(@)),Exp,25.000),Exp,13.000) )

February 2002
Formula for the Pair-trade II system found in the Trading System Lab

Vars: Ratio(0), AvgRatio(0), RiskCalc(0);

Ratio = Close Data1 / Close Data2;

AvgRatio = XAverage(Ratio, 9);

If AvgRatio Crosses above AvgRatio[9] Then Begin


Buy at market;
RiskCalc = AvgTrueRange(9);
End;

If AvgRatio Crosses below AvgRatio[9] Then Begin


Sell at market;
RiskCalc = AvgTrueRange(9);
End;

March 2002
Formula for the system dicussed in "Putting stops to the test," by Thomas Stridsman
(p. 82):

{This code is for a ShowMe}


If High[1] < High[3] and Close[1] < Open[1] and Open < High[1] and High > High[1] Then
Plot1(High * 1.01, "");
If Low[1] > Low[3] and Close[1] > Open[1] and Open > Low[1] and Low < Low[1] Then
Plot2(Low * 0.99, "");
{End ShowMe}

{This code is for a signal}


Inputs: TestRuns(9), ExitLevels(0);
Variables: EntryTrigger(0), LongStopLoss(0), ShortStopLoss(0), ExitTrigger(0);
EntryTrigger = IntPortion(Random(2));
ExitTrigger = (ExitLevels / 5 + 0.2) / 100;
If EntryTrigger = 1 and MarketPosition = 0 Then Begin
If High < High[2] and Close < Open and Open Next Bar < High Then Begin
Buy Next Bar at High Stop;
LongStopLoss = 1 - ExitTrigger;
End;
If Low > Low[2] and Close > Open and Open Next Bar > Low Then Begin
Sell Next Bar at Low Stop;
ShortStopLoss = 1 + ExitTrigger;
End;
End;
If MarketPosition = 1 Then
ExitLong Next Bar at EntryPrice * LongStopLoss Stop;
If MarketPosition = -1 Then
ExitShort Next Bar at EntryPrice * ShortStopLoss Stop;
If BarsSinceEntry = 4 Then Begin
ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

482
Variables: NoTrades(0), MarPos(0), TrProfit(0), SumTrProfit(0), AvgTrade(0), TestString(""),
FileString("");
NoTrades = TotalTrades;
MarPos = MarketPosition;
If NoTrades > NoTrades[1] Then Begin
If MarPos[1] = 1 Then
TrProfit = (ExitPrice(1) - EntryPrice(1)) * 100 / EntryPrice(1);
If MarPos[1] = -1 Then
TrProfit = (EntryPrice(1) - ExitPrice(1)) * 100 / EntryPrice(1);
SumTrProfit = SumTrProfit + TrProfit;
End;

If LastCalcDate = Date + 1 Then Begin


AvgTrade = SumTrProfit / NoTrades;
TestString = LeftStr (GetSymbolName, 5) + "," + NumToStr(TestRuns, 0) + "," +
NumToStr(ExitTrigger*100, 2) + "," + NumToStr(AvgTrade, 2) + NewLine;
FileString = "D:\Temp\StopTest-" + RightStr(NumToStr(CurrentDate, 0), 4) + ".csv";
FileAppend(FileString, TestString);
End;
{End Signal}

April 2002
Formula for the April Trading System Lab (p. 62):

Variables: LenRC(5), TradeLenRC(5), RiskCalc(0), MMExport(1),


RC1(0), RC2(0), RC3(0), RC4(0), RC5(0), RC6(0), RC7(0), RC8(0), RC9(0), RC10(0),
TrendFilter(0);

RC1 = RateOfChange(Close Data1, LenRC);


RC2 = RateOfChange(Close Data2, LenRC);
RC3 = RateOfChange(Close Data3, LenRC);
RC4 = RateOfChange(Close Data4, LenRC);
RC5 = RateOfChange(Close Data5, LenRC);
RC6 = RateOfChange(Close Data6, LenRC);
RC7 = RateOfChange(Close Data7, LenRC);
RC8 = RateOfChange(Close Data8, LenRC);
RC9 = RateOfChange(Close Data9, LenRC);
RC10 = RateOfChange(Close Data10, LenRC);
TrendFilter = Average(Close Data11, 80);

If TrendFilter > TrendFilter[11] Then Begin


If MarketPosition = 0 and RC1 = MinList(RC1,RC2,RC3,RC4,RC5,RC6,RC7,RC8,RC9,RC10)
Then Begin
Buy Next Bar at Market;
RiskCalc = AvgTrueRange(5);
End;
If MarketPosition = 0 and RC1 =
MaxList(RC1,RC2,RC3,RC4,RC5,RC6,RC7,RC8,RC9,RC10) Then Begin
Sell Next Bar at Market;
RiskCalc = AvgTrueRange(5);
End;
End;

If TrendFilter < TrendFilter[11] Then Begin


If MarketPosition = 0 and RC1 = MinList(RC1,RC2,RC3,RC4,RC5,RC6,RC7,RC8,RC9,RC10)
Then Begin
Sell Next Bar at Market;
RiskCalc = AvgTrueRange(5);
End;
If MarketPosition = 0 and RC1 =

483
MaxList(RC1,RC2,RC3,RC4,RC5,RC6,RC7,RC8,RC9,RC10) Then Begin
Buy Next Bar at Market;
RiskCalc = AvgTrueRange(5);
End;
End;

If BarsSinceEntry >= TradeLenRC Then Begin


ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

Formula for the system dicussed in "Balancing stop size and trade length" by Thomas
Stridsman (p. 66):

Inputs: TestRuns(9), ExitLevels(0), BarsInTrade(0);


Variables: EntryTrigger(0), LongStopLoss(0), ShortStopLoss(0), ExitTrigger(0);
EntryTrigger = IntPortion(Random(2));
ExitTrigger = (ExitLevels / 5 + 0.2) / 100;
If EntryTrigger = 1 and MarketPosition = 0 Then Begin
If High < High[2] and Close < Open and Open Next Bar < High Then Begin
Buy Next Bar at High Stop;
LongStopLoss = 1 - ExitTrigger;
End;
If Low > Low[2] and Close > Open and Open Next Bar > Low Then Begin
Sell Next Bar at Low Stop;
ShortStopLoss = 1 + ExitTrigger;
End;
End;
If MarketPosition = 1 Then
ExitLong Next Bar at EntryPrice * LongStopLoss Stop;
If MarketPosition = -1 Then
ExitShort Next Bar at EntryPrice * ShortStopLoss Stop;
If BarsSinceEntry = BarsInTrade+1 Then Begin
ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

Variables: NoTrades(0), MarPos(0), TrProfit(0), SumTrProfit(0), AvgTrade(0), TestString(""),


FileString("");

NoTrades = TotalTrades;
MarPos = MarketPosition;
If NoTrades > NoTrades[1] Then Begin
If MarPos[1] = 1 Then
TrProfit = (ExitPrice(1) - EntryPrice(1)) * 100 / EntryPrice(1);
If MarPos[1] = -1 Then
TrProfit = (EntryPrice(1) - ExitPrice(1)) * 100 / EntryPrice(1);
SumTrProfit = SumTrProfit + TrProfit;
End;

If LastCalcDate = Date + 1 Then Begin


AvgTrade = SumTrProfit / NoTrades;
TestString = LeftStr(GetSymbolName, 5) + "," + NumToStr(TestRuns, 0) + "," +
NumToStr(ExitTrigger*100, 2) + "," +
NumToStr(BarsInTrade+1, 2) + "," + NumToStr(AvgTrade, 2) + NewLine;
FileString = "D:\Temp\StopTest-" + RightStr(NumToStr(CurrentDate, 0), 4) + ".csv";
FileAppend(FileString, TestString);
End;

May 2002

484
Formula for the system discussed in "Looking for a target," by Thomas Stridsman (p.
84):

Inputs: BarsInTrade(0), ProfitExit(0), LossExit(0);


Variables: EntryTrigger(0), LongStop(0), ShortStop(0), LongTarget(0), ShortTarget(0),
LimitExit(0), StopExit(0);
EntryTrigger = IntPortion(Random(2));
LimitExit = (ProfitExit / 2 + 0.5) / 100;
StopExit = (LossExit / 5 + 0.2) / 100;
If EntryTrigger = 1 and MarketPosition = 0 Then Begin
If High < High[2] and Close < Open and Open Next Bar < High Then Begin
Buy Next Bar at High Stop;
LongStop = 1 - StopExit;
LongTarget = 1 + LimitExit;
End;
If Low > Low[2] and Close > Open and Open Next Bar > Low Then Begin
Sell Next Bar at Low Stop;
ShortStop = 1 + StopExit;
ShortTarget = 1 - LimitExit;
End;
End;
If MarketPosition = 1 Then Begin
ExitLong Next Bar at EntryPrice * LongStop Stop;
ExitLong Next Bar at EntryPrice * LongTarget Limit;
End;
If MarketPosition = -1 Then Begin
ExitShort Next Bar at EntryPrice * ShortStop Stop;
ExitShort Next Bar at EntryPrice * ShortTarget Limit;
End;
If BarsSinceEntry = BarsInTrade+1 Then Begin
ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

Variables: NoTrades(0), MarPos(0), TrProfit(0), SumTrProfit(0), AvgTrade(0), TestString(""),


FileString("");

NoTrades = TotalTrades;
MarPos = MarketPosition;
If NoTrades > NoTrades[1] Then Begin
If MarPos[1] = 1 Then
TrProfit = (ExitPrice(1) - EntryPrice(1)) * 100 / EntryPrice(1);
If MarPos[1] = -1 Then
TrProfit = (EntryPrice(1) - ExitPrice(1)) * 100 / EntryPrice(1);
SumTrProfit = SumTrProfit + TrProfit;
End;

If LastCalcDate = Date + 2 Then Begin


AvgTrade = SumTrProfit / NoTrades;
TestString = LeftStr(GetSymbolName, 5) + "," + NumToStr(BarsInTrade+1, 2) + "," +
NumToStr(LimitExit*100, 2) + "," +
NumToStr(StopExit*100, 2) + "," + NumToStr(AvgTrade, 2) + NewLine;
FileString = "D:\Temp\StopTest-" + RightStr(NumToStr(CurrentDate, 0), 4) + ".csv";
FileAppend(FileString, TestString);
End;

Formula for the May Trading System Lab (p. 70):

{Three black candle sticks for entry:}


If High < High[1] and High [1] < High[2] and High[2] < High[3] and

485
Close < Open and Close[1] < Open[1] and Close[2] < Open[2] Then
Buy Tomorrow at High Stop;

{Trailing stop:}
ExitLong Tomorrow at Low Stop;

{Profit taking Gap higher:}


If MarketPosition <> 0 and Open Tomorrow > High Then
ExitLong Tomorrow at Open;

{ Retracement bar:}
If High > High[1] and Close < Close[1] Then
SetExitOnClose;

MetaStock formula for the StochRSI (p. 52):

(Sum(RSI(5)-LLV(RSI(5),3),3)/Sum(HHV(RSI(5),3)-LLV(RSI(5),3),3))*100

June 2002

Formula for the June Trading System Lab (p. 70):

Inputs: BarsInTrade(8), ProfitExit(8), LossExit(4);


Variables: LongStop(0), ShortStop(0), LongTarget(0), ShortTarget(0), LimitExit(0),
StopExit(0);
LimitExit = (ProfitExit / 2 + 0.5) / 100;
StopExit = (LossExit / 5 + 0.2) / 100;
If MarketPosition = 0 Then Begin
If High < High[2] and Close < Open and Open Next Bar < High Then Begin
Buy Next Bar at High Stop;
LongStop = 1 - StopExit;
LongTarget = 1 + LimitExit;
End;
If Low > Low[2] and Close > Open and Open Next Bar > Low Then Begin
Sell Next Bar at Low Stop;
ShortStop = 1 + StopExit;
ShortTarget = 1 - LimitExit;
End;
End;
If MarketPosition = 1 Then Begin
ExitLong Next Bar at EntryPrice * LongStop Stop;
ExitLong Next Bar at EntryPrice * LongTarget Limit;
End;
If MarketPosition = -1 Then Begin
ExitShort Next Bar at EntryPrice * ShortStop Stop;
ExitShort Next Bar at EntryPrice * ShortTarget Limit;
End;
If BarsSinceEntry = BarsInTrade+1 Then Begin
ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

Formula from "Simple but Effective" by Michael Harris (p. 64)

T-Bond C-6 PATTERN


MetaStock Code

{Long positions only, profit target = 1 point, stop-loss = 1 point, entry at the open of next day}

486
(Ref(c,-5)>Ref(c,-4)) and (Ref(c,-4)>Ref(c,-3)) and (Ref(c,-3)>Ref(c,-2)) and (Ref(c,-
2)>Ref(c,0)) and Ref(c,0)>Ref(c,-1))

EasyLanguage Code (2000i)

input:targetpoints(0), stoppoints(0), multiplier(1);


variables: profitprice(0), stopprice(0);
If c[5]>c[4] and c[4]>c[3] and c[3]>c[2] and c[2]>c[0] and c[0]>c[1] then begin
Buy next bar on the open;
If marketposition = 0 then begin
exitlong next bar at open of tomorrow+ (targetpoints * multiplier) points limit;
exitlong next bar at open of tomorrow- (stoppoints * multiplier) points stop;
end;
end:
if marketposition = 1 then begin
profitprice = entryprice + (targetpoints * multiplier) points;
stopprice = entryprice - (stoppoints * multiplier) points;
exitlong at profitprice limit;
exitlong at stopprice stop:
end;

S&P 500 C-6 PATTERN


MetaStock Code

{Long positions only, profit target = 3%, stop-loss = 3% (of entry price), entry at the open of
next day}

(Ref(c,0)>Ref(c,-2)) and (Ref(c,-2)>Ref(c,-1)) and (Ref(c,-1)>Ref(c,-3)) and (Ref(c,-3)>Ref(c,-


4)) and Ref(c,-4)>Ref(c,-5))

EasyLanguage Code (2000i)

input:ptarget(0), stop1(0);
variables: profitprice(0), stopprice(0);
If c[0]>c[2] and c[2]>c[1] and c[1]>c[3] and c[3]>c[4] and c[4]>c[5] then begin
Buy next bar on the open;
If marketposition = 0 then begin
exitlong next bar at open of tomorrow * (1 + ptarget/100) limit;
exitlong next bar at open of tomorrow * (1 - stop1/100) stop;
end;
end:
if marketposition = 1 then begin
profitprice = entryprice * (1 + ptarget/100) points;
stopprice = entryprice * (1 - stop1/100) points;
exitlong at profitprice limit;
exitlong at stopprice stop:
end;

MSFT C-6 PATTERN


MetaStock Code

{Long positions only, profit target = 10%, stop-loss = 10% (of entry price), entry at the open of
next day}

(Ref(c,-1)>Ref(c,0)) and (Ref(c,0)>Ref(c,-2)) and (Ref(c,-2)>Ref(c,-3)) and (Ref(c,-3)>Ref(c,-


4)) and Ref(c,-4)>Ref(c,-5))

EasyLanguage Code (2000i)

487
input:ptarget(0), stop1(0);
variables: profitprice(0), stopprice(0);
If c[1]>c[0] and c[0]>c[2] and c[2]>c[3] and c[3]>c[4] and c[4]>c[5] then begin
Buy next bar on the open;
If marketposition = 0 then begin
exitlong next bar at open of tomorrow * (1 + ptarget/100) limit;
exitlong next bar at open of tomorrow * (1 - stop1/100) stop;
end;
end:
if marketposition = 1 then begin
profitprice = entryprice * (1 + ptarget/100) points;
stopprice = entryprice * (1 - stop1/100) points;
exitlong at profitprice limit;
exitlong at stopprice stop:
end;

Programming code from "Happy Trails" by Thomas Stridsman (p. 76)

The EntryTrigger at the top of the code ensures that each signal will be traded at random so
that every trading sequence will be unique. The bottom part of the code exports the
necessary data for further analysis in Excel. Note: If you use the system in live trading, you
need to get rid of the EntryTrigger variable.

Inputs: BarsInTrade(0), ProfitExit(0), LossExit(0);


Variables: EntryTrigger(0), LongStop(0), ShortStop(0), LongTarget(0), ShortTarget(0),
LimitExit(0), StopExit(0), Top(0), Bottom(0);
EntryTrigger = IntPortion(Random(2));
LimitExit = (ProfitExit / 2 + 0.5) / 100;
StopExit = (LossExit / 5 + 0.2) / 100;
If EntryTrigger = 1 and MarketPosition = 0 Then Begin
If High < High[2] and Close < Open and Open Next Bar < High Then Begin
Buy Next Bar at High Stop;
Top = High;
LongStop = 1 - StopExit;
LongTarget = 1 + LimitExit;
End;
If Low > Low[2] and Close > Open and Open Next Bar > Low Then Begin
Sell Next Bar at Low Stop;
Bottom = Low;
ShortStop = 1 + StopExit;
ShortTarget = 1 - LimitExit;
End;
End;
If MarketPosition = 1 Then Begin
Top = MaxList(Top, High);
ExitLong Next Bar at Top * LongStop Stop;
ExitLong Next Bar at EntryPrice * LongTarget Limit;
End;
If MarketPosition = -1 Then Begin
Bottom = MinList(Bottom, Low);
ExitShort Next Bar at Bottom * ShortStop Stop;
ExitShort Next Bar at EntryPrice * ShortTarget Limit;
End;
If BarsSinceEntry = BarsInTrade+1 Then Begin
ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

Variables: NoTrades(0), MarPos(0), TrProfit(0), SumTrProfit(0), AvgTrade(0), TestString(""),


FileString("");

488
NoTrades = TotalTrades;
MarPos = MarketPosition;
If NoTrades > NoTrades[1] Then Begin
If MarPos[1] = 1 Then
TrProfit = (ExitPrice(1) - EntryPrice(1)) * 100 / EntryPrice(1);
If MarPos[1] = -1 Then
TrProfit = (EntryPrice(1) - ExitPrice(1)) * 100 / EntryPrice(1);
SumTrProfit = SumTrProfit + TrProfit;
End;

If LastCalcDate = Date + 2 Then Begin


AvgTrade = SumTrProfit / NoTrades;
TestString = LeftStr(GetSymbolName, 5) + "," + NumToStr(BarsInTrade+1, 2) + "," +
NumToStr(LimitExit*100, 2) + "," +
NumToStr(StopExit*100, 2) + "," + NumToStr(AvgTrade, 2) + NewLine;
FileString = "D:\Temp\StopTest-" + RightStr(NumToStr(CurrentDate, 0), 4) + ".csv";
FileAppend(FileString, TestString);
End;

July 2002

Formula for the July Trading System Lab (p. 70):

Variables: RiskCalc(0);

If MarketPosition <> 1 and Average(Close, 9) Crosses above Average(Close, 36) Then Begin
RiskCalc = 4 * AvgTrueRange(10);
Buy Next Bar at Market;
End;

If Average(Close, 9) Crosses below Average(Close, 36) Then


ExitLong Next Bar at Market;

If MarketPosition = 1 and EntryPrice > 0 Then


ExitLong Next Bar at EntryPrice - RiskCalc Stop;

August 2002

Formula for the July Trading System Lab (p. 70):

If MarketPosition <> -1 Then


Sell Next Bar at Close[1] + 2 * AvgTrueRange(5) limit;
If MarketPosition <> 1 Then
Buy Next Bar Close[1] - 2 * AvgTrueRange(5) limit;
If MarketPosition = 1 Then Begin
ExitLong Next Bar at EntryPrice - AvgTrueRange(5) Stop;
ExitLong Next Bar at EntryPrice + 2 * AvgTrueRange(5) Limit;
End;
If MarketPosition = -1 Then Begin
ExitShort Next Bar at EntryPrice + AvgTrueRange(5) Stop;
ExitShort Next Bar at EntryPrice - 2 * AvgTrueRange(5) Limit;

End;

ROSS CONGESTION PAINTBAR.

489
Inputs:Option(1);
Vars:x(0),Counter(0),BarBack(0),Str("");

Counter=0;
For x=0 to 3 begin
If Option<=1 Or Option>3 then begin
{Refer the closes in
the condition}
If (C[x]>=L[BarBack]) and (C[x]<=H[BarBack]) then
Counter=Counter+1;
end;
If Option=2 then begin
{Refer the opens in the
condition}
If (O[x]>=L[BarBack]) and (O[x]<=H[BarBack]) then
Counter=Counter+1;
end;
If Option=3 then begin
{Refer both in the condition}
If (C[x]>=L[BarBack]) and (C[x]<=H[BarBack]) and
(O[x]>=L[BarBack])
and (O[x]<=H[BarBack]) then Counter=Counter+1;
end;
end;
If Counter=4 then begin {If the condition is
true
plot the congestion
bars}
For x=0 to 3 begin
Plot1[x](H[x],"H");
Plot2[x](L[x],"L");
end;
end;
If Counter=4 then Barback=BarBack+1 else BarBack=4;

{If the condition is true use the engulfing bar as reference}

NARROW RANGE 4 (NR4) DAYS

A Narrow Range 4 day occurs when the range of today's prices (the high minus the
low) is the smallest range of the past four days. A Narrow Range 4 day appears as
follows:

490
As you can see, the price range (high - low) of the most recent day on the right is
smaller than the price range of the previous three days.
Unlike some of the other patterns discussed here, the Narrow Range 4 day occurs with
moderate frequency. Here is a chart of November 2001 soybeans, with each Narrow
Range 4 Day colored in red and marked by an upward pointing arrow beneath the bar.

Similar to an Inside Day, the Narrow Range 4 day signals a period of reduced price
volatility that may be the prelude to a significant price move in the market. When an
NR4 day occurs, traders should position themselves to trade in the direction of a price
breakout

NARROW RANGE 7 (NR7) DAYS

A Narrow Range 7 day occurs when the range of today's prices (the high minus the
low) is the smallest range of the most recent seven days. A Narrow Range 7 day
appears as follows:

491
As you can see, the price range (high - low) of the most recent day on the right is
smaller than the price range of all the other price bars.
Here is a chart of November 2001 soybeans, with each Narrow Range 7 Day colored
in red and marked by an upward pointing arrow beneath the bar.

Similar to an Inside Day, the Narrow Range 7 day signals a period of reduced price
volatility that may be the prelude to a significant price move in the market. When an
NR7 day occurs, traders should position themselves to trade in the direction of a price
breakout.

HISTORICAL VOLATILITY

Just as markets will trade higher or lower in price, markets also enter periods of
increased or reduced volatility. This relative volatility of the market can be used as an
indicator of future market expansion or contraction. When the market enters into a
period of contraction, prices don't move significantly, the overall range is low and
volatility is reduced. Periods of contraction invariably lead to periods of price
expansion, when price moves in a defined price trend and changes in price are
substantial.
One way of identifying periods of market expansion and contraction is by calculating
a ratio of recent volatility over long term volatility, and then forecasting a period of
market expansion when the short-range volatility drops below 50% of the long-range
volatility. The chart below of the Eurodollar market shows the ratio of 10 day
historical volatility to 100 day historical volatility. When this ratio (marked in red on
the chart) crosses below the 50% threshold (marked in green), the market has entered

492
into a short-term period of significant contraction. Traders may anticipate that the
market is about to expand significantly and enter into a pronounced price trend, so the
traders can plan accordingly.

As you can see from the chart above, in the middle of June, the ratio of 10 day
historical volatility to 100 day historical volatility dropped below 50% (the green
line). It persisted there for about ten market days, and then exploded higher, as the
Eurodollar market dropped significantly.

BOLLINGER BANDS
Standard Deviation or Bollinger Bands are price bands that are used to monitor trends
in prices as well as overall market volatility. The upper Bollinger band represents a
fixed number of standard deviations above the average, and the lower Bollinger band
represents a fixed number of standard deviations below the average. By using
standard deviations rather than a fixed percentage, the bands adjust for volatility.
During volatile periods, the bands move further away from the average, while during
market lulls, the bands move closer to the average.
For those who don't recall high school statistics, the Standard Deviation is a measure
of how widely values are dispersed from the average value (the mean). The
calculation for standard deviation is:

Bollinger bands are usually included in most charting software. Here is a chart of
November 2001 soybeans, with the 20 day Bollinger bands colored in red with a 20
day moving average colored in green.

493
The area between the higher and lower Bollinger bands is the area in which prices
should trade most frequently. Consequently, when price hits either the higher or lower
Bollinger band, it tends to reverse direction and go to the other Bollinger Band,
especially if the Bollinger bands themselves do not appear to reflect a major trend
(they are flat or sideways). Bollinger bands can also be used to identify periods of
market contraction and reduced volatility. When the higher and lower Bollinger bands
are very close together, traders should be ready for market action that boosts volatility
back to average levels - i.e., some kind of significant price move is about to take
place.

OUTSIDE DAY, NR4 AND MOVING AVERAGE


The combination of an NR4 day followed by an Outside Day that penetrates the
moving average following a pullback from the long-term trend can represent an
excellent short-term trading opportunity. Let's look at an example from the Canadian
Dollar market:

494
At the point marked #1, we see that although both the Bollinger Bands and the
Moving Averages have been moving higher, the market has moved lower on a short-
term basis, closing below the 20 day moving average (marked in blue). The
subsequent day is an NR4 day. The third day opens below the low of the NR4 day but
immediately begins trading higher.
In anticipation of an Outside Day formation, traders could have bought the market
while protecting themselves by placing their stop loss order at the low of the day. As
markets traded higher and penetrated the 20 day moving average, the opportunity for
a rebound has grown stronger. Traders could have added to their long positions the
following day as the market traded above the high of the outside day, again while
maintaining their stop loss at the low of the Outside Day.

NR7, INSIDE DAY AND BOLLINGER BAND


Following a pronounced price move in the markets, the emergence of an NR7 day can
signify that the market is pausing before making a significant price move. The
following example from the Canadian Dollar market shows:

As prices move up towards the upper Bollinger Band (marked in red, point #1), the
market experiences a day of consolidation that is both an Inside Day and an NR7 day.
At this point, traders should expect a significant price breakout. In this case, the next
day traded lower and although the long-term trend was higher, the confluence of these
two patterns offered the opportunity for a trade with lower risk as the stop-loss order
could have been placed just above the high of the NR7 day.

One of the most compelling features of the Trader's Toolbox is the fact that it can
identify a wide range of trading setups in a given market. In the following example,
we explore a number of trade setups that occurred in the November 2001 Soybean
market.

495
Trade Setup #1
Following a period when the upper and lower Bollinger Bands became extremely
close to one another, the soybean market gapped lower in price towards the end of
December 2000. Soon after the gap move, the market had an inside day (marked by
the yellow #1). Following the pattern interpretation described in the Toolbox, traders
could seek to get short in the direction of the prevailing trend the following day by
placing a sell stop at a tick below the low of the inside day and a protective buy stop
at a tick above the high of the inside day. The trade would be filled that day, as the
market proceeded to trade lower throughout the day.
When it comes to managing the trade, the protective buy stop could be maintained at a
tick above the high of the inside day for three days at which time the trader could re-
assess the trading situation. At that time, the trader may wish to take off part of the
trading position (if multiple contracts were used), adjust their protective buy stop
lower to protect some of their open profits or exit the position all together. It's
important to note, however, that with this type of setup, the trade is allowed to run for
three days before the trader seeks to exit with profits. Of course, the trade could be
stopped out at any time should the market reverse action. There is one caveat to this
"three day rule" - should the lower Bollinger Band be pointing at an angle that is 45
degrees or more - that is, a very steep angle, the trader might wait FIVE DAYS before
re-assessing the trade, moving up stops or taking profits. This is because the market
has entered into a pronounced trend move and may continue moving lower for an
extended period of time.
The market continued to hug the lower Bollinger band for about two and a half weeks
before entering into a consolidation phase (signified by the yellow #2). The market
then experienced an Outside Day that closed higher. Given the sharp decline
experienced in the previous weeks, this could be used as the signal to exit the trade
and lock in profits.

496
Trade Setup #2
On the second day following the Outside Day that had prompted an exit from the first
trade setup, the market puts in another Inside Day (marked in yellow #3). Again, like
the first trade, a sell stop is placed one tick below the low of the Inside Day while a
protective buy stop is placed above the high of the Inside Day (note that we're only
looking to sell here, not buy, since the longer-term trend of the market is obviously
lower). We are filled on the final day and maintain our protective stop order at one
tick above the high of the Insiday Day for three days at which time we re-appraise the
situation (marked in yellow, #4). The trader could decide to exit the trade completely,
move their protective stop lower in order to lock in some profits or exit the position
partially.

Trade Setup #4
As the market rebounds from its latest downmove, it begins to approach the 20 period
moving average. As the market has been moving in a pronounced downtrend for the
past month, traders could look for this opportunity to get short the market as
oftentimes the price will approach the moving average but not penetrate, instead
continuing downward to the lower Bollinger band in a continuation of the downtrend.

497
At the point marked #5 in yellow, the market attempted to trade higher than the
moving average but failed to hit it, instead turning downward and forming an Outside
Day in the process. Traders could have gotten short at the low of the previous day in
anticipation of this reversal, placing a protective buy stop just above the high of the
day. As the market continued lower, the trader should wait for the third day to re-
appraise the trade: deciding either to move their stops, take partial profits or get out of
the trade all together. Note that since the lower Bollinger Band is NOT demonstrating
a sharp decline (in fact, it's pointing up a little bit), you would wait only THREE
DAYS and not FIVE DAYS to re-appraise the situation.

Trade Setup #4
At the point marked in yellow, #7, we have an Outside Day where the market opened
above the high of the previous day but then traded lower below the low fo the
previous day. This bearish formation should have been traded on the short side, with
the trade being entered at a tick below the low of the previous day with the protective
stop at the high of the Outside Day.
Unfortunately, two days after entering this trade, the market gapped higher, stopping
out the trade at a loss.

498
Trade Setup #5
At point #9 marked in yellow, the market puts in another Inside Day. Again, to
position ourselves, we place a buy stop above the high of the Insiday Day and a
protective sell stop below the low of the Inside Day. Because the market is trading
above the 20 day moving average (in blue), we are willing to take a buy signal
whereas earlier, when the market was trading below the 20 day moving average, we
would be more reluctant to do so.
The next is an Outside Day and the buy signal is taken while the sell stop is
maintained as a protective measure. The market trades higher over the next couple of
days. After three days, the trader can re-assess whether to maintain the position, move
up the protective stop, or exit the position partially.

The Powertool strategy


Like any other craft, trading requires the right tool(s) for the job. In this case,
combining a simple trend indicator with a bull/bear momentum calculation
creates an excellent timing tool for short-term traders.
By THOMAS A. BIEROVIC

Many winning trading strategies rely on two technical indicators — one to determine a
market’s underlying trend and another to time a trade. The Powertool strategy is a good
example: It uses Joseph Stowell’s three-bar net line as the trend indicator and Dr. Alexander
Elder’s bull power/bear power as the timing indicator.

Together, the two indicators create synergy — i.e., a whole greater than the sum of its parts:
Trading with the three-bar net line is more precise when trades are timed with bull power/bear
power; and trading with bull power/bear power is more consistent when trades are taken in
the direction of the three-bar net line.

STOWELL’S THREE-BAR NET LINE


To draw a three-bar net line (see Figures 1 and 2, below) when price has been rising recently,
first find the highest high for the current upswing and label it bar 1. Next, look to the left and

499
find the most recent low that is lower than the low of bar 1 and label it bar 2. Finally, look left
again and find the most recent low that is lower than the low of bar 2 and label it bar 3. The
three-bar net line is a horizontal line extending right from bar 3’s low. The trend is up until
price closes below the current three-bar net line.

The process is inverted for drawing a three-bar net line when prices have been falling (see
Figures 1 and 3, below). Bar 1 is the lowest low of the downswing. Look to the left: The most
recent high that is higher than the high of bar 1 is bar 2. Look left again: The most recent high
that is higher than the high of bar two is bar 3. Now, draw the three-bar net line to the right

500
across the chart from the high of bar 3. The trend is down until price closes above the current
three-bar net line.

One note: Inside bars (those with lower highs and higher lows than the bars preceding them)
don’t count, so just skip over them.

Bull power/bear power indicators

Dr. Elder’s bull power measures the bulls’ ability to pull price higher; his bear power measures
the bears’ ability to push price lower.

Bull power is the current price bar’s high minus a 13-bar exponential moving average (EMA)
of closing prices. Bear power is the current price bar’s low minus the 13-bar EMA.

The logic behind bull power/bear power is that the price high represents the maximum power
of bulls, the price low represents the maximum power of bears, and the EMA represents, in
Dr. Elder’s words, the “average consensus of value.” The distance between the high and the
EMA defines bull power, while the distance between the low and the EMA defines bear power
(see Figure 4, below).

501
Bull power and bear power are plotted as separate histograms below a bar chart (see Figure
5, below).

Interpreting bull power/bear power

In a neutral (sideways) market, bull power is usually above zero (i.e., the high is above the
EMA), and bear power is usually below zero (i.e., the low is below the EMA.) In an uptrend,
however, both bull and bear power are frequently above zero (the high and low are both
above the EMA). In a downtrend, both bull and bear power are frequently below zero (the
high and low are both below the EMA). Figure 5 illustrates this.

502
You probably won’t want to buy a market when price has already climbed so steeply that the
low is above the EMA, or sell it short when it has already declined so sharply that the high is
below the EMA.

Instead, when price is in an uptrend, wait for bear power to cross below zero (e.g., for the low
to fall below the EMA) to avoid buying when the market is overbought. Then wait for bear
power to tick up (to be greater than it was yesterday), which indicates the countertrend
decline has lost its downward momentum. With that setup in effect, place an order to buy
above the previous price bar’s high.

Similarly, in a downtrend, wait for bull power to cross above zero (e.g., for the high to rise
above the EMA) so you won’t be selling short when the market is oversold. Then wait for bull
power to tick down (to be less than it was yesterday), suggesting the countertrend rally has
run its course. With the setup in effect, place an order to sell short below the previous price
bar’s low.

Traders use oscillators such as rate-of-change (ROC), the relative strength index (RSI) and
stochastics to identify exhaustion points in a market. These indicators typically fluctuate
above and below a neutral axis (hence the name oscillator) as the market swings, with high
oscillator values reflecting overbought conditions and low oscillator values reflecting oversold
conditions.

Oscillators are most effective in trading ranges. If the range of values for an oscillator is
between zero and 100 (as is the case for the RSI), overbought is typically (i.e., for a default
14-bar indicator) defined as 70 or higher while oversold is 30 or lower. If the market is moving
sideways, these levels often correspond closely to swing highs and lows and provide
excellent trade points.

However, if the market is trending, the oscillator values will shift, reflecting the power of the
trend. During an uptrend, oscillator values are usually skewed to the upside and often never
reach oversold levels; similarly, during downtrends, oscillators are pushed to the downside
and may not reach their overbought levels. For example, in a strong downtrend, the
overbought level may be closer to 55 and the oversold level closer to 15

Figure 1 (below) is a daily chart with a five-day RSI. Notice that during the downtrend the RSI
values are persistently near the oversold level of 30 and never reach the overbought level of
70. Similarly, when the stock was trending up, the RSI never dropped to the oversold level of
30. Ultimately, had you been waiting for the oscillator to indicate an overbought reading in the
downtrend (which would have given a sell signal), or an oversold reading during the uptrend
(generating a buy signal), you would have missed out.

503
Despite these drawbacks, it is nevertheless apparent the RSI tended to behave in an orderly
manner relative to the trend. The shorter-term swings were still reflected in the RSI and there
were somewhat identifiable oversold-overbought ranges during the downtrend (approximately
20-45) and the uptrend (approximately 45-85); the range simply shifted up while Microsoft
was in the uptrend.

What is necessary is a tool that will reflect relative overbought and oversold levels by
adapting to trend changes such as the one in Figure 1. The Stochastic RSI (StochRSI), which
was developed by Tushar Chande, combines elements of the stochastic oscillator and the
RSI to create an indicator that captures price turns more effectively in different market
conditions.

Formula for the system discussed in "Looking for a target," by Thomas Stridsman (p.
84):

Inputs: BarsInTrade(0), ProfitExit(0), LossExit(0);


Variables: EntryTrigger(0), LongStop(0), ShortStop(0), LongTarget(0), ShortTarget(0),
LimitExit(0), StopExit(0);
EntryTrigger = IntPortion(Random(2));
LimitExit = (ProfitExit / 2 + 0.5) / 100;
StopExit = (LossExit / 5 + 0.2) / 100;
If EntryTrigger = 1 and MarketPosition = 0 Then Begin
If High < High[2] and Close < Open and Open Next Bar < High Then Begin
Buy Next Bar at High Stop;
LongStop = 1 - StopExit;
LongTarget = 1 + LimitExit;
End;
If Low > Low[2] and Close > Open and Open Next Bar > Low Then Begin
Sell Next Bar at Low Stop;
ShortStop = 1 + StopExit;
ShortTarget = 1 - LimitExit;
End;
End;
If MarketPosition = 1 Then Begin
ExitLong Next Bar at EntryPrice * LongStop Stop;
ExitLong Next Bar at EntryPrice * LongTarget Limit;
End;
If MarketPosition = -1 Then Begin
ExitShort Next Bar at EntryPrice * ShortStop Stop;
ExitShort Next Bar at EntryPrice * ShortTarget Limit;
End;
If BarsSinceEntry = BarsInTrade+1 Then Begin
ExitLong Next Bar at Market;
ExitShort Next Bar at Market;
End;

Variables: NoTrades(0), MarPos(0), TrProfit(0), SumTrProfit(0), AvgTrade(0), TestString(""),


FileString("");

NoTrades = TotalTrades;
MarPos = MarketPosition;
If NoTrades > NoTrades[1] Then Begin
If MarPos[1] = 1 Then
TrProfit = (ExitPrice(1) - EntryPrice(1)) * 100 / EntryPrice(1);
If MarPos[1] = -1 Then
TrProfit = (EntryPrice(1) - ExitPrice(1)) * 100 / EntryPrice(1);
SumTrProfit = SumTrProfit + TrProfit;
End;

If LastCalcDate = Date + 2 Then Begin


AvgTrade = SumTrProfit / NoTrades;

504
TestString = LeftStr(GetSymbolName, 5) + "," + NumToStr(BarsInTrade+1, 2) + "," +
NumToStr(LimitExit*100, 2) + "," +
NumToStr(StopExit*100, 2) + "," + NumToStr(AvgTrade, 2) + NewLine;
FileString = "D:\Temp\StopTest-" + RightStr(NumToStr(CurrentDate, 0), 4) + ".csv";
FileAppend(FileString, TestString);
End;

Formula for the May Trading System Lab (p. 70):

{Three black candle sticks for entry:}


If High < High[1] and High [1] < High[2] and High[2] < High[3] and
Close < Open and Close[1] < Open[1] and Close[2] < Open[2] Then
Buy Tomorrow at High Stop;

{Trailing stop:}
ExitLong Tomorrow at Low Stop;

{Profit taking Gap higher:}


If MarketPosition <> 0 and Open Tomorrow > High Then
ExitLong Tomorrow at Open;

{ Retracement bar:}
If High > High[1] and Close < Close[1] Then
SetExitOnClose;

MetaStock formula for the StochRSI (p. 52):

( Sum(RSI(5)-LLV(RSI(5),3),3)/Sum(HHV(RSI(5),3)-LLV(RSI(5),3),3) )
NONLINEAR EHLERS FILTER

Type :
Indicator,
Name :
Nonlinear
Ehlers
Filter

Inputs: Price((H+L)/2), Length(15);


Vars: count(0), SumCoef(0), Num(0),
Filt(0);
Array: Coef[25](0);

{Coefficients can be computed using any


statistic of choice ----
---- a five-bar momentum is used as an
example}

For count = 0 to Length - 1 begin


Coef[count] = AbsValue(Price[count]
- Price[Count + 5]);
{The line above is all that needs to be

505
changed to use other statistics.
For example:
Coef[count]=AbsValue(Price[count]-
Filt[count+1]);}
end;

{Sum across the numerator and across all


coefficients}
Num = 0;
SumCoef =0;

For count = 0 to Length -1 begin


Num = Num +
Coef[count]*Price[count];
SumCoef = SumCoef + Coef[count];
end;

Filt = Num / SumCoef;

Plot1(Filt, "Ehlers");

506
This exemplary filter has 15 coefficients ["Length(15)"], although the array of coefficients is dimension
experimentation using a longer filter. If you want a filter longer than 25, the dimension of the Coef arra

In the first calculation, you find each coefficient in the filter as the five-bar momentum. The next comp
as the product of each coefficient and the price (the x's in the general equation) at each corresponding s
alone. Finally, the filter is completed by taking the ratio of the numerator to the coefficient sum. The pe
2 in the article.

If you'd rather use a spreadsheet, an example done in Microsoft Excel is shown in Figure 1.

FIGURE 1: EXCEL SPREADSHEET. Starting from the prices on the left, here is a way to compute a n
momentum as the embedded filter.

--John Ehlers

The EasyLanguage for both the function and indicator will be available for download at www.tradestat
"EhlersFilter.ELS."

-- Ramesh Dhingra, Product Manager, EasyLanguage

TradeStation Technologies, Inc. (formerly Omega Research, Inc.)

507
A wholly owned subsidiary of TradeStation Group, Inc.
http://www.TradeStation.com

Znalezione na/w/od:
http://www.traders.com

NEW MARKET PARADIGM SYSTEM

Home

New Ma
To implement the strategie
generate studies and system
indicators, paintbars and sy
standard deviation function

Default Settings For NMP


Function Name: NewMar
Output: Numeric

Input: Price(NumericSe
value1 = BollingerBand
value2 = BollingerBand
Condition1 = value1 <
-WD}
Condition2 = value1 >
Condition3 = Condition
IF Condition1 then New
IF Condition2 then New
IF Condition3 then New

New market paradigm sy

This system will eventually


phases, or plug in existing
Setting Defaults for NMP s

Name: NMP SYSTEM


Stops: None
Properties: Check "Allow

Input: Price(close),Le
Vars: NmpC(0),NmpE(0)
{*1.}
If NewMarketParadigm(P

508
Else NmpC = 0; {Contra
If NewMarketParadigm(P
Else NmpE = 0; {Expans
If NewMarketParadigm(P
Else NmpT = 0; {Transi
use it. No Counter is
{*2.}
Condition1 = NmpE > 1
If Condition1 then beg
Trigger = 1;
End;
{*3.}
If Trigger = 1 then be
Buy Highest(High,10) +
Sell Lowest(Low,10) -
End;

Notes to the code


1. First, write a set of
been added to the c
occurrences. Use th
2. Next, establish the

509
3. The following code
changing this to a c
initial testing phase
into the market at th
The original CIS bow-tie/
Setting Defaults for NMP
Name: NMP SYSTEM 2
Stops: None
Properties: Check "Do n

Input: Price(close),Le
value1 = StdDev(Price
If value1 = Lowest(val
If SlowD(Length) > 75
IncludeSystem: "Parabo
End;
End;

-- Walt Downs, Internet: ht

Znalezione na/w/od:
http://www.traders.com

Home ______________________

BETTER BOLLINGER BANDS BY DENNIS MCNICHOLL

Better Bollinger Bands by


Dennis McNicholl
(Futures 10/98)

Type : Indicator, Name : Better Bollinger Bands

{Denvelope Indicator}

inputs:
lookback(20),
mult(2);

510
vars:
alpha(0),
mt(0),
ut(0),
dt(0),
mt2(0),
ut2(0),
dt2(0),
but(0),
blt(0);

alpha = 2 / (lookback + 1);


mt = alpha * close + (1 - alpha) * mt;
ut = alpha * mt + (1 - alpha) * ut;
dt = ((2 - alpha) * mt - ut) / (1 - alpha);
mt2 = alpha * absvalue(close - dt) + (1 - alpha) * mt2;
ut2 = alpha * mt2 + (1 - alpha) * ut2;
dt2 = ((2 - alpha) * mt2 - ut2) / (1 - alpha);
but = dt + mult * dt2;
blt = dt - mult * dt2;
plot1(dt,"CenterB");
plot2(but,"UpperB");
plot3(blt,"LowerB");

511
Copyright © 2001 Empire Systems Design [ 03.06.01 04:12 PM ]

Znalezione na/w/od:
http://www.empire-systems.com

Home _____________________________________________________________________________

KLINGER VOLUME OSCILLATOR

Klinger
Volume
Oscillator
by
Stephen
Klinger
In "Identifying trends with volume analysis" in this issue, Stephen Kling
using volume. The TradeStation Traders' Tip this month is based on the v
presented in the article. For TradeStation and SuperCharts, we'll call the
indicator can plot both the short-term and long-term versions of the oscil

The indicator uses a total of four inputs: FastX determines the length of t
moving average of the volume force; SlowX determines the length of the
moving average of the volume force; Trigger determines the length of th
used to smooth the KVO line; and Smooth determines the amount of smo
lines using a summation of the values. The Smooth input allows for the g
for longer-term analysis. If the Smooth input is set to 1 or zero, no smoot

The process of developing this indicator begins with the creation of two f
These two functions basically provide supporting calculations, which wil
be easily referenced from other custom studies. The two functions should
presented below, using their assigned names.

Type: Function, Name: VForce

512
Vars: TSum(0), Trend(0), DM(0), CM(0);

TSum = High + Low + Close;


IF TSum > TSum[1] Then

Trend = 1
Else
Trend = -1;
IF Trend = Trend[1] Then
CM = CM + Range
Else
CM = Range + Range[1];
IF CM <> 0 Then
VForce = Volume * AbsValue(2 * (DM/CM) -1) * Trend * 100;

Type: Function, Name: KVO

Inputs:
FastX(Numeric),
SlowX(Numeric);

Vars:
FXAvg(0),
SXAvg(0);

FXAvg = XAverage(VForce, FastX);


SXAvg = XAverage(VForce, SlowX);
KVO = FXAvg - SXAvg;

Once the two functions have been created and verified, the indicator can
should be scaled to "screen."

Type: Indicator, Name: Klinger Volume Oscillator

Inputs:
FastX(34),
SlowX(55),
TrigLen(13),
Smooth(1);

Vars:
Trigger(0);

Trigger = XAverage(KVO(FastX, SlowX), TrigLen);

IF Smooth <= 1 Then Begin


Plot1(KVO(FastX, SlowX), "KVO");
Plot2(Trigger, "KVO Trigger");
End Else Begin

Plot1(Summation(KVO(FastX, SlowX), Smooth), "KVO");


Plot2(Summation(Trigger, Smooth), "KVO Trigger");
End;

513
Plot3(0, "Zero");
IF Plot1 Crosses Above Plot2 OR Plot1 Crosses Below Plot2 O
Plot2 Crosses Above Plot3 OR Plot2 Crosses Below Plot3 Then
Alert = True;

TPF_REVERSAL2002

Inputs: Sens(numeric);

Vars: S(0), B(0), Consec(4), Cntr(0), BCntr(0);

514
If jfcbmb = 0 and d = currentdate and DataCompression = 0 and T > Sess1StartTime
and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If jfcbmb = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If jfcbmb = 431 then begin

If C>C[Consec] then Cntr = Cntr + 1;

If C<C[Consec] then Cntr = 0;

{IF Cntr >= Count then begin


Plot1(H+.6,"Sell");
zz= PlaySound("e:\pages\high.wav");
end;}

If C<C[Consec] then BCntr = BCntr + 1;

If C>C[Consec] then BCntr = 0;

{IF BCntr >= Count then begin


Plot2(L-.6,"Buy");
zz= PlaySound("e:\pages\low.wav");
end;}

IF Cntr > 0 and Cntr >= Sens then TPF_Reversal2002 = -1;

IF BCntr > 0 and BCntr >= Sens then TPF_Reversal2002 = 1;

If (BCntr = 0 and BCntr[1] >= Sens) then TPF_Reversal2002 = 0;

If (Cntr = 0 and Cntr[1] >= Sens) then TPF_Reversal2002 = 0;

end;

515
{EXHAUSTION
+++++++++++++++++++++++++++++++++++++++++++}
Input: L1(21),SU(1),SD(-1), L2(8);

Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin


Plot1(BollingerBand(H,L1,SU),"Hi Exh");
Plot2(BollingerBand(L,L1,SD),"Lo Exh");
Plot3((BollingerBand(H,L1,SU) - BollingerBand(L,L1,SD))/2
+BollingerBand(L,L1,SD) ,"Avg");
Plot4(LinearRegValue(C,L2,0), "Avg2");

end;

{EXHAUSTION 2
+++++++++++++++++++++++++++++++++++++++++++}
Input: L1(21),SU(1),SD(-1), L2(8);

Vars: LRV(0);
Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;

516
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

LRV = LinearRegValue(C,L2,0);

If PassFlag = 1 and jfcbmb = 431 then begin

If LRV[1] > BollingerBand(H,L1,SU) and LRV < LRV[1] then begin


Plot1(LRV[1],"EHigh");
end;
If LRV[1] < BollingerBand(L,L1,SD) and LRV > LRV[1] then begin
Plot2(LRV[1],"ELow");
end;
end;

{MARKET DIRECTION}

Vars: NuHi(0), NuLo(999999), Med(0), UpCntr(0), DnCntr(0), CumCntr(0);

Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF D<>D[1] Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;

517
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin

If T = Sess1FirstBarTime then begin


NuHi = C;
NuLo = C;
UpCntr = 0;
DnCntr = 0;
CumCntr = 0;
end;

If T>Sess1StartTime and T < CalcTime(Sess1StartTime,+5) then begin


If H>NuHi then NuHi = H;
If L<NuLo then NuLo = L;
end;

If T > CalcTime(Sess1FirstBarTime,+5) then begin


Med = NuLo + ((NuHi-NuLo)/2);

end;

If C>Med then UpCntr = UpCntr + 1;


If C<Med then DnCntr = DnCntr + 1;
CumCntr = UpCntr - DnCntr;
Plot1(UpCntr,"Adv");
Plot2(-DnCntr,"Dec");
Plot3(CumCntr,"Total");

end;

REAL TIME PIVOT 2000


========================
}
Inputs: BB(numeric), SS(numeric);

Vars: rtp(0);

518
If jfcbmb = 431 then begin

If FastD(45) < 30 and FastD(7)[1] < BB and FastD(7)>FastD(7)[1] then begin


{Plot1(Low-.2,"JR Buy");}
rtp = 1;
end;

If FastD(45) > 30 or FastD(7)[1] > BB or FastD(7)<FastD(7)[1] then rtp = 0;

If FastD(45) > 70 and FastD(7)[1] >SS and FastD(7)<FastD(7)[1] then begin


{Plot2(High + .2,"JR Sell");}
rtp = -1;
end;

RealTimePivot2000 = rtp;

end ;

VOLATILITY STOP INDICATOR


=========================
}
{
Programmed by Dr. John F. Clayburg
Registered Commodity Trading Advisor
Omega Research Solution Provider
Omega Research EasyLanguage Expert
29568 Hwy 141
Coon Rapids, Iowa 50058-7178
(712) 684-5239 Voice & Fax

Volatility Stop
Indicator}

Vars: PassFlag(0);

519
DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin

Inputs: Length(21), Factor(3);

Vars: UVL(0), DVL(0), HClose(0), LClose(0), Up(true), Dn(true), UNuHi(0),


DNuLo(999999);

If CurrentBar = length then begin


UNuHi = H;
DNuLo = L;
end;

HClose = UNuHi;
LClose = DNuLo;

If CurrentBar = length then UVL = H - Factor*(Average(Range,Length));


If CurrentBar > length then UVL = HClose - Factor*(Average(Range,Length));
If CurrentBar = length then DVL = L + Factor*(Average(Range,Length));
If CurrentBar > length then DVL = LClose + Factor*(Average(Range,Length));

If C < UVL[1] then begin


Up = false;
Dn = true;
end;
If C > DVL[1] then begin
Dn = false;
Up = true;
end;
If Up then begin

520
If C > UNuHi then UNuHi = C;
DNuLo = 999999;
end;
If Dn then begin
If C < DNuLo then DNuLo =C;
UNuHi = 0;
end;

{Print("D",d,"T",t,"VUP",VolUp(21,4),"VDN",VolDn(21,4));}

{Print("D",d,"UP",up,"DN",dn,"UNuHi",Unuhi,"DNuLo",dnulo);}
If Up and UVL > 0 then Plot1(uvl,"UVL");
If Dn and DVL < 999999 then Plot2(dvl,"DVL");

end; {end for time bomb & blocknumber lock}

CLUSTER 20000
===============
}
Vars: PassFlag(0), LRV(0), BRT(false), SRT(false), BE(false), SE(false), BR(false),
SR(false),{ BB(12), SS(88),} BRS(5), sss(false), bbb(false);

If jfcbmb = 431 then begin

{********real time pivot


indicator********}

Vars: BRTBar(0);

If RealTimePivot2000(12,88) = 1 then begin


BRT = true;
BRTBar = barnumber;
end;

If RealTimePivot2000(12,88) = -1 then begin


SRT = true;
BRTBar = barnumber;
end;

If Barnumber > BRTbar + brs then begin


SRT = false;
BRT = false;
end;

{********exhaustion indicator********}

521
Vars: EBar(0), L1(21),SU(1),SD(-1), L2(8);

LRV = LinearRegValue(C,L2,0);

If LRV[1] > BollingerBand(H,L1,SU) and LRV < LRV[1] then begin


SE = true;
EBar = barnumber;
end;

If LRV[1] < BollingerBand(L,L1,SD) and LRV > LRV[1] then begin


BE = true;
EBar = barnumber;
end;

If Barnumber > Ebar + brs then begin


SE = false;
BE = false;
end;

REVERSAL INDICATOR

Vars: SBar(0) {S(0), B(0),Sens(9)};

IF TPF_Reversal2002(9) = -1 then begin


SR = true;
SBar = barnumber;
end;

IF TPF_Reversal2002(9) = 1 then begin


BR = true;
SBar = barnumber;
end;

If Barnumber > Sbar + brs then begin


SR = false;
BR = false;
end;

{********cluster indicator code********}

Vars: BBC(false), BBS(false), BBCBar(0), cl(0);

If (BR = false and BR[1] = true{consecutive indicator stops}) or BE or BRT then


begin
BBC = true;
BBCBar = barnumber;

522
end;

If Barnumber > BBCBar + brs then begin


BBC = false;
BE = false;
BRT = false;
end;

If BBS and SE and SRT then sss = true else sss = false;
If cl = -1 and cl[1] = -1 then cl = 0;
If sss and sss[1] = false then cl = -1 ;

If BBC and BE and BRT then bbb = true else bbb = false;
If cl = 1 and cl[1] = 1 then cl = 0;
If bbb and bbb[1] = false then cl = 1 ; {plot1(L-plt,"BUY");}

If (SR = false and SR[1] = true{consecutive indicator stops}) or SE or SRT then


begin
BBS = true;
BBCBar = barnumber;
end;

cluster2000 = cl;

end; {end for pass flag loop}

HI LO PIVOTS
}
{Programmed by Dr. John F. Clayburg
Omega Research Solution Provider
Omega Research EasyLanguage Expert
29568 Hwy 141
Coon Rapids, Iowa 50058-7178
(712) 684-5239 Voice & Fax
e mail: clayburg@pionet.net
http://elwood.pionet.net/~clayburg/ }

Inputs: Strength(2);

DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

Vars: PassFlag(0);

IF CurrentBar = 1 Then Begin


PassFlag = 0;

523
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin

If SwingHighBar(1,High,Strength,(Strength + 1)) = Strength then begin


Plot1[Strength](High[Strength],"High");

end;

If SwingLowBar(1,Low,Strength,(Strength + 1)) = Strength then begin


Plot2[Strength](Low[Strength],"Low");

end;

end;

INTRADAY HI LO
===============
}
Inputs: Pts(3);

Vars: NuHI(0), NuLo(0);

Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

524
If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >
Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin

If d<>d[1] then begin


NuHi = C;
NuLo = C;
end;

If H>NuHI then NuHi = H;

If L<NuLo then NuLo = L;

If H + pts > NuHi then Plot1(NuHi,"DayHi");


If L - pts < NuLo then Plot2(NuLo,"DayLo");

end;

PB LONG
=======
}

Vars: FastMA(5),SlowMA(34),MacdMA(8){,Length(9) ,x(5)},v2(85);

Vars: TrK(0),TrDF(0), TrDS(0),factor(0), zz(false);


vars: TrDSavg ( 0 ) , TrDFavg ( 0 ) , MultX ( 0 ) ;
Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin

525
PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin

MultX = {X}5 ;

TrDF = sfd( {length}9 , {X}5 ,{ X}5 ) ;

TrDs = ssd( {length}9 , {X}5 ,{ X}5 ) ;

TrDSavg = average ( average ( TrDS , 3 ) , 2 ) ;


TrDFavg = average ( average ( TrDF , 3 ) , 2 ) ;

condition1 = TrDSavg > v2 and TrDFavg > v2 and (absvalue ( TrDFavg - TrDSavg )
<2);

condition2 = TrDSavg < ( 100 - v2) and TrDFavg < ( 100 - v2 ) and ( ( TrDFavg -
TrDSavg ) > 2 ) ;

condition3 = TrDFavg > ( 100 - v2 ) and ( TrDFavg > TrDSavg ) ;

if condition1 = true
or condition2 = true
or condition3 = true
then value8 = 10
else value8 = 0 ;

value99 = MACD(Close,{FastMA}5,{SlowMA}34) -

XAverage(MACD(Close,{FastMA}5,{SlowMA}34),{MacdMA}8);

VALUE98 = (RSI(CLOSE,9)) - (AVERAGE(RSI(CLOSE,9),15));

value50 = slowk(21);

526
value51 = slowd(21);

condition11 = value50 > v2 and value51 > v2 and ( absvalue ( value50 - value51 ) < 2
);

condition12 = value51 < ( 100-v2 ) and value50 < ( 100 - v2 ) and ( ( value50 -
value51 ) > 2 );

condition13 = value50 > ( 100 - v2 ) and ( value50 > value51 ) ;

if condition11 = true
or condition12 = true
or condition13 = true
then value18 = 10
else value18 = 0;

if (value99 > 0 and value8 = 10) and


{MACD} {plot1 (high,"long");}

{Value 8 works with KFastD function}


(value18 = 10 and value8 = 10) and
{Regular Stochastic} {plot2 (MedianPrice,"long");}

( value98 > 0 and value8 = 10) then begin {RSI} {plot3


(LOW,"long");}
zz= PlaySound("e:\pages\low.wav");
Plot1(H,"H");
Plot2(L,"L");
end;

end; {end for passflag loop}

PB SHORT
=========
}

Vars:FastMA(5),SlowMA(34),MacdMA(8),Length(9),x(5),v2(85);

Vars: TrK(0),TrDF(0), TrDS(0),factor(0), zz(false);

527
vars: TrDSavg ( 0 ) , TrDFavg ( 0 ) , MultX ( 0 ) ;
Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin

MultX = {X}5 ;

{ Trk = sfk( {Length}9 , MultX ) ; }

TrDF = sfd( {Length}9 , {X}5 , {X}5 ) ;

TrDs = ssd( {Length}9 , {X}5 , {X}5 ) ;

TrDSavg = average ( average ( TrDS , 3 ) , 2 ) ;


TrDFavg = average ( average ( TrDF , 3 ) , 2 ) ;

condition1 = TrDSavg > v2 and TrDFavg > v2 and (absvalue ( TrDFavg - TrDSavg )
<2);

condition2 = TrDSavg < ( 100 - v2) and TrDFavg < ( 100 - v2 ) and ( ( TrDFavg -
TrDSavg ) > 2 ) ;

condition3 = TrDFavg > ( 100 - v2 ) and ( TrDFavg > TrDSavg ) ;

if condition1 = true
or condition2 = true
or condition3 = true
then value8 = 10
else value8 = 0 ;

528
value99 = MACD(Close,{FastMA}5,{SlowMA}34) -

XAverage(MACD(Close,{FastMA}5,{SlowMA}34),{MacdMA}8);

VALUE98 = (RSI(CLOSE,9)) - (AVERAGE(RSI(CLOSE,9),15));

value50 = slowk(21);
value51 = slowd(21);

condition11 = value50 > v2 and value51 > v2 and ( absvalue ( value50 - value51 ) < 2
);

condition12 = value51 < ( 100-v2 ) and value50 < ( 100 - v2 ) and ( ( value50 -
value51 ) > 2 );

condition13 = value50 > ( 100 - v2 ) and ( value50 > value51 ) ;

if condition11 = true
or condition12 = true
or condition13 = true
then value18 = 10
else value18 = 0;

if (value98 < 0 and value8 = 0) and

(value18 = 0 and value8 = 0 )and

( value99 < 0 and value8 = 0 ) then begin


zz= PlaySound("e:\pages\high.wav");
Plot1(H,"Short");
Plot2(L,"Short ");
end;

end; {end for passflag loop}

RUBBER BAND2
============
}

DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,


FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

529
IF CurrentBar = 1 Then Begin
PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 1 and jfcbmb = 431 then begin

Plot1(XAverage(C,13),"Plot1");
Plot2(XAverage(C,21),"Plot2");
Plot3(XAverage(C,34),"Plot3");
Plot4(XAverage(C,55),"Plot4");

end;

SFD
===
}
Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 1 then begin

If CurrentBar <= 1 then begin


Factor = 2 / (3 + 1);
sfd =sfk(Length , MultX ) ;
End
Else

530
SFD = sfd[X] + (Factor * (sfk( Length , MultX ) -sfd[X] ) );

end; {end for passflag loop}

SFK
===
}

Inputs : Length(NumericSimple) , MultX ( Numeric );

{Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 1 then begin}

Value1 = Lowest(Low , Length * MultX ) ;


Value2 = Highest(High , Length * MultX ) - Value1;
Value3 = Close;

If Value2 > 0 then


sfk = (Value3 - Value1) / Value2 * 100
Else
sfk = 0;

{end;} {end for passflag loop}

SSD
===
}

531
Input : Length(NumericSimple) , X(Numeric) , MultX ( Numeric ) ;

Vars: PassFlag(0);

DefineDLLFunc: "JCB1Lock.dll",FLOAT,
"LTCalcRef",LPFloat,LPFloat,LPFloat,LPFloat,LPSTR;
DefineDLLFunc: "JCB1lock.dll", FLOAT, "LTCalcVal", FLOAT, FLOAT, FLOAT,
FLOAT, LPSTR;
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF CurrentBar = 1 Then Begin


PassFlag = 0;
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 1 then begin

If CurrentBar <= 1 then ssd = sfd( Length , X, MultX )


Else
ssd = ((ssd[X] * 2) + sfd( Length , X , MultX ) ) / 3;
end; {end for passflag group}

CLUSTER VOLATILITY STOP – USES CLUSTER 2000 AS A FUNCTION


=========================================
}

Input: Fac(3),
ATRLen(10),
Plt(.5);

Vars: MP(0), {Market position}


MaxChand(0), {Chandelier exit var}
MinChand(0) {Chandelier exit var},
Lng(false),
LStp(0), Sht(false), LStpPlt(0), SStpPlt(0), passflag(1);
{
DefineDLLFunc: "JCB1Lock.dll",INT,"LTInitializeFromIni";

IF d = currentdate Then Begin


PassFlag = 0;

532
PassFlag = LTInitializeFromINI;
end;

If PassFlag = 0 and d = currentdate and DataCompression = 0 and T >


Sess1StartTime and T < CalcTime(Sess1StartTime,5) then Value97 =
Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );

If PassFlag = 0 and d = currentdate and t = Sess1FirstBarTime then Value97 =


Text_New(CurrentDate,Sess1FirstBarTime,O, "STUDY HAS EXPIRED. Call
712.684.5239 for new password " );
}
If PassFlag = 1 and jfcbmb = 431 then begin

if Cluster2000 = 1 then begin


MaxChand = -999999;
Lng = true;
Plot3(L-Plt,"CL_BUY");
{Sht = false;}
{LStp = c-Ini_Stp;}
end;

if L < MaxChand then lng = false;

If lng and (H -Fac*Average({True}Range,ATRLen)) >= MaxChand then begin


MaxChand= ( H -Fac*Average({True}Range,ATRLen));

end;
If Lng then Plot1(MaxChand,"LongStop");

if Cluster2000 = -1 then begin


MinChand = 999999;
Sht = true;
Plot4(H+Plt,"CL_SELL");
{Lng = false;}
{LStp = c-Ini_Stp;}
end;

If H > MinChand then sht = false;

If sht and (L +Fac*Average(TrueRange,ATRLen)) <= MinChand then begin


MinChand= (L +Fac*Average(TrueRange,ATRLen));

end;

If sht then Plot2(MinChand,"ShortStop"); end;

533
{

CLUSTER 2000
}

Vars: PassFlag(0), LRV(0), BRT(false), SRT(false), BE(false), SE(false), BR(false),


SR(false),{ BB(12), SS(88),} BRS(5), sss(false), bbb(false);

If jfcbmb = 431 then begin

{********real time pivot


indicator********}

Vars: BRTBar(0);

If RealTimePivot2000(12,88) = 1 then begin


BRT = true;
BRTBar = barnumber;
end;

If RealTimePivot2000(12,88) = -1 then begin


SRT = true;
BRTBar = barnumber;
end;

If Barnumber > BRTbar + brs then begin


SRT = false;
BRT = false;
end;

{********exhaustion indicator********}

Vars: EBar(0), L1(21),SU(1),SD(-1), L2(8);

LRV = LinearRegValue(C,L2,0);

If LRV[1] > BollingerBand(H,L1,SU) and LRV < LRV[1] then begin


SE = true;
EBar = barnumber;
end;

If LRV[1] < BollingerBand(L,L1,SD) and LRV > LRV[1] then begin


BE = true;
EBar = barnumber;
end;

534
If Barnumber > Ebar + brs then begin
SE = false;
BE = false;
end;

REVERSAL INDICATOR

Vars: SBar(0) {S(0), B(0),Sens(9)};

IF Reversal2000(9) = -1 then begin


SR = true;
SBar = barnumber;
end;

IF Reversal2000(9) = 1 then begin


BR = true;
SBar = barnumber;
end;

If Barnumber > Sbar + brs then begin


SR = false;
BR = false;
end;

CLUSTER INDICATOR CODE

Vars: BBC(false), BBS(false), BBCBar(0), cl(0);

If (BR = false and BR[1] = true{consecutive indicator stops}) or BE or BRT then


begin
BBC = true;
BBCBar = barnumber;
end;

If Barnumber > BBCBar + brs then begin


BBC = false;
BE = false;
BRT = false;
end;

If BBS and SE and SRT then sss = true else sss = false;
If cl = -1 and cl[1] = -1 then cl = 0;
If sss and sss[1] = false then cl = -1 ;

If BBC and BE and BRT then bbb = true else bbb = false;

535
If cl = 1 and cl[1] = 1 then cl = 0;
If bbb and bbb[1] = false then cl = 1 ; {plot1(L-plt,"BUY");}

If (SR = false and SR[1] = true{consecutive indicator stops}) or SE or SRT then


begin
BBS = true;
BBCBar = barnumber;
end;

cluster2000 = cl;

end; {end for pass flag loop}

CANDLESTICK PATTERN RECOGNITION


{*******************************************************************
Description : This Indicator plots CandleStick Patterns
Provided By : Omega Research, Inc. (c) Copyright 1999

MODIFIED BY BSS-- IE: HANGING MAN; also added gaps: up gap with blue dot;
down gap with magenta dot
********************************************************************}

Inputs: Tolernce(5), Length(5), Tail(3);


Variables: String1(""), TextLoc(0), String2(""), String3("");

If DataCompression = 0 and BarInterval <= 5 Then


Commentary("This indicator must be applied to a bar interval larger than 5
ticks.")
Else
If DataCompression = 5 Then
Commentary("This indicator can not be applied to Point and Figure charts.
")
Else Begin
String1 = "";
String2 = "";

Condition1 = false; {for bullish patterns}


Condition2 = false; {for bearish patterns}
Condition3 = false; {for hangman}
Condition4 = false; {for doji}

If Doji(tolernce) Then Begin


String1 = "Dj";
String3 = "A \hbDOJI\he pattern has been identified. ";
Condition4 = True;

536
End;

If _Hammer(Length, tail) Then Begin


String1 = "Ha";
String3 = "A \hbHAMMER\he pattern has been identified. ";
Condition1 = True;
End;

If _HangingMan(Length, tail) Then Begin


String1 = "HM";
String3 = "A \hbHANGING MAN\he pattern has been identified. ";
Condition3 = True;
End;

If _ShootingStar(Tail, Length) Then Begin


String1 = "SS";
String3 = "A \hbSHOOTING STAR\he pattern has been identified. ";
Condition2 = True;
End;

If _BearishEngulfing(length) Then Begin


String1 = "BeE";
String3 = "A BEARISH ENGULFING pattern has been identified. "+"Please
see \hbBullish & Bearish Engulfing Lines\he. ";
Condition2 = True;
End;

If _BullishEngulfing(length) Then Begin


String1 = "BuE";
String3 = "A BULLISH ENGULFING pattern has been identified. "+"Please
see \hbBullish & Bearish Engulfing Lines\he. ";
Condition1 = True;
End;

If _DarkCloud(length) Then Begin


String1 = "DC";
String3 = "A \hbDARK CLOUD cover\he pattern has been identified. ";
Condition2 = True;
End;

If MorningStar(length) Then Begin


String1 = "MS";
String3 = "A \hbMORNING STAR\he pattern has been identified. ";
Condition1 = True;
End;

If _EveningStar(length) Then Begin


String1 = "ES";
String3 = "A \hbEVENING STAR\he pattern has been identified. ";

537
Condition2 = True;

End;

If CommentaryEnabled Then
String2 = ("DJ = Doji "+newline+"Ha = Hammer"+Newline+"HM =
HangingMan"+Newline+"SS = ShootingStar"+
Newline + "BeE= BearishEngulfing"+ Newline+ "BuE= BullishEngulfing"+
NewLine+ "DC = DarkCloud"+ Newline+
"MS = MorningStar"+ Newline+ "ES = EveningStar"+Newline+Newline);

If Condition1 Then Begin


String2 = String2 + String3;
{ Plot1(High, "CndlPH");
Plot2(Low, "CndlPL"); }
Value1 = Text_New(Date, Time, High, String1);
TextLoc = Text_SetStyle(Value1, 2, 1);
If GetBackGroundColor = Tool_White Then
Value2 = Text_SetColor(Value1, Tool_Red)
Else
Value2 = Text_SetColor(Value1, Tool_cyan);
End;

If Condition2 Then Begin


String2 = String2 + String3;
{ Plot1(High, "CndlPH");
Plot2(Low, "CndlPL"); }
Value1 = Text_New(Date, Time, High, String1);
TextLoc = Text_SetStyle(Value1, 2, 1);
If GetBackGroundColor = Tool_White Then
Value2 = Text_SetColor(Value1, Tool_Red)
Else
Value2 = Text_SetColor(Value1, Tool_magenta);
End;

If Condition3 Then Begin


String2 = String2 + String3;
{ Plot1[1](High[1], "CndlPH");
Plot2[1](Low[1], "CndlPL"); }
Value1 = Text_New(Date[1], Time, High, String1);
TextLoc = Text_SetStyle(Value1, 2, 1);
If GetBackGroundColor = Tool_White Then
Value2 = Text_SetColor(Value1, Tool_Red)
Else
Value2 = Text_SetColor(Value1, Tool_magenta);
End;

538
If Condition4 Then Begin

String2 = String2 + String3;


{ Plot1(High, "CndlPH");
Plot2(Low, "CndlPL"); }
Value1 = Text_New(Date, Time, High, String1);
TextLoc = Text_SetStyle(Value1, 2, 1);
If GetBackGroundColor = Tool_White Then
Value2 = Text_SetColor(Value1, Tool_Red)
Else
Value2 = Text_SetColor(Value1, Tool_white);
End;

If AtCommentaryBar Then
Commentary(String2);
End;

{gap up}
Condition5 = Low > High of 1 bar ago;

{gap down}
Condition6 = High < Low of 1 bar ago;

Inputs: PLOTINCR(1);

If condition5 then
plot3(low - PLOTINCR*MINMOVE POINTS, "Gap Up", yellow, default, 2);

If condition6 then
plot4(high + PLOTINCR*MINMOVE POINTS, "Gap down", yellow, default, 2);

=============================================================
===============
=========
{*******************************************************************
Description : This Function returns Dark Cloud
Provided By : Omega Research, Inc. (c) Copyright 1999
Added additional criteria per page 258 of Steve Nison's book "Beyond
Candlesticks"
********************************************************************}

Input: Length(Numeric);
Variables: LongBody(False), OCRange(0);

OCRange = AbsValue(Open - Close);


LongBody = OCRange > Average(OCRange, Length);
_DarkCloud = False;

539
Condition1 = average(close, length)[1] > average(close, length)[3];
{there is an uptrend}

If Condition1 and Close[1] > Open[1] AND Close[1] - Open[1] >


MaxList(High[1] - Close[1], Open[1] - Low[1]) Then Begin
If LongBody[1] AND Open > High[1] AND Close <= MedianPrice[1] Then
_DarkCloud = True;
End;

=============================================================
===============
========
{*******************************************************************
Description : This Function returns HangingMan
Provided By : Omega Research, Inc. (c) Copyright 1999

Added additional criteria per page 258 of Steve Nison's book "Beyond
Candlesticks"
********************************************************************}

Inputs: Length(Numeric), Tail(Numeric);


Variables: Min(0), Max(0);

Min = Minlist(Close, Open);


Max = Maxlist(Close, Open);
_HangingMan = False;

Condition1 = close < Min[1]; {close is under real body of hangingman}


Condition2 = average(close, length)[1] > average(close, length)[3];
{there is an uptrend}

If Condition1 and condition2 and Min[1] > MedianPrice[1] AND Open[1] <>
Close[1] Then Begin
If Min[1] - Low[1] > (Max[1] - Min[1]) * Tail AND High[1] - Max[1] <
Max[1] - Min[1] Then
_HangingMan = True;
End;

=============================================================
===============
========
{*******************************************************************
Description : This Function returns Shooting Star
Provided By : Omega Research, Inc. (c) Copyright 1999

BSS added a requirement for an uptrend


********************************************************************}

540
Input: Tail(Numeric), Length(Numeric);
Variables: Min(0), Max(0);

Min = Minlist(Close, Open);


Max = Maxlist(Close, Open);

_Shootingstar = false;

Condition1 = Average(Close, Length)[1] > Average(Close,Length)[3] ;

If Currentbar > 1 Then Begin


If Condition1 and Max < MedianPrice AND Open <> Close Then Begin
If High - Max > (Max - Min) * Tail AND Min - Low < Max - Min Then
_ShootingStar = true;

End;
End;

=============================================================
===============
========

{ *******************************************************************
Description : This Function returns Bearish Engulfing
Provided By : Omega Research, Inc. (c) Copyright 1999

BSS changed particular days on the average


*********************************************************************
}

Inputs: Length(Numeric);

If Average(Close, Length)[1] > Average(Close,Length)[3] AND Close < Open AND


Close[1] > Open[1] AND Close < Open[1] AND Open > Close[1] then
_BearishEngulfing = True
Else
_BearishEngulfing = False;

=============================================================
===============
=========
{*******************************************************************
Description : This Function returns Bullish Engulfing
Provided By : Omega Research, Inc. (c) Copyright 1999

BSS changed particular days in average


*********************************************************************

541
}

Inputs: Length(Numeric);

If Average(Close, Length)[1] < Average(Close, Length)[3] AND Close > Open

AND Close[1] < Open[1] AND Close > Open[1] AND Open < Close[1] Then
_BullishEngulfing = True
Else
_BullishEngulfing = False;

=============================================================
===============
========

{*******************************************************************
Description : This Function returns Evening Star
Provided By : Omega Research, Inc. (c) Copyright 1999
Added additional criteria per page 258 of Steve Nison's book "Beyond
Candlesticks"
********************************************************************}

Inputs: Length(Numeric);
Variables: LongBody(False), OCRange(0), Hollow(False), Filled(False),
Shortbody(false);

Hollow = Close > Open;


Filled = Close < Open;

OCRange = AbsValue(Open-Close);
LongBody = OCRange > Average(OCRange,Length);
ShortBody = OCRange < Average(OCRange, Length);
_EveningStar = False;

Condition1 = shortbody[1]; {the second bar must be a shortbody}

Condition2 = average(close, length)[1] > average(close, length)[3]; {there


is an uptrend}

Condition3 = Minlist(close[1], Open[1]) > open; {the current


candle's real body is below the previous bodies real body}

If CurrentBar >= Length Then Begin


If condition1 and condition2 and condition3 and Hollow[2] AND
Minlist(Close[1],Open[1]) > Close[2] AND Filled AND LongBody[2] AND Close <
Close[2] Then
_EveningStar = True;
End;

=============================================================

542
===============
=========
{ *******************************************************************
Description : This Function returns Hammer
Provided By : Omega Research, Inc. (c) Copyright 1999
********************************************************************}

Inputs: Length(Numeric), Tail(Numeric);


Variables: Min(0), Max(0);

Min = Minlist(Close, Open);


Max = Maxlist(Close, Open);
_Hammer = False;

Condition1 = average(close, length)[1] < average(close, length)[3];


{there is an downtrend}

If Min > MedianPrice AND Open <> Close Then Begin


If Min - Low > (Max - Min) * Tail AND High - Max < Max - Min AND Condition1
then
_Hammer = True;
End;

=============================================================
===============
=========

{*******************************************************************
Description : This Function returns Doji
Provided By : Omega Research, Inc. (c) Copyright 1999
********************************************************************}

Inputs: Tolernce(Numeric);

If Open = Close OR AbsValue(Open - Close) <= Range * (Tolernce / 100) Then


Doji = True
Else
Doji = False;
=============================================================
===============
=========

{*******************************************************************
Description : This Function returns the MorningStar pattern
Provided By : Omega Research, Inc. (c) Copyright 1999
********************************************************************}

Inputs: Length(Numeric);

543
Variables: LongBody(False), OCRange(0), Hollow(False), Filled(False);

Hollow = Close > Open;


Filled = Close < Open;

OCRange = AbsValue(Open-Close);
LongBody = OCRange > Average(OCRange,Length)MorningStar = False;

If Filled[2] AND Maxlist(Close[1], Open[1]) < Close[2] AND Hollow AND


LongBody[2] AND Close > Close[2] Then
MorningStar = True;

TFS TREND FOLLOWING SYSTEM

The guy who sent this is supposed to be a whiz.He deals with


corporate and hedge fund clients.

Is anyone up to creating an ELA and testing it on various markets of


interest.?

If nothing else add it to your library for things to do.

John

"This attached system (with accompanying indicators) follows the


basic
tenents of good trading discipline:
1) let profits run,
2) cut losses short,
3) trade with the trend

other disciplines need to be followed such as:

4) proper diversification (never expose more than 2 to 5% capital


risk onany one trade)

5) close attention to the economic and business fundamentals that


apply to the stock or futures market you are trading. (i.e. don't
buy just because a stock is going up and don't sell just because a
stock is going down.

Understand the 'why' and be reasonable about the likelihood of


continuation/follow-through.)"

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
++++++
+++++
{ *******************************************************************

Indicator : TFS (Trend Following System)

544
Last Edit : 7/2/2000

Provided By : James Taylor, Principal

Description :
Variation of the function from the June 2000 edition of S&C
Magazine,Bryan Strain, Author.

********************************************************************}

Vars: VolOsc(0);
If Close > Open then
VolOsc = Volume;

If Close < Open then


VolOsc = - Volume;

{Original concept logic}


{If Close Crosses Above ((Highest(High, 50) + Lowest(Low, 50)) / 2)
then
If Average(VolOsc, 7) > 0 then begin
Buy;
ExitShort;
End
Else
ExitShort;

If Close Crosses Below ((Highest(High, 50) + Lowest(Low, 50)) / 2)


then
If Average(VolOsc, 7) < 0 then begin
Sell;
ExitLong;
End
Else
ExitLong;}

{ This variation appears to be more profitable than the original }


If Close > ((Highest(High, 50) + Lowest(Low, 50)) / 2) AND
Average(VolOsc, 7) > 0 then begin
Buy;
ExitShort;
End;

If Close < ((Highest(High, 50) + Lowest(Low, 50)) / 2) AND


Average(VolOsc, 7) < 0 then begin
Sell;
ExitLong;
End;

TETHERLINE

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+++++

{ *******************************************************************

545
Indicator : TetherLine (Trend Following Indicator)

Last Edit : 7/2/2000

Provided By : James Taylor, Principal

Description :
This function is from the June 2000 edition of S&C Magazine.

********************************************************************}
Plot1((Highest(High, 50) + Lowest(Low, 50)) / 2);

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
++++++
++

VOLUME OSCILLATOR

{ *******************************************************************

Indicator : VolOsc (Volume Oscillator)

Last Edit : 7/2/2000

Provided By : James Taylor, Principal

Description :
This function is from the June 2000 edition of S&C Magazine.

********************************************************************}
Vars: VolOsc(0);

If Close > Open then


VolOsc = Volume;

If Close < Open then


VolOsc = - Volume;

Plot1(Average(VolOsc, 7), "VO");


Plot2(0, "ZeroLine");

DOUBLE STOCHASTIC

Hello Spot,

try of %R of %R

546
Indicator:
>
> Inputs: DStLen(21),SellLine(80),BuyLine(20),Smooth(3);
>
> Vars: DStoc(0);
>
> {DStoc}
> DStoc=_DStoc(DStLen);
>
>
> {Plots}
> Plot1(DStoc,"DStoc");
> Plot2(SellLine,"Upper");
> Plot3(BuyLine,"Lower");
> Plot4(average(DStoc,Smooth),"Smooth");
>
> **************************************************
> Function:
>
> {_DStoc: Double Stochastic}
>
> Inputs: DStLen(NumericSimple);
>
> Vars: Num(0),Denom(0),Ratio(0),PctK(0),DNum(0),DDenom(0),
> DRatio(0),DPctK(0);
>
> {Stoc}
> Num=C-_Lst(L,DStLen);
> Denom=_Hst(H,DStLen)-_Lst(L,DStLen);
> Ratio=IFF(Denom>0,(Num/Denom)*100,Ratio[1]);
> PctK=IFF(CurrentBar=1,Ratio,PctK[1]+(.5*(Ratio-PctK[1])));
>
> {DStoc}
> DNum=PctK-_Lst(PctK,DStLen);
> DDenom=_Hst(PctK,DStLen)-_Lst(PctK,DStLen);
> DRatio=IFF(DDenom>0,(DNum/DDenom)*100,DRatio[1]);
> DPctK=IFF(CurrentBar=1,DRatio,DPctK[1]+(.5*(DRatio-DPctK[1])));
>
> _DStoc=DPctK;
>

RINA DATA COLLECTION PORTFOLIO OUTPUT

Hi List:

547
The below code has been extremely helpful for us in data collection. It
was provided to us FREELY by Rina Systems, and should be noted as such. We
use it with their PortfolioStream software and both come highly recommended.

The purpose of this TradeStation Strategy code is to create text files with
each data bar on the chart stored in it. When applied to a TS6.0 chart,
you will then create a txt file at the OutputPath input location. These
text files can then be accessed by 2000i by creating a new 3rd party
Directory Symbol list, which allows for us to continue our offline testing
on secondary computers.

By using PortfolioStream, we were able to have it automatically go through


each symbol in the SP500 without user intervention.

One problem however, is the intra-day data limitations of TS6.0. Their


intraday data only goes back to November of 2000.

Any suggestions for using other software that stores more intradata data?
Esignal has 60 days, and i heard MetaStock stores more but not sure how
much.
Looking for around 5 years of intraday stock data for testing.

Thanks, and hope this simple tool helps.

David

{This code is provided by RINA Systems, Inc.

Data Exporter Signal

The Data Exporter signal exports the date and pricebars of the data in your
TradeStaiton chart to a file. The file is
named and placed on your computer based on the inputs you provide. The
price data that is exported can be constrained
by a date rage if you wish, or you can export all the data in the chart that
the strategy is applied to.
The signal automatically names the file after the symbol in the chart so
that you can run workspace assistant to export
multiple signals and have each signal written to its own file.}

Inputs:
StartDTE(701210),EndDTE(1011231),OutputPath("C:\Data\"),FileExtension(".txt"
),UseDateRange(false),HeaderAndFooter(false),IncludeVOI(false),DecimalPlaces

548
(8);

Var: priceO(Open), priceH(High), priceL(low), PriceC(close);


var: PadDate("PaddedDate"),PadYear("PaddedYear"), PadMonth("PaddedMonth"),
PadDay("PaddedDay"), PadTime("PaddedTime");

{Sets the OHLC values every bar}


PriceO=Open;
PriceH=High;
PriceL=Low;
PriceC=close;

if HeaderAndFooter = true then {Print the header if desired}


begin
if barnumber = 1 then
FileAppend((OutputPath + getsymbolname + FileExtension), "Begin PriceData
for "+getsymbolname+NewLine);
end;

if UseDateRange = true then {Set Condition1 if you are using the date range}
begin;
Condition1 = date >= StartDTE and date <= EndDTE; {set Condition 1 to
export only inclusively between the two input dates}
end;

if UseDateRange = false then {Set Condition1 if you are not using the date
range}
begin;
Condition1 = open > 0; {Export all price data}
end;

if Condition1 = true then


begin

if time < 0010 then {Pad the Time with zeros as needed}
PadTime = numtostr(0,0)+ numtostr(0,0)+numtostr(0,0)+numtostr(time,0);
if time > 0009 and time < 0100 then
PadTime = numtostr(0,0)+numtostr(0,0)+numtostr(time,0);
if time > 0059 and time < 1000 then
PadTime = numtostr(0,0)+numtostr(time,0);
if time > 0959 then
Padtime = numtostr(time,0);

if dayofmonth(date) < 10 then {Pad the Day with zeros as needed}


PadDay = numtostr(0,0)+numtostr(dayofmonth(date),0);
if dayofmonth(date) > 9 then
PadDay = numtostr(dayofmonth(date),0);

549
if month(date) < 10 then {Pad the Month with zeros as needed}

PadMonth = numtostr(0,0)+numtostr(month(date),0);
if month(date) > 9 then
PadMonth = numtostr(month(date),0);

if year(date) < 100 then {Pad the Year with zeros as needed}
PadYear = numtostr(19,0)+numtostr(year(date),0);
if year(date) > 99 then
PadYear = numtostr(200,0)+numtostr(year(date)-100,0); {takes care of the
non y2k compliancy problem with EasyLanguage}

{Propper Date formats: YYYYMMDD, YYYYDDMM, MMDDYYYY,


DDMMYYYY
All of whice can be easlity achived by moving around the padded variables
in the line below.}
PadDate = PadMonth + PadDay + PadYear;

{Last but not least the printing. 8 decimal places should be sufficient
for most markets.
The file outputs to the specified OutputPath input.
The format in the comma delimited output file is as follows:
Date, Time, Open, High, Low, Close}

if IncludeVOI = false then


FileAppend((OutputPath + getsymbolname + FileExtension),
PadDate+","+PadTime+","+numtostr(Open,DecimalPlaces)+","+numtostr(High,Deci
m
alPlaces)+","+numtostr(Low,DecimalPlaces)+","+numtostr(Close,DecimalPlaces)+
NewLine);
if IncludeVOI = true then
FileAppend((OutputPath + getsymbolname + FileExtension),
PadDate+","+PadTime+","+numtostr(Open,DecimalPlaces)+","+numtostr(High,Deci
m
alPlaces)+","+numtostr(Low,DecimalPlaces)+","+numtostr(Close,DecimalPlaces)+
","+numtostr(Volume,0)+","+numtostr(OpenInt,0)+NewLine);

{End Condition1}
end;

if HeaderAndFooter = true then {Print the footer if desired}


begin
if lastbaronchart then
FileAppend((OutputPath + getsymbolname + FileExtension), "End PriceData
for "+getsymbolname+NewLine);
end;

550
WILL SPREAD

John,

Here is a version of the WillSpread indicator that you can cut and paste:

The points make it easier to see the crossovers of the L/Tmoving average.

Regards,

Barry Silberman
==================================================
{Will-Spread per Larry Williams pages 138 - 141 of book "Long-Term Secrets
to Short-Term Trading}
{Barry Silberman interpretation}
{plots 1 and 2 should be lines. Plots 3 and 4 should be points}

inputs: DataSeries1( Close of data1), DataSeries2( Close of data2 ),


length1(5), length2(20) ;
Variable: Spread(0), Avg_Short(0), Avg_Long(0);

Spread = DataSeries1 - DataSeries2;

Avg_Short = xaverage(spread, length1);

Avg_Long = xaverage(spread, length2);

Plot1( Avg_Short, "avg_short" ) ;

Plot2( Avg_long, "avg_long" ) ;

If avg_short crosses over avg_long then


Plot3(0, "up", green, default, 4);

If avg_short crosses under avg_long then


Plot4(0, "down", red, default, 4);

MAMA FAMA
+++++++++++++++++++++++++++++++++++

{by John Ehlers TASC September 2001}


{Plots two lines that trend with price and cross over near turning points.}

Inputs: Price((H+L)/2),FastLimit(0.5),SlowLimit(0.05);
Vars:

551
Smooth(0),
Detrender(0),
I1(0),
Q1(0),
jI(0),
jQ(0),
I2(0),
Q2(0),
Re(0),
Im(0),
Period(0),
SmoothPeriod(0),
Phase(0),
DeltaPhase(0),
alpha(0),
MAMA(0),
FAMA(0);

If CurrentBar>5 then begin


Smooth=(4*Price+3*Price[1]+2*Price[2]+Price[3])/10;

Detrender=(0.0962*Smooth+0.5769*Smooth[2]-0.5769*
Smooth[4]-0.0962*Smooth[6])*(0.075*Period[1]+0.54);

{Compute InPhase and Quadrature components}


Q1=(0.0962*Detrender+0.5769*Detrender[2]-0.5769*
Detrender[4]-0.0962*Detrender[6])*(0.075*Period[1]+0.54);
I1=Detrender[3];

{Advance the phase of I1 and Q1 by 90 degrees}


jI=(0.0962*I1+0.5769*I1[2]-0.5769*I1[4]-0.0962*I1[6])*(0.075*Period[1]+0.54)
;
jQ=(0.0962*Q1+0.5769*Q1[2]-0.5769*Q1[4]-0.0962*Q1[6])*(0.075*Period[1]+0.54)
;

{Phasor addition for 3-bar averaging}


I2=I1-jQ;
Q2=Q1+jI;

{Smooth the I and Q components before applying the discriminator}


I2=0.2*I2+0.8*I2[1];
Q2=0.2*Q2+0.8*Q2[1];

{Homodyne Discriminator}
Re=I2*I2[1]+Q2*Q2[1];
Im=I2*Q2[1]-Q2*I2[1];
Re=0.2*Re+0.8*Re[1];
Im=0.2*Im+0.8*Im[1];
If Im<>0 and Re<>0 then Period=360/ArcTangent(Im/Re);
If Period>1.5*Period[1] then Period=1.5*Period[1];
If Period<0.67*Period[1] then Period=0.67*Period[1];
If Period<6 then Period=6;
If Period>50 then Period=50;
Period=0.2*Period+0.8*Period[1];
SmoothPeriod=0.33*Period+0.67*SmoothPeriod[1];

If I1<>0 then Phase=(ArcTangent(Q1/I1));


DeltaPhase=Phase[1]-Phase;
If DeltaPhase<1 then DeltaPhase=1;

552
alpha=FastLimit/DeltaPhase;
If alpha<SlowLimit then alpha=SlowLimit;
If alpha>FastLimit then alpha=FastLimit;
MAMA=alpha*Price+(1-alpha)*MAMA[1];
FAMA=0.5*alpha*MAMA+(1-0.5*alpha)*FAMA[1];

Plot1(MAMA,"MAMA");
Plot2(FAMA,"FAMA");

End;
+++++++++++++++++++++++++++++++++++

ACTIVE INVESTING

DALE 8_ !Original SuperCharts Easy Language Code


!Code extracted from "Active Investing" by Alan Hull (Australia)
published by John Wiley International
!cleared by Alan Hull for conversion to AIQ Code. 9/12/02

!**********************
!SuperCharts Code:
!**********************

!Range Indicator - Rising Equities


!The range indicator overlays 3 lines on the price data and 'Scaling'
must be set for 'Same as
!price data'.

!Plot1 [Central Cord]


!round(

!((6.854*LinearRegValue(close,13,0))+(4.236*LinearRegValue(LinearRegV
alue(close,13,0),11,0))+(2.618*

!LinearRegValue(LinearRegValue(LinearRegValue(close,13,0),11,0),7,0))
+(1.618*LinearRegValue(LinearR
!egValue(LinearRegValue(LinearRegValue(close,13,0),11,0),7,0),5,0)) +

!(1*LinearRegValue(LinearRegValue(LinearRegValue(LinearRegValue(Linea
rRegValue(close,13,0),11,0),7
!,0),5,0),3,0)) )/16.326,2)

!Plot2 [Upper Channel]


!round(plot1+(3*AvgTrueRange(13)) ,2)

!Plot3 [Lower Channel]


!round( iff( plot1>plot3[1] ,iff(plot1-
(2.5*AvgTrueRange(13))>plot3[1],plot1-
!(2.5*AvgTrueRange(13)),plot3[1]),plot1),2)

!----END OF SUPERCHARTS CODE----

!********************************************************************
*****************************
!Range Indicator for Alan Hull's Active Investing Channel System:

553
! Coded by Gordon Sutherland but not functioning as per
SuperCharts Code above

!********************************************************************
*****************************.

TR is Max([High], Val([Close], 1)) - Min([Low], Val([Close], 1)).


!True Range for Channel Expansion
ATR13 is ExpAvg(TR,13).

!CENTRAL CORD:
LinReg13 is Intercept. ! Set the days to 13 below in the Dale
Paul Defined "Constdays"

!LOWER CHANNEL: !Doesn't seem to achieve the "flatline" as per


SuperCharts GIF file
! and not sure code is correct due to circular reference?
LowerDev13 is Iff(LinReg13 > ValResult(LinReg13,1),
iff(LinReg13 - (ATR13 * 2.5) >
ValResult(LinReg13 - (ATR13 * 2.5),1),
LinReg13 - (ATR13 *
2.5),ValResult(LinReg13 - (ATR13 * 2.5),1)),
LinReg13).

!UPPER CHANNEL: !LinReg13 UDF below is simplified pending solution to


Central Cord above
UpperDev13 is LinReg13 + (ATR13 * 3).

!END OF MY CODING ATTEMPT!

!********************************************************************
******************
! LINEAR REGRESSION AND SLOPE AND STD DEVIATION - Sourced from:

!********************************************************************
******************

! Author: Dale Paul (AIQ)


! Date: 4/7/2001
! How to calculate a slope and intercept using linear regression

! how many days are we running this for?


define constdays 13. ! Originally set at 5 But changed to 13 for
Active Investing criteria
! days is HasDataFor(constdays).
days is constdays.
! value (in this case the close)
varudf is [close]. !!!!! y = varudf

!=======================================
! Linear regression calculation using the Least Means Squared method
!========================================
day is offsettodate(month(),day(),year())+1.
dayX2 is day * day. !!! x = Day , dayX2 = x-
squared

sx is Sum(day,days). !!!Sum of x
sx2 is Sum(dayX2,days). !!!Sum of x*x
sy is Sum(varudf,days). !!!Sum of y
sy2 is Sum(varudf*varudf,days).

554
sxy is Sum( day * varudf ,days). !!!sum of x*y
d is ( days * sx2) - (sx * sx).

slope is ((days * sxy) - ( sx * sy)) / -d. ! same result as internal


Slope function
b is ((sx2 * sy) - (sx * sxy)) / d.

Intercept is slope + b. !THIS IS THE LINEAR REGRESSION VALUE


! REMEMBER TO CHANGE THE
DEFINED # DAYS AND VARUDF (CLOSE etc) - GBS
!=======================
!RD code from HHP Excel sheet from Chande & Kroll "New Tech Trader"
p.21
q1 is (sxy-((sx*sy)/days)).
q2 is (sx2-((sx*sx)/days)).
q3 is ((sy2) - ((sy*sy)/days)).
Slpe is q1/-q2. ! Formula
correction & negative denominator - fudge factor.
Intercpt is ((0.2*sy) - (3*Slpe)). ! Chande's formula.
Intercpt2 is sy/days-Slope*sx/days. ! Cliffs Notes "Statistics"
formula.
Rsqrd is (q1*q1)/(q2*q3).
PrjClose6 is ((6*Slope) + Intercept).
PrjClose7 is ((7*Slope) + Intercept).
PrjClose8 is ((8*Slope) + Intercept).
PrjClose9 is ((9*Slope) + Intercept).
PrjClose10 is ((10*Slope) + Intercept).
Diff1 is (Prjclose6-[close])/[close]*100.
Diff2 is (Prjclose7-[close])/[close]*100.
Diff3 is (Prjclose8-[close])/[close]*100.
Diff4 is (Prjclose9-[close])/[close]*100.
Diff5 is (Prjclose10-[close])/[close]*100.

!==========================================

! get the standard deviation of the close


variance is Variance(varudf,days).
stddev is Sqrt(Variance).

! Compute our Deviation Bands


UpperSD is 2 * StdDev + Intercept.
LowerSD is Intercept - 2 * StdDev.

!============================

IntSlope is Slope([Close],days).
Test if 1.

!********************************************************************
**********************************************************_ _Rule
Libraryÿÿ CCodeView$_ _ _

555

You might also like