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

Tuesday, April 3, 2018

Think or Swim Indicator -- Fisher Scalper Color Bars with Thinkscript

I've got a whole bank of indicators and strategies that I've coded over the years for think or swim and have decided to start randomly posting them along with the codes.  They'll be posted weekly for the next month or two..depends how many good ones I decide are worth posting.

Here's the first and it's an indicator.  The Fisher Scalper Color Bars.  Based on the fisher transform, this indicator is pretty easy to comprehend.  The bars are colored Green (bullish), Yellow (transition from bull to bear), Red (bearish), Blue (bearish transitioning to bullish).

I've played around with this indicator by using it on a higher time frame, like a one hour chart, as seen below, and then taking signals on a lower time frame chart (5m or 15m) in the direction of the trend based on the indicator.

Here's a chart:



Enjoy!

George
(TLT)

Here's the thinkscript code.

***delete this line***
declare lower;

input price = hl2;
input length = 10;

def maxHigh = Highest(price, length);
def minLow = Lowest(price, length);
def range = maxHigh - minLow;
rec value = if IsNaN(price)
    then Double.NaN
    else if IsNaN(range)
        then value[1]
        else if range == 0
            then 0
            else 0.66 * ((price - minLow) / range - 0.5) + 0.67 * value[1];
def truncValue = if value > 0.99 then 0.999 else if value < -0.99 then -0.999 else value;
rec fish = 0.5 * (log((1 + truncValue) / (1 - truncValue)) + fish[1]);

plot FTOneBarBack = fish[1];
plot FT = fish;
plot ZeroLine = 0;

input emalength = 50;

plot ema2 = expAverage(fish, emalength);

FTOneBarBack.SetDefaultColor(GetColor(1));
FT.SetDefaultColor(GetColor(8));
ZeroLine.SetDefaultColor(GetColor(5));

def bullish = if ft > ema2 then 1 else 0;
def bearish = if ft < ema2 then 1 else 0;

assignpriceColor(if ft>ftonebarback and bullish then color.green else if ft>ftoneBarBack and bearish then color.blue else if ft<ftoneBarBack and bearish then color.red else if ft<ftOneBarBack and bullish then color.yellow else color.gray);

***delete this line***

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