Site Meter The Lawyer Trader: Thinkscript
Showing posts with label Thinkscript. Show all posts
Showing posts with label Thinkscript. Show all posts

Sunday, December 7, 2014

ThinkScript Indicator: CalmvVolatile

This is a pretty basic stud that compares the current Average True Range (ATR) with a long term average of the ATR.  The default periods are 14 period for the ATR and 500 period for the average.


This indicator can be helpful as a quick reference when taking short term trades.  If the instrument is volatile, you know that there's a better possibility of a quicker and farther move than if it's calm.  Enjoy.  The code is below.


#######Delete this line in TOS#############

input atrlength = 14;

input avglength = 500;

input plotlower = {default "yes", "no"};

def vol = AverageTrueRange(atrlength);

def avgvol = Average(vol, avglength);

def calm = vol < avgvol - (avgvol * .1);

def neutral = avgvol + (avgvol * .1) > vol > avgvol - (avgvol * .1);

def Volatile = vol > avgvol + (avgvol * .1);

AddLabel(yes, Concat("Market is Currently ", (if calm then "Calm" else if neutral then "Neutral" else if Volatile then "Volatile" else "Neutral")),  if calm then Color.GREEN else if neutral then Color.BLUE else if Volatile then Color.RED  else Color.GRAY);

declare lower;

plot window =  vol - avgvol;

window.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);

window.AssignValueColor(if Volatile then Color.RED else if calm then Color.GREEN else if neutral then Color.BLUE else Color.GRAY);

plot zeroline = 0;

######delete this line in TOS##############

Tuesday, June 18, 2013

Thinkscript: The Trend_Fuzz Indicator for Think or Swim

Here is the thinksript code for one of my favorite custom made indicators.  I've used it quite a bit over the last three or four years..now maybe you can get some use out of it as well. Here's a chart of the SPY daily chart with the indicator:


 Here's the code:

###delete this line when pasting into thing or swim###

input ThermoLookBackBars = 50;
input PlotType = {default AdaptiveMovingAverages, Standard};

def HighLowScore = 1000 * ((high - high[1]) / (high[1]) +
(low - low[1]) / low[1]);

#######ATR TrailingStop Code
input trailType = {default modified, unmodified};
input ATRPeriod = 5;
input ATRFactor = 3.5;
input firstTrade = {default long, short};

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def ATRMod = ExpAverage(Max(HiLo, Max(HRef, LRef)), 2 * ATRPeriod - 1);

def loss;
switch (trailType) {
case modified:
    loss = ATRFactor * ATRMod;
case unmodified:
    loss = ATRFactor * AvgTrueRange(high, close, low, ATRPeriod);
}

rec state = {default init, long, short};
rec trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    }
    else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    }
    else {
        state = state.long;
        trail =  close - loss;
    }
}

def BuySignal = Crosses(state == state.long, 0, CrossingDirection.ABOVE);
def SellSignal = Crosses(state == state.short, 0, CrossingDirection.ABOVE);

plot TrailingStop = trail;
TrailingStop.Hide();
####End ATR Trailing Stop Code

def A = Highest(high[1], ThermoLookBackBars);
def B = Lowest(low[1], ThermoLookBackBars);

def FiftyTwoWeekHigh = A;

def FiftyTwoWeekLow = B;

def FiftyTwoWeekScore = 10 * (((high
- FiftyTwoWeekHigh) / FiftyTwoWeekHigh) + 
((low - FiftyTwoWeekLow) / FiftyTwoWeekLow));

def ThermoScore = ExpAverage(HighLowScore + FiftyTwoWeekScore, ThermoLookBackBars);

input FastLengthShort = 5;
input SlowLengthShort = 15;
input EffRatioShort = 10;
input FastLengthLong = 10;
input SlowLengthLong = 25;
input EffRatioLong = 5;

def AMA = MovAvgAdaptive(ThermoScore, FastLengthShort, SlowLengthShort, EffRatioShort);
def AMA2 = MovAvgAdaptive(ThermoScore, FastLengthLong, SlowLengthLong, EffRatioLong);

plot Line1;
Line1.Hide();
plot Line2;
Line2.Hide();

switch (PlotType) {
case AdaptiveMovingAverages:
    Line1 = AMA;
    Line2 = AMA2;
case Standard:
    Line1 = ThermoScore;
    Line2 = ThermoScore;
}

def InvisibleLine = close * 0;
plot Line3 = InvisibleLine;
Line3.Hide();

def Buy = Line1 > 0 and Line2 < 0 and state == state.long;
def StrongBuy = Line1 > 0 and Line2 >= 0 and state == state.long;
def Sell = Line1 < 0 and Line2 > 0 and state == state.short;
def StrongSell = Line1 < 0 and Line2 <= 0 and state == state.short;


AssignPriceColor(if Buy then Color.DARK_GREEN else if StrongBuy then Color.GREEN else if Sell then Color.DARK_RED else if StrongSell then Color.RED else Color.BLUE);

AddLabel(yes, Concat("Current Reading is ", (if Buy then "Up Trend" else if StrongBuy then "Strong Up Trend" else if Sell then "Down Trend" else if StrongSell then "Strong Down Trend" else "Neutral")),  if Buy then Color.DARK_GREEN else if StrongBuy then Color.GREEN else if Sell then Color.DARK_RED else if StrongSell then Color.RED else Color.GRAY);

#######Stochastic Code

declare upper;

input over_bought = 80;
input over_sold = 20;
input KPeriod = 10;
input DPeriod = 10;
input priceH = high;
input priceL = low;
input priceC = close;
input slowing_period = 3;
input smoothingType = {default SMA, EMA};

def lowest_k = Lowest(priceL, KPeriod);
def c1 = priceC - lowest_k;
def c2 = Highest(priceH, KPeriod) - lowest_k;
def FastK = if c2 != 0 then c1 / c2 * 100 else 0;

def FullK;
def FullD;

switch (smoothingType) {
case SMA:
    FullK = Average(FastK, slowing_period);
    FullD = Average(FullK, DPeriod);
case EMA:
    FullK = ExpAverage(FastK, slowing_period);
    FullD = ExpAverage(FullK, DPeriod);
}

def pricefilterup = if close > close[50] then 1 else 0;
def pricefilterdown = if close < close [50] then 1 else 0;

def OverBoughtAdd = if FullK < over_bought and FullK[1] >= over_bought then 1 else 0;
def OverSoldAdd = if FullK > over_sold and FullK[1] <= over_sold then 1 else 0;

def na = Double.NaN;

#Plot arrows
plot up = if StrongBuy and OverSoldAdd  and pricefilterup then low - (3 * TickSize()) else na;
plot down = if StrongSell and OverBoughtAdd and pricefilterdown then high + (3 * TickSize()) else na;
up.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
down.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

###delete this line when pasting into think or swim###

Take care,

TLT

Wednesday, September 19, 2012

DT 2000 Gave a Buy Signal a Month Ago: Here's the Thinkscript Code for the Indicator

The DT 2000 is a trend following indicator that I came  up with about a year ago.  It uses linear regression and it's purpose is to determine the trend of the overall market.  It uses linear regression slope readings on 4 different symbols and its defaults are qqq, xlv, xlf, tlt.  The indicator tends to work well on the weekly time frame..which makes sense because the longer time frames smooth out the choppy price action of equities.

Here's a chart, the DT 2000 is at the bottom and it's coloring the bars on the chart as well:

This indicator is just one more tool in my collection that I look at to help gauge risk and market bias.  I don't necessarily trade this like a system in and of itself--such as buying the SPY or SSO on buy signals.  What this buy signal does for me is it gives me the confidence to put on more long positions, whether the positions are stocks or covered calls or options spreads.  As you can see from the chart, we've had 3 other buy signals in the last 4 years and the buy signals tend to last several months before petering out.  We'll see if this signal has any legs to it.

Here's the thinkscript code for you thinkorswimmers out there:

####DELETE THIS LINE WHEN PASTING INTO TOS####


declare lower;

input symbol1 = "qqq";
input symbol2 = "xlv";
input symbol3 = "xlf";
input symbol4Inverse = "tlt";
input lrlength = 20;

def data1 = close(symbol1);
def data2 = close(symbol2);
def data3 = close(symbol3);
def data4 = close(symbol4Inverse);

def trend1 = linearRegressionSlope(data1, lrlength);
def trend2 = linearRegressionSlope(data2, lrlength);
def trend3 = linearRegressionSlope(data3, lrlength);
def trend4 = linearRegressionSlope(data4, lrlength);

def score1 = if trend1 > 0 then 1 else -1;
def score2 = if trend2 > 0 then 1 else -1;
def score3 = if trend3 > 0 then 1 else -1;
def score4 = if trend4 < 0 then 1 else -1;

plot DT = score1 + score2 + score3 + score4;    

def buysignal = crosses(DT, 0, crossingDirection.ABOVE);
def sellsignal = crosses(DT, 0, crossingDirection.BELOW);  

assignPriceColor(if dt > 0 then color.green else if dt < 0 then color.red else color.blue);


####DELETE THIS LINE WHEN PASTING INTO TOS####


I hope everyone is having a great week so far.

TLT

Saturday, July 14, 2012

Summer Reading: Deemer on Technical Analysis and a TOS Code for His Break Away Momentum Indicator



This summer, I've been reading Walter Deemer's Deemer On Technical Analysis and it has been one of the best technical analysis books that I've read in a really long time.  Mr. Deemer gives his take on using TA for longer term investors and he shy's away from the ultra short term time frames that many modern trading books focus on.  He had a long career as a technical analyst and his book is chock full incredibly interesting and witty observations based on his own experiences from his career.


Deemer  not only breaks down what he feels is useful about TA, he also does a great job of explaining his beliefs on why the TA that he uses works.  You're not going to see pictures of massive charts with multiple indicators and squiggly lines in this book..he keeps his charts to the bare minimum of what he considers useful tools.  This book will likely be the book that I recommend to people when they ask me for a good book that can help them get started with investing/trading or with TA in genearl.  If you haven't read it yet, pick it up or order it for the kindle/ipad.  It's well worth the read.

As a bonus, I coded his Breakaway Momentum indicator for think or swim.  This indicator uses the NYSE advances and declines that are added together for the trailing 10 days and then a ratio is created of advances to declines.  To be breakaway momentum, the reading has to be above a 1.97.  These readings only happen once every 31 and a half years on average.  That being said, we had three in 2009..a bit of an anomaly and a testament to how oversold the market was after the 2008 meltdown.  For more info and historical recordings of breakaway momentum check out Mr. Deemer's website here.

Here's a chart, note TOS has some data issues with advance decline numbers starting in 2009 and going backwards, however, this indicator works well with recent data and you can still see the 3 breakaway readings in 2009..there are just some holes in the data that don't look pretty.



And here is the code for you thinkorswim fans:

####Delete this line when pasting in TOS####


declare lower;

input adv = "$ADVN";
input dec = "$DECN";
input length = 10;

def up = close(adv);
def down = close(dec);

def sumup = sum(up, length);
def sumdn = sum(down, length);

plot ratio = sumup/sumdn;

plot breakaway = 1.97;

####Delete this line when pasting in TOS####


Have a great weekend!

TLT

Saturday, April 28, 2012

General Update and a ThinkScript Code

I almost let an entire month go by without posting...just a sign of how busy (crazy) my world is right now.  Recently, I opened up a Title Company and that has been eating a lot of my time.  Generally, you won't hear me comment on real estate because this blog is about trading, however, the title company is a play on the overall real estate market.  Here in North Texas, real estate is really beginning to pick up.  Real estate agents are seeing lots of activity on the residential side and commercial spaces are filling back up as well.  The title company seemed to be the most direct way to really profit from a rebound.

On the trading side of things, I've been working on a couple of mechanical strategies that are designed to be traded with a basket of commodities.  Nothing too fancy, a simple trend following model and a mean reversion model.  The hard work is in determining how to measure different markets to establish which commodities to include in each system and then how to allocate to each system as a whole.  For example, if my measurements are telling me that volatility is steadily declining and certain commodities are trending, then I may allocate 65% of the overall portfolio to the trend following system and 35% to the mean reversion.  Sounds easy enough, but developing and testing rules is a tedious process.  I'll be providing some posts on this is the future.

Over the past month, I've been in talks with a local hedge fund manager that runs an options trading fund.  He has an interesting strategy that returned about 7% this month...generally he targets 1-2% a month but the volatility in the beginning of April really helped him out.  We are working out a deal that involves a couple of entities partnering up to form a new fund that trades a "Collared Dividend" Strategy.  If this comes together, the new fund looks like it will have $30-50 million to trade by the end of July.  At this point, this might be a pie-in-the-sky dream because there are many working parts that still need to get figured out...but, the thought of managing some institutional money sure is exciting.  

Before I sign off, lets take a quick look at the market.  Below is a chart of S&P 500 via SPY, and it has my Spec Stocks Indicator attached to it.  The premise is pretty simple:  select 6 stocks that are popular and speculative and take a measurement of the trend for each stock.  Then put it together and take an average of them.  These stocks tend to lead the market and be indicative of investors' willingness to take on risk.  Here's the chart:


And for any thinkorswimmers out there, here is the ThinkScript code:

//

declare lower;

input symbol1 = "aapl"; 
input symbol2 = "goog";
input symbol3 = "bidu";
input symbol4 = "cmg";
input symbol5 = "nflx";
input symbol6 = "pcln";
input malength = 200;
input malrlength = 5;
input shortmalength = 50;
input longmalength = 200;

def S1 = close(symbol1, period = "Day");
def S2 = close(symbol2, period = "Day");
def S3 = close(symbol3, period = "day");
def S4 = close(symbol4, period = "day");
def S5 = close(symbol5, period = "day");
def S6 = close(symbol6, period = "day");

def ma1 = ExpAverage(s1, malength); 
def ma2 = ExpAverage(S2, malength);
def ma3 = ExpAverage(S3, malength);
def ma4 = ExpAverage(S4, malength);
def ma5 = ExpAverage(S5, malength);
def ma6 = ExpAverage(S6, malength);

def MALR1 = linearRegressionSlope(ma1, malrlength);
def MALR2 = linearRegressionSlope(ma2, malrlength);
def MALR3 = linearRegressionSlope(ma3, malrlength);
def MALR4 = linearRegressionSlope(ma4, malrlength);
def MALR5 = linearRegressionSlope(ma5, malrlength);
def MALR6 = linearRegressionSlope(ma6, malrlength);

def MALRMAShort1 =expAverage(MALR1, shortmalength);
def MALRMAShort2 =expAverage(MALR2, shortmalength);
def MALRMAShort3 =expAverage(MALR3, shortmalength);
def MALRMAShort4 =expAverage(MALR4, shortmalength); 
def MALRMAShort5 =expAverage(MALR5, shortmalength); 
def MALRMAShort6 =expAverage(MALR6, shortmalength); 

def MALRMALong1 = expAverage(MALR1, longmalength); 
def MALRMALong2 = expAverage(MALR2, longmalength);
def MALRMALong3 = expAverage(MALR3, longmalength);
def MALRMALong4 = expAverage(MALR4, longmalength);
def MALRMALong5 = expAverage(MALR5, longmalength);
def MALRMALong6 = expAverage(MALR6, longmalength);

Def BuySell1 = if MALRMASHORT1 > MALRMALong1 then 10 else -10;
Def BuySell2 = if MALRMASHORT2 > MALRMALong2 then 10 else -10;
Def BuySell3 = if MALRMASHORT3 > MALRMALong3 then 10 else -10;
Def BuySell4 = if MALRMASHORT4 > MALRMALong4 then 10 else -10;
Def BuySell5 = if MALRMASHORT5 > MALRMALong5 then 10 else -10;
Def BuySell6 = if MALRMASHORT6 > MALRMALong6 then 10 else -10;

plot SpecScore = buySell1 + buysell2 + buysell3 + buysell4 + buysell5 + buysell6;

plot zeroline = 0;

assignPriceColor(if specscore > 0 then color.green else if specscore < 0 then color.red else color.blue); 
//

Have a great weekend.

TLT

Wednesday, February 15, 2012

Stock Market Still in an Uptend..despite what the financial news says

I think most traders and investors too, eventually realize that at a minimum, financial news needs to be taken with a grain of salt and more likely just needs to be ignored all together.  I've started seeing the bearish headlines and concerning stories pop up but when I pull up my charts, all I see is a nice trend that is taking a much needed breather.  Here's the S&P:

I believe Jesse Livermore said something to the effect of he learned to make big money by sitting on his hands..something like that.  What he meant was that timing every wiggle of the market is generally a losers game...the big money is finding a trend and then riding it until it's done.  As you can see from the chart above, my system says the trend is still up, so I'm staying long with stock..plain and simple.

On a separate note, I stumbled across this blog today http://share-tos.blogspot.com/.  It is filled with all sorts of ThinkorSwim codes that the authors share.  If you're into tos, it might behoove you to go spend some time at the blog..I know I will.

TLT

Monday, December 26, 2011

ID/NR4 Bars and Thinkscript

Linda Bradford-Raschke, Laurence Connors, Tony Crabel and many other professional traders have referenced narrow range bars as part of there trading setup arsenal.  LBR likes the ID/NR4 which stands for Inside Day Narrowest Range in 4 days.  That means the high and low of the bar have to be within the prior bar (an inside day) and the overall range itself has to be the narrowest in the last 4 bars.

Referenced in many books authored by the above mentioned traders, ID/NR4 and NR4 bars provide a low risk high reward trade setup.  The setup generally involves trading the break out above or below the ID/NR4 bar and placing a stop at the other side.  Then trail a stop for another bar or two.  LBR stresses that in the event your initial stop gets hit, you should stop and reverse so that you are now in the trade in the other direction.  She states that this is important because many of the moves can be false break outs but the move in the opposite direction can be very powerful after a false break out.  Regardless, these setups do allow for very tight stops and can provide some very good short term edges.  Adding some additional research such as current trend direction if any (Crabel does a lot of this research) or monitoring an opening range break out after a NR4 day (Crabel does this as well) or using some volume analysis can all help you filter NR4 or ID/NR4 bars for even higher probability trades.

Here's a chart, note the blue dots above bars indicate an ID/NR4 bar:

And for those of you on ThinkorSwim, here is the thinkscript:

###DELETE THIS ROW WHEN PASTING INTO TOS###


# ID/NR4 Bars
#
def range = high – low;
def na=double.nan;

def plotter=high+range*0.3;

def longvol = volatilityStdDev(100);
def shortvol = volatilityStdDev(6);

def volratio = shortvol/longvol;

def isnr4 = (range <= range[1] and range <= range[2] and range <= range[3] and range and high<high[1] and low>low[1]);

plot lowvol = if volratio<.5 and isnr4 then low-.0005 else double.nan;

lowvol.SetDefaultColor(color.violet);
lowvol.setstyle(curve.points);
lowvol.setlineWeight(3);

plot nr4 = if isnr4 then plotter else na;

nr4.SetDefaultColor(Color.yellow);
nr4.setstyle(curve.points);
nr4.setlineWeight(3);

###DELETE THIS ROW WHEN PASTING INTO TOS###

This code was adopted from a code for NR7 bars written by ReadtheProspectus at his blog with the same name.  If you like thinkscript it would be well worth it to spend some time at his blog.

Happy Holidays!

TLT

Sunday, November 27, 2011

ThinkorSwim Indicator: Multi-Time Frame Stochastics

Here's a code for a multi time frame stochastic.  This will allow you to plot a stochastic for any time frame that is greater than the one that your chart is currently on.  For example, it can be helpful to know what the hourly stochastic looks like if you're trading on a 5 min chart.  I'm playing around with using this a filter for mean reverting systems..such as ignore a "Buy Signal" if the stochastic on a higher time frame is over 60.  Here's an example of using the 15min stochastic with a 1 minute chart:

Here's the code.  To use this code, copy and paste it into TOS and then delete the // marks at the top and bottom.  These marks are necessary for posting the code on blogger and the indicator will not work in TOS if you don't delete them. 

Hope everyone had a great Thanksgiving!

TLT

//

declare lower;

input aggregationPeriod = AggregationPeriod.DAY;
input KPeriod = 10;
input DPeriod = 10;
input slowing_period = 3;

plot FullK = Average((close(period = aggregationPeriod) - Lowest(low(period = aggregationperiod), KPeriod)) / (Highest(high(period = aggregationperiod), KPeriod) - Lowest(low(period = aggregationperiod), KPeriod)) * 100, slowing_period);
plot FullD = Average(Average((close(period = aggregationPeriod) - Lowest(low(period = aggregationperiod), KPeriod)) / (Highest(high(period = aggregationperiod), KPeriod) - Lowest(low(period = aggregationperiod), KPeriod)) * 100, slowing_period), DPeriod);

//

Thursday, September 8, 2011

Index Trader Indicator for Think or Swim: Using Volume, Advance/Decline and Cumulative Tick for Day Trading

I've been playing around with a day trading indicator.  It consists of the ratio of advancing stocks to declining stocks (on the NYSE), Up volume vs. Down volume (NYSE) and the cumulative tick (also NYSE).  Basically, if advancing stocks are above declining and the UpVolume for the day is higher than the down volume, this indicator will show you that the market is bullish.  To filter these signals, I use the cumulative tick.  If the tick lines up with the other two then the bars are painted green (when bullish) or red (when bearish).  If the tick conflicts with the other indicators, the bar will be painted blue.  Check out a five minute SPY chart:

This indicator is useful for day trading, as it can help you determine where the market internals are pushing the market and get you on board with the trend as it's developing intra-day.  This indicator should not be used all by itself for entries and/or exits.  It is not perfect, as there are plenty of times when the bars are green and prices just drop.  I have been playing with it more as a filter.  For example, if I'm trading using bollinger bands, I will look for long intra-day setups when the bars are green.  Or if I'm looking to fade rallies using a stochastic oscillator, I'll look to sell an over bought signal if the bars are red.  There are lots of possibilities to incorporate this and tweak it to your liking.

Here is the think script code for think or swim if anyone out there uses TOS.

//
def VolUp = close("$UVOL");
def VolDn = close("$DVOL");

def advancers = close("$ADVN");
def decliners = close("$DECN");

def BullVol = if volup>voldn then 1 else 0;
def BullAdv = if advancers>decliners then 1 else 0;
def BearVol = if volup<voldn then 1 else 0;
def BearAdv = if advancers<decliners then 1 else 0;

def BullMode = if BullVol and BullAdv then 1 else 0;
def BearMode = if BearVol and BearAdv then 1 else 0;

def upper = no;
input hidecumtick = yes;
input symbol = "$TICK";
input period = 20;
input smooth = 5;
input lookback = 4;
input filter = 300;
def p = period;
def i = barNumber();
def na = double.nan;
#input usetrend = {"No", default "Yes"};
def usetrend = yes;
rec htick = if IsNaN(high(symbol)) then htick[1] else high("$TICK") ;
rec ltick = if IsNaN(low(symbol)) then ltick[1] else low("$TICK");
rec avgh = if i == 1 then htick else Max(filter, avgh[1] + 2 / (p + 1) * (htick - avgh[1]));
rec avgl = if i == 1 then ltick else Min(-filter, avgl[1] + 2 / (p + 1) * (ltick - avgl[1]));


def hi = high("$TICK");
def lo = low("$TICK");

def Last = if IsNaN(close(symbol)[-1]) then close(symbol) else double.nan;

def amean = if IsNaN(close) then na else (avgh + avgl) / 2;
def trendmean = if usetrend AND (htick > avgh OR ltick < avgl) then amean else 0;

def bull = if htick > avgh then htick - avgh  else 0;
def bear = if ltick < avgl then ltick - avgl  else 0;

rec ctick = if i == 1 then 0 else if IsNaN(htick) OR IsNaN(ltick) then ctick[1] else ctick[1] + bull + bear + trendmean; 

def ctickavg = ExpAverage(ctick, smooth);
def cumtick = if IsNaN(close) then na else ctickavg;
def nettick = if IsNaN(close) then na else ctick;

def zero = 0;

AssignPriceColor(if !upper then color.current else if cumtick > cumtick[lookback] AND ltick < avgl then color.green else if cumtick > cumtick[lookback] then color.gray else if cumtick < cumtick[lookback] AND htick > avgh then color.red else color.gray);

def hcumtick=if !hidecumtick then cumtick else na;
def hzero=if !hidecumtick then zero else na;
AddCloud(hcumtick, hzero );
def buy = if cumtick > cumtick[lookback] AND ltick < avgl then low - tickSize() else if cumtick > cumtick[lookback] then na else if cumtick < cumtick[lookback] AND htick > avgh then na else na;
def sell = if cumtick > cumtick[lookback] AND ltick < avgl then na else if cumtick > cumtick[lookback] then na else if cumtick < cumtick[lookback] AND htick > avgh then high + tickSize() else na;

def ahi = if IsNaN(close) then na else avgh;
def alo = if IsNaN(close) then na else avgl;
def hib = if hi < 0 then hi else na;
def lob = if lo > 0 then lo else na;
def phi = hi;
def plo = lo;

#plot zero=0;
#
# Formatting:

Def TickBull = (if cumtick > cumtick[lookback] then 1 else 0);

assignPriceColor(if BullMode and TickBull then color.Green else if BearMode then color.red else color.blue);
//


That's all folks.  I have been working on quite a few indicators and strategies lately and would be happy to share more code if there is enough interest/demand.  We'll see.  Hope everyone's trading is going well.

TLT

*****Update*****
The above code has been fixed.  A reader alerted me to a problem with the coding from the original post..not sure what happen but it appears to be a copy/paste error.  The new code should work much better