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 =val([close],1)). RedBar if ([close] 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 !
[email protected] 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) = {position entry price} * losslimit or [low] 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 4. BigMover if avgrat>8. List if 1=1.
MOMENTUM !
[email protected] 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]=minprice.
16
! check for minimum volume volumefilter if [Volume ESA] > minvolume. phasereverse if val([phase],1)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]1.5 and MaxProfitR1.6 and MaxProfitR1.7 and MaxProfitR1.8 and MaxProfitR1.9 and MaxProfitR2.0,Stop6,0)))))). LossStop if [close]=20. MasterExit if ProfitProtect or LossStop
19
BUY FOR STOCKS IN A SECTOR !Scan for DTUniversity Price if [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) ===================================== > 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 biotech Semi
if GroupSym = "medic1". ! AIQALL list uses medic1 for 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. semiconductors or biotechs
! Only want symbols from
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)) 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)) 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) AND RSI(9) 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 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 25 AND (BarsSince(Cross(45,ADX(periods))) > BarsSince(Cross(ADX(periods),25)))) OR (ADX(periods) > 10 AND Ref(ADX(periods),-4)0)), 1, If(ADX(periods)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)RMTA:=(1-Alpha)*(If(Cum(1) (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)RMTA:=(1-Alpha)*(If(Cum(1) (Alpha*(C+Bot-Ref(Bot,-1))); >TOSC:=RMTA-Mov(C,lb,E); >TOSC; > Best wishes, > Adam Hefner. e-mail:
[email protected]
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)RMTA:=(1-Alpha)*(If(Cum(1) (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)RMTA:=(1-Alpha)*(If(Cum(1) (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)RMTA:=(1-Alpha)*(If(Cum(1) (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)RMTA:=(1-Alpha)*(If(Cum(1) (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:
[email protected]
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= 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
[email protected] 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)/(HL),,ref(fml(#17),-1),1, if(fml(#17),,ref(hhv(H,100),-1),1,if(L,,ref(hhv(H,40),-1),1, if(L,, 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,, mov(C,20,E), {then bullish} +1, {else bearish} -1) 24 STOCHASTIC VALUE WAVE if(ref(stoch(14,3),-1),, 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,,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(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,%),-2); TR:=Zig(C,10,%)>Ref(Zig(C,10,%),-1) AND Ref(Zig(C,10,%),1).96 AND ValueWhen(1,PK,Ref(C,-1)) / ValueWhen(2,PK,Ref(C,-1))=10 AND Cross(ValueWhen(1,TR,Ref(C,-1)),C) Double Bottoms PK:=Zig(C,10,%)Ref(Zig(C,10,%),-2); TR:=Zig(C,10,%)>Ref(Zig(C,10,%),-1) AND Ref(Zig(C,10,%),1).96 AND ValueWhen(1,TR,Ref(C,-1)) / ValueWhen(2,TR,Ref(C,-1))=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
[email protected]. 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) 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 (LRef(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" } Shark Pattern Symmetry:=.28; Apex:=(H+L)/2; WB:=Ref(H,-2)-Ref(L,-2); If((HRef(L,-1) AND Ref(H,-1)Ref(L,-2)), If(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, when yesterday's (close moving average) Ref(H,-1) AND L>Ref(L,-1)) < BarsSince(LRef(L,-1)) AND (Ref(H,-1)>Ref(H,-2) AND Ref(L,-1)>Ref(L,-2))) < BarsSince((LRef(L,-2)), without the "=1"} If(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((HRef(L,-1) AND Ref(H,-1)Ref(L,-2)), If(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) 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) 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())15)90)Mov(V,200,S)*2
CONSOLIDATION OVER 16 WEEKS Col A: CLOSE Filter 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(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(CLOSE,=,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,%)5
Filter enabled: Yes
BIGGEST LOSERS Col A: CLOSE Col B: ROC(C,5,%) Filter: (ROC(C,5,%)>10 OR ROC(C,5,%)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(dw0,1,If(Mt,0) AND When(colE,.2 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,,0)AND When(CLA,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,0 AND ROC(Mov(C,60,E),1,%)>0
EXIT LONG: (ROC(Mov(C,12,E),1,%)0) OR (ROC(Mov(C,12,E),1,%)>0 AND ROC(Mov(C,60,E),1,%)= (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) Ref(Peak(1,H,1) ,-1),
115
{then}1, {else}If(CLOSE 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(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 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 OO AND CRef(C,-1) AND CRef(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")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()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(Mt0, 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()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()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 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(CLOSERef(H,-1),2)=2); Ds:=BarsSince(Sum(L 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,Sd20,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(L0,Tv), {then}-1, {else}0)); {UpTrend=1 DownTrend =-1} Tdv:=ValueWhen(1,Td0,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()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((Lv1Lc) AND (Lv2Lc), {then}1, {else}0), {else}If(Ds=0, {then}If((Hv1Hc) AND (Hv2Hc), {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,Sd20,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(L0,Tv), {then}-1, {else}0)); {UpTrend=1 DownTrend =-1} Tdv:=ValueWhen(1,Td0,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 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 GapIncrement, If(CLOSE = 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 GapIncrement),0)); If(LookingForGapUp, Cum(If(Gap >= MinGap AND Gap < MinGap + GapIncrement, If(LOW = 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 - 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
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(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(CLOSE,=,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.
[email protected] 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 70day 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) /Mov(If(P-Ref(P,-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} HRef(HHV(H,N1),-1) OR Cum(1)=LastValue(Cum(1))
154
{SELL} N1:=5; HRef(HHV(H,N1),-1) OR Cum(1)=LastValue(Cum(1)) {Exit Long} N2:=3; C with Trough(1,RSI(14),.8) AND Ref(CLOSE,-1)-80) AND (Ref(CCI(11),-1)= HHV(RSI(9),19) AND CLOSE = HHV(CLOSE,19) AND RSI(9) 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)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) 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()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
[email protected]
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
[email protected]
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(H,-2) AND Ref(L,-5) ,.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
[email protected]. 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))=up, OPEN-CLOSE, If(gap-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-(HL))) 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)),((HL)+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=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(BdyThBotB AND BdyThTopB,112,0))+ If(C0 AND UshdThbotU AND UshdThTopU,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(C,-8)) AND (Ref(L,2)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
[email protected]
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(Abs((Mo(opt3))),opt4,E),1))
enter short When(Mov( Mid(C, opt1) ,opt1,E),= ,(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 breakalways 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 LOWRef(LOW,-1)-LOW, HIGH-Ref(HIGH,-1), 0)); DIPlus:= 100 * Wilders(PlusDM,Periods) / ATR(Periods); MinusDM:= If(LOW 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 = PREV, {then} ( H - 3*ATR(10) ), {else} PREV), {else (L = PREV, {then} ( C - 2.5*ATR(10) ), {else} PREV), {else (L 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.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 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(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(CLOSE,=,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.
[email protected] 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 70day 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) /Mov(If(P-Ref(P,-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} HRef(HHV(H,N1),-1) OR Cum(1)=LastValue(Cum(1)) {SELL} N1:=5; HRef(HHV(H,N1),-1) OR Cum(1)=LastValue(Cum(1)) {Exit Long} N2:=3; C with Trough(1,RSI(14),.8) AND Ref(CLOSE,-1)-80) AND (Ref(CCI(11),-1)= HHV(RSI(9),19) AND CLOSE = HHV(CLOSE,19) AND RSI(9) 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)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) 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()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. 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 50.0 and previous day's StochRSI-14 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) 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 MNN:=If(Er=0,N,If(Er=1 AND M >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 by Spyros Raftopoulos Review of () -----------------------------------------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(No0,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(Xo0 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)1 AND (Alert(Tr,2) OR (Nd+Xd1 AND (Max(No,Xo)>4 OR NoXo))),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 0,Bt,0)); Xd:=Cum(If((Ex OR Lb) AND N0; 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(No0,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(Xo0 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)1 AND (Alert(Tr,2) OR (Nd+Xd1 AND (Max(No,Xo)>4 OR NoXo))),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(No0,Bt,0)); Xd:=Cum(If((Ex OR Lb) AND N0; 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(No0,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(Xo0 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)1 AND (Alert(Tr,2) OR (Nd+Xd1 AND (Max(No,Xo)>4 OR NoXo))),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 0,Bt,0)); Xd:=Cum(If((Ex OR Lb) AND N0;
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(No0,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(Xo0 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)1 AND (Alert(Tr,2) OR (Nd+Xd1 AND (Max(No,Xo)>4 OR NoXo))),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 0,Bt,0)); Xd:=Cum(If((Ex OR Lb) AND N0; 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(Xa0,2)) OR (Tr-1)=1 OR Tr0,Abs(Tr)); Cp:=If(Xb,If(Xa=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(Cp0,If(Tr0,C,If(Xa=1 AND Xo0 AND Xo0 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(Xa0,2)) OR (Tr-1)=1 OR Tr0,Abs(Tr)); Cp:=If(Xb,If(Xa=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(Cp0,Min(H,Max(If(Tr0,C,If(Xa=1 AND Xo0 AND Xo0 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)-1)=1; Tr:=BarsSince(I OR N)-1)=1; Tr:=If(BarsSince(I OR N)BarsSince(I OR X),0,1); The difference is in the use of “=” with “>” or “=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 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
[email protected] 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-BC, 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; { = 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); missing! } end; end;
{ IMPORTANT -- infinite loop if this is
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
[email protected] } 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
[email protected] } 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 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,
[email protected]
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]=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 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 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 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 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 >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" To: "Omega List" 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 > 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,
[email protected] wrote: >In a message dated 4/20/01 9:18:46 AM Pacific Daylight Time, >
[email protected] writes: > >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 xprice0 then exitlong("lx1") next bar at xprice - 30 points stop; if mp = -1 and xprice0 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 (@TextCurrentC0x1000 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" To: "Jon Macmichael" ; "omega" 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:
[email protected]] > > 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" To: 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:
[email protected] >
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 {#OptVar7 {#OptVar5 {#OptVar4 {#OptVar1
Default: Default: Default: Default: Default:
-30} 30} 1} 5} 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 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 -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) 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 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] 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] 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 85 and (absvalue(value2-value1) 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 value9885 and (absvalue(value50-value51) 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 85 and (absvalue(value2-value1) 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) 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) 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 (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)) 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 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)) slowD(21)); if value980 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)) 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)) 85 and XPermk(length,x,password)>85 and ((XPermd(length,x,password)-XPermk(length,x,password)) > 2); condition13 = XPermk(length,x,password) 0 then TrK = (Value3 - Value1) / Value2 * 100 Else TrK = 0;
If CurrentBar 85 and (absvalue(value2-value1) 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)) 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 if value80 < p2 then value80 = p2; XDev = Value80 - XRev(s1,l1,p1,p2,p3,password); end; If oscl 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 CloseHigh[1] then SlamDayDn=1 else SlamDayDn=0;
418
PctR=PercentR(PctRLen); PCTR5=PctR[3]; If CloseClose[5] then UpClose=UpClose+1 Else UpClose=0; KRFake= High>High[1] and Low>Low[1] and CloseOpen[1]; KRFakeFail=KRFake[1] and High High[1] and CloseClose[5] ; ExtremeDn=Close=High[5] and ClosePctr[1]; PctRDn=PctR 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 OverBght and REIval[1] 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 = +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 = loChannel then chavot = +1 ; If Close < loChannel then chavot = +2 ; ReiValCond1= REIval >= OverSold and REIval[1] < OverSold; ReiValCond2= REIval 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 < If Value1 < 1 and Value2 >= end; If CurrentBar > 1 then begin If Value1 < 1 and Value2 >= If Value1 >= 1 and Value2 < End;
1 then Buy on close; 1 then ExitLong; 1 then Sell on close; 1 then ExitShort;
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 :
[email protected]} {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)= perc ,tr,0); tr:=If( tr=0, ValueWhen(1,tr0,tr), tr); pk:=ValueWhen(1,Zig(C,perc,%)Ref(Zig(C,perc,%),-2),Ref(Zig(C,perc,%),-1)); pk:=If((C-pk)*100/pk I forgot to add fml("rel") which is simply c/p. Sorry for the > inconvenience. > > --- In torontometastockusers@y..., "morluk2000" > 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> > > 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") > > ("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" 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:
[email protected]] > 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:
[email protected]] > 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 >
[email protected] > ********************************************************************* ****} > > > 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: Line 2: Line 3: Line 4: Line 5: Line 6: Line 7: Line 8: Line 9:
Index = 0; RemainingIncr = Length; while RemainingIncr > 0 begin VolRatio = Volume[Index] / VolIncr; Factor = MinList(VolRatio, RemainingIncr); Sum = Sum + Factor * Price[Index]; RemainingIncr = RemainingIncr - Factor; Index = Index + 1; 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 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 = 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 = 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 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 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 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= Count then begin Plot1(H+.6,"Sell"); zz= PlaySound("e:\pages\high.wav"); end;} If CC[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 DD[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 CalcTime(Sess1FirstBarTime,+5) then begin Med = NuLo + ((NuHi-NuLo)/2); end; If C>Med then UpCntr = UpCntr + 1; If CFastD(7)[1] then begin {Plot1(Low-.2,"JR Buy");} rtp = 1; end; If FastD(45) > 30 or FastD(7)[1] > BB or FastD(7) 70 and FastD(7)[1] >SS and FastD(7) 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:
[email protected] 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 dd[1] then begin NuHi = C; NuLo = C; end; If H>NuHI then NuHi = H; If L 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 ) ; 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 (LOW,"long");} zz= PlaySound("e:\pages\low.wav"); Plot1(H,"H"); Plot2(L,"L"); end;
{RSI}
{plot3
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 ) ; 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 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 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)) 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 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 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) 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 apply to buy just stock is
attention to the economic and business fundamentals that the stock or futures market you are trading. (i.e. don't because a stock is going up and don't sell just because a 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 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 Im0 and Re0 then Period=360/ArcTangent(Im/Re); If Period>1.5*Period[1] then Period=1.5*Period[1]; If Periodplot3[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. Paul Defined "Constdays"
! Set the days to 13 below in the Dale
!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 = xsquared sx is Sum(day,days). sx2 is Sum(dayX2,days). sy is Sum(varudf,days). sy2 is Sum(varudf*varudf,days).
!!!Sum of x !!!Sum of x*x !!!Sum of y
554
sxy is Sum( day * varudf ,days). d is ( days * sx2) - (sx * sx).
!!!sum of x*y
slope is ((days * sxy) - ( sx * sy)) / -d. Slope function b is ((sx2 * sy) - (sx * sxy)) / d.
! same result as internal
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