Welcome! Log In Create A New Profile

Get Earnings and Seasonal Trends - Subscribe Today!

Advanced

Fun with ThinkScript

Posted by robert 
Recursive Studies
September 07, 2018 10:17AM
Hello,

Recently I have constructed a custom study using the thinkscript editor. While it has been successfully used on charts, it seems that it does not work with the ThinkorSwim stock/option scanners and the study alerts. After researching my problem, it appears that my study uses recursion. Being a novice coder, I am uncertain what needs to be done with the code. Any help would gratefully appreciated.


Below is the code for the study:


declare upper;

#FisherTransform
input price = hl2;
input length = 10;

def maxHigh = Highest(price, length);
def minLow = Lowest(price, length);
def range = maxHigh - minLow;
def 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;
def fish = 0.5 * (log((1 + truncValue) / (1 - truncValue)) + fish[1]);

def FTOneBarBack = fish[1];
def FT = fish;

#ChaikinVolatility
input ROClength = 10;

assert(ROCLength > 0, "'roc length' must be positive: " + ROCLength);

def diff2 = high - low;
def avg2 = Average(diff2, 10);

def CV = if avg2[roclength] == 0 then 100 else (avg2 - avg2[roclength]) / avg2[roclength] * 100;

plot up = ftOneBarBack < -2.5 and ft < -2.5 and cv > 500;
plot down = ftOneBarBack > 2.5 and ft > 2.5 and cv > 500;

up.setPaintingStrategy(paintingStrategy.BOOLEAN_ARROW_UP);
up.setDefaultColor(Color.BLUE);
down.setPaintingStrategy(paintingStrategy.BOOLEAN_ARROW_DOWN);
down.setDefaultColor(color.BLUE);

#TAC_ADX
def ADX1 = DMI(length = 3).ADX;
def ADX2 = DMI(length = 4).ADX;
def ADX3 = DMI(length = 5).ADX;
def adxmax = max(max(ADX1, ADX2), ADX3);
def adxmin = min(min(ADX1,ADX2), ADX3);

#Heikin Ashi Candles
def openMA = CompoundValue(1, Average(open, 1), open);
def closeMA = CompoundValue(1, Average(close, 1), close);
def highMA = CompoundValue(1, Average(high, 1), high);
def lowMA = CompoundValue(1, Average(low, 1), low);
def haOpen2 = CompoundValue(1, ( (haOpen2[1] + (openMA[1] + highMA[1] + lowMA[1] + closeMA[1]) / 4.0) / 2.0), open);;
def haClose2 = ((openMA + highMA + lowMA + closeMA) / 4.0) ;;
def haLow = Min(lowMA, haOpen2);
def haHigh = Max(highMA, haOpen2); 

#MACD
def Value2 = MovingAverage(averageType = AverageType.EXPONENTIAL, close, 12) - MovingAverage(averageType = AverageType.EXPONENTIAL, close, 26);
def Avg = MovingAverage(averageType = AverageType.EXPONENTIAL, Value2, 9);
def Diff = Value2 - Avg;

#Ichimoku
def Tenkan = (Highest(high, 9) + Lowest(low, 9)) / 2;
def Kijun = (Highest(high, 26) + Lowest(low, 26)) / 2;
def "Span A" = (Tenkan[26] + Kijun[26]) / 2;
def "Span B" = (Highest(high[26], 2 * 26) + Lowest(low[26], 2 * 26)) / 2;
def Chikou = close[-26];

#SimpleTrendChannelFilter
input trendCheck = {default Min};
def avg20 = Average(close, 20);
def avg50 = Average(close, 50);
def Downtrend3 = close < avg50 and
    (if trendCheck != trendCheck.Min then avg20 < avg50 else yes);
def Uptrend3 = close > avg50 and
    (if trendCheck != trendCheck.Min then avg20 > avg50 else yes);

#HACOLT
Assert(1.1 >= 0, "'candle size factor' must not be negative: " + 1.1);
def haOpen = CompoundValue(1, (haOpen[1] + ohlc4[1]) / 2, ohlc4);
def haClose = (haOpen + Max(high, haOpen) + Min(low, haOpen) + ohlc4) / 4;
def temaHaClose = TEMA(haClose, 55);
def zeroLagHaClose = 2 * temaHaClose - TEMA(temaHaClose, 55);
def temaTypPrice = TEMA(hl2, 55);
def zeroLagTypPrice = 2 * temaTypPrice - TEMA(temaTypPrice, 55);
def shortCandle = BodyHeight() < (high - low) * 1.1;
def keepGreen = haClose >= haOpen or haClose[1] >= haOpen[1] or close >= haClose or high > high[1] or low > low[1] or zeroLagTypPrice >= zeroLagHaClose;
def keepGreenAll = keepGreen or (keepGreen[1] and (close >= open or close >= close[1]));
def holdLong = shortCandle and high >= low[1];
def utr = keepGreenAll or (keepGreenAll[1] and holdLong);
def keepRed = haClose < haOpen or haClose[1] < haOpen[1] or zeroLagTypPrice < zeroLagHaClose;
def keepRedAll = keepRed or (keepRed[1] and (close < open or close < close[1]));
def holdShort = shortCandle and low <= high[1];
def dtr = keepRedAll or (keepRedAll[1] and holdShort);
def upw = !dtr and dtr[1] and utr;
def dnw = !utr and utr[1] and dtr;
def upwSave = if upw or dnw then upw else upwSave[1];
def buy = upw or (!dnw and upwSave);
def longTermSell = close < ExpAverage(close, 60);
def neutral = buy or (if longTermSell then no else neutral[1]);
def HACOLT = if buy then 100 else if neutral then 50 else 0;

#CMF
def tmp_var = 
if high == low then 
  volume 
else 
  (close - low - (high - close)) / (high - low) * volume
;
def sum_close = Sum(tmp_var, length = 21) * 100;
def total = Sum(volume, length = 21);
def CMF = 
if total == 0 then 
  0 
else 
  sum_close / total
;

#Entry Parameters
def upTrend = ohlc4 < "Span A" and ohlc4 < "Span B" and CMF > 0 and Uptrend3 == yes and HACOLT == 100 and Value2 > 0 and Avg > 0 and Diff > 0 and haOpen2 > haLow and haOpen2 < haHigh and adxmin < 30;
def neutral1 = ohlc4 < "Span A" and ohlc4 < "Span B" and CMF > 0 and Uptrend3 == yes and HACOLT == 100 and Value2 > 0 and Avg > 0 and Diff > 0 and haOpen2 == haLow and adxmin < 30;
def neutral2 = ohlc4 < "Span A" and ohlc4 < "Span B" and CMF > 0 and Uptrend3 == yes and HACOLT == 100 and Value2 > 0 and Avg > 0 and Diff > 0 and haOpen2 == haHigh and adxmin < 30;
def downTrend = ohlc4 > "Span A" and ohlc4 > "Span B" and CMF < 0 and Downtrend3 == yes and HACOLT <= 50 and Value2 < 0 and Avg < 0 and Diff < 0 and haOpen2 > haLow and haOpen2 < haHigh and adxmax > 70;
def neutral3 = ohlc4 > "Span A" and ohlc4 > "Span B" and CMF < 0 and Downtrend3 == yes and HACOLT <= 50 and Value2 < 0 and Avg < 0 and Diff < 0 and haOpen2 == haHigh and adxmax > 70;
def neutral4 = ohlc4 > "Span A" and ohlc4 > "Span B" and CMF < 0 and Downtrend3 == yes and HACOLT <= 50 and Value2 < 0 and Avg < 0 and Diff < 0 and haOpen2 == haLow and adxmax > 70;
plot buy1 = upTrend == yes and neutral1[1] == yes;
plot buy2 = upTrend == yes and neutral2[1] == yes;
plot buy3 = upTrend[1] == yes and neutral1 == yes;
plot buy4 = upTrend[1] == yes and neutral2 == yes;
plot buy5 = neutral1 == yes and neutral2[1] == yes;
plot buy6 = neutral1[1] == yes and neutral2 == yes;
plot buy7 = neutral1 == yes and neutral1[1] == yes;
plot buy8 = neutral2 == yes and neutral2[1] == yes;
plot sell1 = downTrend == yes and neutral3[1] == yes;
plot sell2 = downTrend == yes and neutral4[1] == yes;
plot sell3 = downTrend[1] == yes and neutral3 == yes;
plot sell4 = downTrend[1] == yes and neutral4 == yes;
plot sell5 = neutral3 == yes and neutral4[1] == yes;
plot sell6 = neutral3[1] == yes and neutral4 == yes;
plot sell7 = neutral3 == yes and neutral3[1] == yes;
plot sell8 = neutral4 == yes and neutral4[1] == yes;

buy1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy1.SetDefaultColor(Color.LIGHT_GRAY);
buy1.HideTitle();
buy2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy2.SetDefaultColor(Color.LIGHT_GRAY);
buy2.HideTitle();
buy3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy3.SetDefaultColor(Color.LIGHT_GRAY);
buy3.HideTitle();
buy4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy4.SetDefaultColor(Color.LIGHT_GRAY);
buy4.HideTitle();
buy5.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy5.SetDefaultColor(Color.LIGHT_GRAY);
buy5.HideTitle();
buy6.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy6.SetDefaultColor(Color.LIGHT_GRAY);
buy6.HideTitle();
buy7.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy7.SetDefaultColor(Color.LIGHT_GRAY);
buy7.HideTitle();
buy8.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy8.SetDefaultColor(Color.LIGHT_GRAY);
buy8.HideTitle();
sell1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell1.SetDefaultColor(Color.LIGHT_GRAY);
sell1.HideTitle();
sell2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell2.SetDefaultColor(Color.LIGHT_GRAY);
sell2.HideTitle();
sell3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell3.SetDefaultColor(Color.LIGHT_GRAY);
sell3.HideTitle();
sell4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell4.SetDefaultColor(Color.LIGHT_GRAY);
sell4.HideTitle();
sell5.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell5.SetDefaultColor(Color.LIGHT_GRAY);
sell5.HideTitle();
sell6.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell6.SetDefaultColor(Color.LIGHT_GRAY);
sell6.HideTitle();
sell7.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell7.SetDefaultColor(Color.LIGHT_GRAY);
sell7.HideTitle();
sell8.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell8.SetDefaultColor(Color.LIGHT_GRAY);
sell8.HideTitle();

Thanks Again

Ragingmoener



Edited 1 time(s). Last edit at 09/07/2018 10:18AM by ragingmoener.
Re: On Balance Volume
September 09, 2018 10:49AM
Just now adding the code to the OBV, I really appreciate your help, so far it looks a lot more accurate for my entries and exits.
Re: Recursive Studies
September 10, 2018 08:29AM
@ragingmoener,

I believe the reason why your couldn't get your study to work in the scanners is because you are specifying more than one plot statement...if possible, remove all but one plot statement or condense the plot statements into one...

Hope this helps smiling smiley

P.S. - I couldn't get the study to work in a chart
Help to convert study for watchlist
September 12, 2018 05:09PM
would like help to convert study to use in watch list, change color tabs



input length = 13;
input paintBars = yes;

def EMA = ExpAverage(close, length);
def MACD = ExpAverage(close, 12) - ExpAverage(close, 26);
def MACDHist = MACD - ExpAverage(MACD, 9);
def GreenPrice = EMA > EMA[1] and MACDHist > MACDHist[1];
def RedPrice = EMA < EMA[1] and MACDHist < MACDHist[1];

plot Bullish = GreenPrice;
plot Neutral = !GreenPrice and !RedPrice;
plot Bearish = RedPrice;

Bullish.SetDefaultColor(Color.UPTICK);
Bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Bullish.SetLineWeight(3);
Bullish.hide();
Neutral.SetDefaultColor(Color.BLUE);
Neutral.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Neutral.SetLineWeight(3);
Neutral.hide();
Bearish.SetDefaultColor(Color.DOWNTICK);
Bearish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Bearish.SetLineWeight(3);
Bearish.hide();

DefineGlobalColor("Bullish", Color.BLUE);
DefineGlobalColor("Neutral", Color.YELLOW);
DefineGlobalColor("Bearish", Color.RED);
AssignPriceColor(if !paintBars then Color.CURRENT else if GreenPrice then globalColor("Bullish"winking smiley else if RedPrice then globalColor("Bearish"winking smiley else globalColor("Neutral"winking smiley);
Re: Help to convert study for watchlist
September 16, 2018 11:09AM
OptionMaster,

Here you have it
input length = 13;
input paintBars = yes;

def EMA = ExpAverage(close, length);
def MACD = ExpAverage(close, 12) - ExpAverage(close, 26);
def MACDHist = MACD - ExpAverage(MACD, 9);
def GreenPrice = EMA > EMA[1] and MACDHist > MACDHist[1];
def RedPrice = EMA < EMA[1] and MACDHist < MACDHist[1];


Plot scan=close;
assignBackgroundColor(if GreenPrice then Color.lime else if RedPrice then  Color.red else Color.yellow);
scan.assignValueColor(if GreenPrice then Color.black else if RedPrice then  Color.white else Color.black);

Re: Help to convert study for watchlist
September 16, 2018 12:13PM
Thank you Rigel again for your help
NMR
Re: Recursive Studies
September 17, 2018 07:34PM
Hi there- can you please share what this study does and how you use it?
Thank you in advance.
Plot Yesterday's Custom OR on Today's Chart
September 18, 2018 11:59AM
Hello,

Anyone have a thinkscript that plots previous day's customized opening range on current day's chart?

For example, I'm trying to plot yesterday's opening range from 9:00 am to 9:30 am on today's chart.

TIA.
VPCI Indicator by Lazy Bear
September 20, 2018 06:57PM
I have been following this indicator on the /ES via Trading View. It does show some promise. If someone could convert it to TOS that would be excellent!






//
// @author LazyBear
//
// If you use this code in its orignal/modified form, do drop me a note.
//
study("Volume Price Confirmation Indicator [LazyBear]", shorttitle="VPCI_LB"winking smiley
shortTerm=input(5)
longTerm=input(20)

src=close
vpc = vwma(src, longTerm) - sma(src, longTerm)
vpr = vwma(src, shortTerm)/sma(src, shortTerm)
vm = sma(volume, shortTerm)/sma(volume, longTerm)

vpci = vpc*vpr*vm
hline(0)
plot(vpci, color=orange, linewidth=2)

DrawMA = input(true, type=bool, title="Draw MA on VPCI?"winking smiley
lengthMA=input(8, "VPCI MA Length"winking smiley
s=sma(vpci, lengthMA)
plot(DrawMA?s:na, color=teal)

// Uncomment this line to enable histogram
// plot(DrawMA?(vpci-s):na, color=blue, style=histogram)

DrawBands = input(false, type=bool)
HighlightBreaches = input(true, type=bool)
length=input(20, title="BB Length"winking smiley
mult=input(2.5)
bb_s = vpci
basis = sma(bb_s, length)
dev = (mult * stdev(bb_s, length))
upper = (basis + dev)
lower = (basis - dev)

plot(DrawBands?basis:na, color=gray, style=line)
p1 = plot(DrawBands?upper:na, color=gray)
p2 = plot(DrawBands?lower:na , color=gray)
fill(p1, p2, blue)

b_color = (bb_s > upper) ? red : (bb_s < lower) ? green : na
offs_v = 0.3
breach_pos = (bb_s >= upper) ? (bb_s+offs_v) : (bb_s <= lower ? (bb_s - offs_v) : 0)
Breached=(bb_s >= upper) or (bb_s <= lower)
plot(HighlightBreaches and Breached ? breach_pos : na, style=cross, color=b_color,linewidth=3)
Re: VPCI Indicator by Lazy Bear
September 23, 2018 09:20AM
Quote
Sim_Boy
If someone could convert it to TOS that would be excellent!

Try this:


#//
#// @author LazyBear
#//
#// If you use this code in its orignal/modified form, do drop me a note.
#//
#study("Volume Price Confirmation Indicator [LazyBear]", shorttitle="VPCI_LB" )
# Converted to TOS by Rigel 2018.
#
declare lower;
input shortTerm = 5;
input longTerm = 20;
def agg=aggregationPeriod.MIN;
input src = close;
input BBlength = 20; #, title="BB Length"
input mult = 2.5;
def vpc = vwap(period=longTerm*agg) - Average(src, longTerm);
def vpr = vwap(period=shortTerm*agg) / Average(src, shortTerm);
def vm = Average(volume, shortTerm) / Average(volume, longTerm);

plot vpci = vpc * vpr * vm;
vpci.setDefaultColor(color.green);
plot zero=0;
zero.setdefaultColor(color.cyan);

input lengthMA=8 ; #, "VPCI MA Length"
plot MA = Average(vpci, lengthMA);
MA.setdefaultColor(color.pink);

def bb_s = vpci;
plot basis = Average(bb_s, BBlength);
def dev = (mult * StDev(bb_s, BBlength));
plot upper = (basis + dev);
plot lower = (basis - dev);
basis.setdefaultColor(color.white);
basis.setPaintingStrategy(PaintingStrategy.line);
basis.setStyle(curve.SHORT_DASH);

E-Charts Scanner for ToS
September 25, 2018 09:17AM
Hello All! I am sort of new to this forum and would like some help. I am using ToS and would love it if someone could create and post a scanner code for E Signals. Meaning I would be alerted when both the 5 SMA and 10 SMA cross the 20 SMA (either up or down). I have found the formula on here for the charts, but not for the scanner. Hope everyone is having fun out there trading!

Kris
Re: VPCI Indicator by Lazy Bear
September 25, 2018 07:00PM
Thank You Rigel!!
Re: Fun with ThinkScript
September 26, 2018 12:51PM
What's the problem with the script?

input length = 50;
def AverageCandle = Average(Candlesize, length);

I want to get the number from average candle size for a trailing stop.
ThX
Re: Fun with ThinkScript
September 26, 2018 09:06PM
Hi Guys,

I have been racking my brains around this and I can't figure this out. I am trying to write a study that plots open gap lines. If it gaps down and the stock moves up then it changes the bottom line up to match the high of the current candle until the gap fills. I have done this. The problem is that I would like to for it to plot a second and maybe third open gap with different colors. If anyone could please help me I would appreciate it. here is the script I have for the first gap.



input percentIntraDay = 0.1;
input percent = 4;

def p = if GetAggregationPeriod() < AggregationPeriod.DAY then percentIntraDay else percent;
def threshold = close[1] * p / 100;

def UpSignal = low - high[1] > threshold;
def DownSignal = low[1] - high > threshold;

def mostRecent = {default init, up, down};
mostRecent = if UpSignal then mostRecent.up else if DownSignal then mostRecent.down else mostRecent[1];

def topPrice;
def bottomPrice;

def gapEnd =
  if mostRecent[1] == mostRecent.up and low <= bottomPrice[1] then 1
  else if mostRecent[1] == mostRecent.down and high >= topPrice[1] then 1
  else 0;

topPrice = 
  if UpSignal then low
  else if DownSignal then low[1]
  else if gapEnd == 1 then Double.NaN
  else if mostRecent[1] == mostRecent.up then if low < topPrice[1] then low else topPrice[1]
  else topPrice[1];
plot Top = if topPrice > 0 then topPrice else Double.NaN;
Top.SetDefaultColor(Color.YELLOW);
Top.SetPaintingStrategy(PaintingStrategy.DASHES);

bottomPrice =
  if UpSignal then high[1]
  else if DownSignal then high
  else if gapEnd == 1 then Double.NaN
  else if mostRecent[1] == mostRecent.down then if high > bottomPrice[1] then high else bottomPrice[1]
  else bottomPrice[1];
plot Bottom = if bottomPrice > 0 then bottomPrice else Double.NaN;
Bottom.SetDefaultColor(Color.YELLOW);
Bottom.SetPaintingStrategy(PaintingStrategy.DASHES);



Edited 1 time(s). Last edit at 09/26/2018 09:59PM by brazilianpillar.
Re: E-Charts Scanner for ToS
September 28, 2018 04:05AM
Kris

See my answer above to Option master, adapt to your case which is simpler.
Re: Fun with ThinkScript
September 28, 2018 05:40AM
brazilianpillar

Do you want to have the plots for the last 3 days for example, rather than the last gap?
ADX MTF period
September 28, 2018 01:16PM
Hi Rigel, can you please help me converting the ADX STUDY into a MTF study please.

declare lower;

input length = 14;
input averageType = AverageType.WILDERS;

plot ADX = DMI(length, averageType).ADX;
ADX.setDefaultColor(GetColor(5));

it wold be nice to have a period of 5min in a 1 min chart.

Thank you in advance. winking smiley
Hi Rigel, can you please help me converting the ADX STUDY into a MTF study please.
September 28, 2018 01:37PM
Actually you have already done it.!! sorry my bad.
Re: Fun with ThinkScript
September 29, 2018 10:57PM
Hello, could somebody help me with putting multiple times frames on 1 minute chart...not plotting though
For example: I want the 5 minute charts MACD signal line to be above trigger line and I simply want the current MACD Histogram bar to be greater than the last and the Stochastic %K to be greater than %D on the 15 minute 30 minute and 1 hour charts...thanks in advance!!
Re: Fun with ThinkScript
October 02, 2018 01:46AM
I would really appreciate if this is possible and some one can help me with the code.

I'm trying to have a column on my watchlist that turns green if the atm call has a 5 cent spread or less, otherwise it stays gray. I want to add this to what I have 3 other column conditions that I have been able to code, but this last condition I cannot code, is this possible?

Tha k you
Re: Fun with ThinkScript
October 02, 2018 10:24PM
I would like for it to plot the last 3 open gaps
Re: Fun with ThinkScript
October 10, 2018 10:47AM
Does anyone have a script that will calculate Pre Market movement starting at 4:AM and using 4AM as the open price?

I use this but I'm not sure it works right;

# % Pre Market Movement #
Plot PreMarketMovement = ((Highest(High)/open) - (Lowest(low)/open))*100;


Thank you.
Re: Fun with ThinkScript
October 18, 2018 01:00PM
Given my rather limited skills in terms of scripting/programming, I've been trying to construct a trade calculator. As a result, please find below what I have put together so far:

input ATRlength = 10; # default length = 14 - can range anywhere from 6 to 21
def priceC = close;
input averageType = AverageType.WILDERS;
input ATRmultiplier = 1.50; # default multiplier = 2.0 - can range anywhere from 1.0 to 5.0
def ATR = MovingAverage(averageType, TrueRange(high, close, low), ATRlength);
def avgDailyMovement = (ATR / priceC) * 100;
input profitMultiplier = 3.00;

input AccountEquity = 100000.00;
input PercentRiskPerTrade = 0.005;
def EquityRiskPerTrade = AccountEquity * PercentRiskPerTrade;

def SharesToBuy = (EquityRiskPerTrade / (avgDailyMovement * ATRmultiplier));
def currentPositionSize = SharesToBuy * priceC;

def stopAmount = avgDailyMovement * ATRmultiplier;
def longSellStop = priceC - stopAmount;
def shortBuyStop = priceC + stopAmount;

def profitTarget = avgDailyMovement * profitMultiplier;
def longSellLimit = priceC + profitTarget;
def shortBuyLimit = priceC - profitTarget;

AddLabel(yes, "Shares to Buy: " + Round(SharesToBuy, 0), CreateColor (255, 255, 255));
AddLabel(yes, "Position Size: " + Round(currentPositionSize, 2), CreateColor (255, 255, 255));

AddLabel(yes, "Long SELL Stop: " + Round(longSellStop, 2), CreateColor (255, 255, 255));
AddLabel(yes, "Long SELL Limit: " + Round(longSellLimit, 2), CreateColor (255, 255, 255));

AddLabel(yes, "Short BUY Stop: " + Round(shortBuyStop, 2), CreateColor (255, 255, 255));
AddLabel(yes, "Short BUY Limit: " + Round(shortBuyLimit, 2), CreateColor (255, 255, 255));

I'm happy to say it works, just not necessarily as intended to some degree.

Depending on what timeframe I'm on, I get a wide degree of suggested trade numbers to "plug" in to a current trade, as shown below:

Here's the current quote:



5 min Calculator:



Hourly Calculator:



Daily Calculator:



Weekly Calculator:



Monthly Calculator:




The "farther out" you go, the less it suggests to buy and further suggests very wide stops. Whereas, the "closer in" you go, the more it suggests to buy and further suggests very tight stops. Also, depending on the Stock/ETF selected, it will sometimes recommend very large purchases that far exceed the size of the account (AccountEquity)...

Thanks in advance for any help/insights/feedback...
Re: Fun with ThinkScript
October 18, 2018 03:11PM
Hi All,

Glad to have found a thinkscripting community. Recently I have been working on a thinkscript that tracks the highest positive value between any two given negative values on the histogram for MACD however I can't seem to get it to keep track of strictly just the highest positive value between two negative values.

Here is the code I have so far:




declare lower;

input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input averageType = AverageType.EXPONENTIAL;

plot Diff = MACD(fastLength, slowLength, MACDLength, averageType).Diff;

def HA = if Diff > Diff[1] and Diff > 0 then Diff else HA[1];
plot HighestAngle = HA;

Diff.SetDefaultColor(GetColor(5));
Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff.SetLineWeight(3);
Diff.DefineColor("Positive and Up", Color.GREEN);
Diff.DefineColor("Positive and Down", Color.DARK_GREEN);
Diff.DefineColor("Negative and Down", Color.RED);
Diff.DefineColor("Negative and Up", Color.DARK_RED);
Diff.AssignValueColor(if Diff >= 0 then if Diff > Diff[1] then Diff.color("Positive and Up"winking smiley else Diff.color("Positive and Down"winking smiley else if Diff < Diff[1] then Diff.color("Negative and Down"winking smiley else Diff.color("Negative and Up"winking smiley);




Here is a image of what it looks like:





Here is a image of the concept of the points in which I'm aiming for the plotted line to stop going lower (the highest high on the positive side of the histogram between two negative values)



I would be greatly appreciative if anyone is able to help me with this.

Thanks in advance to anyone who is able to help within insight as to where I am going wrong.



Edited 1 time(s). Last edit at 10/18/2018 03:11PM by wolfonkstreet.
Re: Fun with ThinkScript
October 18, 2018 06:47PM
I'd appreciate some help with this code. This code plots lower lows and lower highs and vice versa. I'd like to edit this code and place it on my watchlist column and have the column turn red if a lower high followed by a lower low is plotted and also green when a higher low and higher high is plotted. Is this doable?

input swing_back = 8;
input swing_forward = 2;
input maxbars = 30;
input showlevels = Yes;
def sb = swing_back;
def sf = swing_forward;
def na = double.nan;

def lfor = Lowest(low, sf)[-sf];
def lback = Lowest(low, sb)[1];
def swinglow = if low < lfor and low <= lback then 1 else 0;
plot sl = if swinglow then low else na;
def hfor = Highest(high, sf)[-sf];
def hback = Highest(high, sb)[1];
def swinghigh = if high > hfor and high >= hback then 1 else 0;
plot sh = if swinghigh then high else na;

sh.SetStyle(curve.points);
sh.SetLineWeight(5);
sh.SetDefaultColor(color.white);
sl.SetStyle(curve.points);
sl.SetLineWeight(5);
sl.SetDefaultColor(color.white);

rec lsl = if IsNaN(close[-sf]) then lsl[1] else if swinglow then low else lsl[1];
rec lsh = if IsNaN(close[-sf]) then lsh[1] else if swinghigh then high else lsh[1];

def bn = barNumber();
rec hcount = if swinghigh then 1 else hcount[1] + 1;
rec lcount = if swinglow then 1 else lcount[1] + 1;

plot lasthigh = if hcount<=maxbars AND IsNaN(close[-sf]) then lsh[1] else if hcount > maxbars then na else if hcount < 2 then na else lsh;
plot lastlow = if lcount<=maxbars AND IsNaN(close[-sf]) then lsl[1] else if lcount > maxbars then na else if lcount < 2 then na else lsl;

lasthigh.SetStyle(curve.SHORT_DASH);
lasthigh.SetDefaultColor(color.white);
lasthigh.setHiding(!showlevels);

lastlow.SetStyle(curve.sHORT_DASH);
lastlow.SetDefaultColor(color.white);
lastlow.setHiding(!showlevels);
Set up 233 Chart on TOS?
October 22, 2018 12:23AM
Hi There,

I'm trying to get basics on using ThinkOrSwim charts with the 233 time frame.

I came across this entry which is helpful: [researchtrade.com]

But doesn't cover the basics of setting up a 233 chart in the first place! Maybe someone knows how Nathan got TOS to show 90 days of the 233 chart? I'm stumped!

(At first I thought you'd use the tick option but that doesn't seem right.)

Can anyone give some hints on TOS chart set up basics? Thanks!!

Mel



Edited 1 time(s). Last edit at 10/22/2018 12:23AM by MelCarter.
TCB
Re: Set up 233 Chart on TOS?
October 22, 2018 01:12PM
MelCarter, Hi, I believe if you would right click on the chart and select Style, Timeframe, then under timeframe choose intraday and select the time interval of 180 days with the aggregation period of 233min. This will give you 180 days worth of chart data on the 233 min chart.
Re: Set up 233 Chart on TOS?
October 23, 2018 03:17PM
Yeah it used to be 90 days, but a while back they up'ed it to 180 days.
Re: Fun with ThinkScript
October 28, 2018 10:38AM
Hello everyone!! I am new to register but have been enjoying this forum for well over a year. I am trying to modify a script that uses 2 Keltner channels. I have not been able to parse this study and have it only declare the labels on the top of my screen for kentler channel value and if the trend is above or below said channel. The additional moving averages are not really important. Thanks for your help.


declare weak_volume_dependency;
input showBubble = yes;
input displace = 0;
input factor1 = 1.5;
input factor2 = 3.0;
input length = 26;
input price = close;
input averageType = AverageType.EXPONENTIAL;
input trueRangeAverageType = AverageType.WILDERS;
input showLabel = yes;
input showKBands = yes;
input lineLength = 0;
input showB = yes ;
input BubbleFma = 35;
input Bubblesma = 25;
DefineGlobalColor("upper", Color.dark_green);
DefineGlobalColor("lower", Color.red);
DefineGlobalColor("MA", Color.black);
DefineGlobalColor("Close", Color.blue);
DefineGlobalColor("bubble", Color.cyan);
DefineGlobalColor("upperBubble", Color.green);
DefineGlobalColor("lowerBubble", Color.pink);

def shift1 = factor1 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), length);
def shift2 = factor2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), length);


def average = MovingAverage(averageType, price, length);
plot Avg = average;
avg.SetPaintingStrategy(PaintingStrategy.LINE);
avg.SetDefaultColor(GlobalColor("ma"winking smiley;
avg.setLineWeight(2);



plot UpperBand1 = average[-displace] + shift1[-displace];
UpperBand1.SetPaintingStrategy(PaintingStrategy.line);
UpperBand1.SetDefaultColor(GlobalColor("upper"winking smiley;
UpperBand1.setLineWeight(2);

plot UpperBand2 = average[-displace] + shift2[-displace];
UpperBand2.SetPaintingStrategy(PaintingStrategy.line);
UpperBand2.SetDefaultColor(GlobalColor("upper"winking smiley;
UpperBand2.setLineWeight(2);

plot LowerBand1 = average[-displace] - shift1[-displace];
lowerBand1.SetPaintingStrategy(PaintingStrategy.line);
lowerBand1.SetDefaultColor(GlobalColor("lower"winking smiley;
lowerBand1.setLineWeight(2);

plot LowerBand2 = average[-displace] - shift2[-displace];
lowerBand2.SetPaintingStrategy(PaintingStrategy.line);
lowerBand2.SetDefaultColor(GlobalColor("lower"winking smiley;
lowerBand2.setLineWeight(2);


Def ub1 = upperband1;
Def lb1 = lowerband1;
Def ub2 = upperband2;
Def lb2 = lowerband2;
Def ma = average;

def lastBar = !IsNaN(close) && IsNaN(close[-1]);
def lastClose = if lastBar then close else lastClose[1];
def lastub1 = if lastBar then ub1 else lastub1[1];
def lastlb1 = if lastBar then lb1 else lastlb1[1];
def lastub2 = if lastBar then ub2 else lastub2[1];
def lastlb2 = if lastBar then lb2 else lastlb2[1];
def lastma = if lastBar then ma else lastma[1];


plot KLB1 = if IsNaN(close[-lineLength-1]) then lastLB1 else Double.NaN;
KLB1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
KLB1.SetDefaultColor(GlobalColor("lower"winking smiley;
klb1.setLineWeight(2);
addchartbubble( IsNaN(close[-lineLength-1]) and lastBar and showb,lastlb1," LB1 ",(GlobalColor("lower"winking smiley, if close > ub1 then yes else no);

plot KUB1 = if IsNaN(close[-lineLength-1]) then lastUB1 else Double.NaN;
KUB1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
KUB1.SetDefaultColor(GlobalColor("upper"winking smiley;
KUB1.setLineWeight(2);
addchartbubble( IsNaN(close[-lineLength-1]) and lastBar and showb,lastub1," UB1 ",(GlobalColor("Upper"winking smiley, if close < ub1 then yes else no);

plot KLB2 = if IsNaN(close[-lineLength-1]) then lastLB2 else Double.NaN;
KLB2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
KLB2.SetDefaultColor(GlobalColor("lower"winking smiley;
klb2.setLineWeight(2);
addchartbubble( IsNaN(close[-lineLength-1]) and lastBar and showb,lastlb2," LB2 ",(GlobalColor("lower"winking smiley,no);

plot KUB2 = if IsNaN(close[-lineLength-1]) then lastUB2 else Double.NaN;
KUB2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
KUB2.SetDefaultColor(GlobalColor("upper"winking smiley;
KUB2.setLineWeight(2);
addchartbubble( IsNaN(close[-lineLength-1]) and lastBar and showb,lastub2," UB2 ",(GlobalColor("Upper"winking smiley,if close < ub2 then yes else no);


plot KMA = if IsNaN(ma[-lineLength-1]) then lastMA else Double.NaN;
KMA.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
KMA.SetDefaultColor(GlobalColor("MA"winking smiley;
kma.setLineWeight(2);
addchartbubble( IsNaN(close[-lineLength-1]) and lastBar and showb,lastma," MA ",(GlobalColor("bubble"winking smiley,yes);


plot clPrice = if IsNaN(close[-lineLength-1]) then lastClose[-lineLength] else Double.NaN;
clPrice.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
clPrice.SetDefaultColor(GlobalColor("close"winking smiley;
clPrice.setLineWeight(2);
addchartbubble( IsNaN(close[-lineLength-1]) and lastBar and showb,lastclose," Close ",(GlobalColor("close"winking smiley, if close > lb1 then yes else no );

AddLabel(showLabel, " Keltner = (" + length + " " +
" (" + factor1 + " " + " UB = (" + Round( ub1, 1) + " " + " LB = (" + Round(lb1, 1) + " " + " MA = (" + round(kma,1) + " " , if close > average then Color.dark_GREEN else if close < average then Color.RED else if close > ub1 or close < lb1 then Color.ORANGE else color.black);

AddLabel(showLabel, " Keltner = (" + length + " " +
" (" + factor2 + " " + " UB2 = (" + Round( ub2, 1) + " " + " LB2 = (" + Round(lb2, 1) + " ", if close > average then Color.dark_GREEN else if close < average then Color.RED else if close > ub2 or close < lb2 then Color.ORANGE else color.black);





Def Alert = close > ub2 or close < lb2;
alert(alert, " Price extreme alert! ", alert.BAR, sound.Ring);
Re: Fun with ThinkScript
October 30, 2018 09:45AM
Hey Robert. I bought your Wolfe wave months ago and I have been loving it. I wanted to ask if there is a way to add a strategy to the script?
Sorry, only registered users may post in this forum.

Click here to login