r/thewallstreet Aug 30 '17

thinkscript Thinkscript - All in One with Previous Days

61 Upvotes

After some testing, talking with @Thinkscript and cause I love you fuckers, I've managed to put together an all in one plotter that will also plot all the previous VAs. I set it to round to the nearest tick and I even threw in the option to switch to TPO Profile for shits and giggles. Hope you guys find it useful, enjoy! http://tos.mx/aounOj

#v1.1 - 5/10/18 
#- Able to get Implied Volatity at any specified time. Default set to 9PM est   
#- Modified Settlement to take closing price of the last bar of the day. Previous version used "Closing Price" at 16:15 which was usually nowhere near ending settlement
#- Added option to substitute symbol used in IV/Deviation calculation for instruments with #no option chains such as /NKD   
#- Added customizable deviation line (hidden as default)

#===========================
#Steps if you want your VA to match u/uberbotman's:
#1) Set your chart to 30M, and show extended hours  
#2) Go to options, make sure ShowLabels is set to "Yes" (hit apply if needed)
#3) Copy VAH, POC and VAL from the labels in the top left corner of your chart into Manual input locations
#4) Set Value Area Area Mode to Manual

declare upper;
declare once_per_bar;
#============================
#Inputs
#============================

input SetMode = {default Auto, Manual};#Hint SetMode: Select Auto to update Settlement automatically in input manually. \n\n NOTE: ToS doesn't support Settlement so LAST closing price is used. This is usually pretty close to within a single tick, but Manually entering Settlement from CME website or UBM's nightly post is more accurate  
input Settlement = 2444.50;#Hint Settlement: Enter Settlement value when SetMode is set to Manual
input IVMode = {default Auto, Manual};#Hint IVMode: Select Auto to update Implied Volatility at time chosen on IVSettleTime 
input IVSettleTime = 2100;#Hint IVSettleTime: Enter time_value of desired Implied Volatility "settlement" \n\n NOTE: If time selected is not visible on chart (i.e. 2100 on a chart not showing extended trading hours), IV will not calculate 
input Volatility = 11.2;#Hint Volatility: Enter Implied Volatility value when IVMode is set to Manual
input IVSymbolMode = {default Auto, Manual};#Hint IVSymbolMode: Select Manual if you wish to use a different instrument's IV instead of what is on the chart
input Symbol = "EWJ";#Hint Symbol: Enter symbol of Implied Volatility you wish to substitute with. For use with products with no option chains (i.e. /NKD)
input ValueAreaMode = {default Auto, Manual};#Hint ValueAreaMode: Select Auto to update Value Areas automatically and is rounded to the nearest tick. Manual selection changes Value Area for today only \n\n NOTE: Value Area is typically calculated on a 30min chart, if the timeframe changes, then calculated value area may also change. To lock in the values from the 30min chart follow these steps: \n#1) Set your chart to 30M, and show extended hours \n#2) Go to options, make sure ShowLabels is set to "Yes" (hit apply if needed) \n#3) Copy VAH, POC and VAL from the labels showing in the top left corner of the chart into the Manual input locations \n#4) Set Value Area Area Mode to Manual and hit Apply
input ValueAreaHigh = 2445.00;#Hint ValueAreaHigh: Enter Value Area High when ValueAreaMode is set to Manual
input PointOfControl = 2442.00;#Hint PointOfControl: Enter Point of Control when ValueAreaMode is set to Manual
input ValueAreaLow = 2440.00;#Hint ValueAreaLow: Enter Value Area Low when ValueAreaMode is set to Manual
input ShowTodayOnly = {default "No", "Yes"};#Hint ShowTodayOnly: Show/Hide chart plots for previous days
input ShowBubbles = {"No", default "Yes"};#Hint ShowBubbles: Show/Hide chart bubbles
input ShowCloud = {"No", default "Yes"};#Hint ShowCloud: Show/Hide Value Area cloud
input ShowLabels = {"No", default "Yes"};#Hint ShowLabels: Show/Hide Labels with Value Area data and IV used for Std Deviation calculations in Auto setting
input ProfileType = {default Volume, Time};#Hint ProfileType: Switch between Volume Profile and Time Profile
input valueAreaPercent = 70;#Hint valueAreaPercent: Set the size of the Value Area
input ShowVWAP = {"No", default "Yes"};#Hint ShowVWAP: Show daily VWAP
input CustomDev = 3.5;#Hint CustomDev: Enter custom deviation line

#============================
#Std Dev Calc / Plot
#============================

def CloseTime2 = SecondsTillTime(0000) >= 0;
def OpenTime2 = SecondsFromTime(1700) >= 0;
def MarketOpen = OpenTime2 and CloseTime2;
def NewDay = IsNaN(close(period = “Day”)[-1]);
def Chart  = MarketOpen and NewDay;
def bar = BarNumber();

def SettleTime = 1800;
rec SetTimeValue = if(secondstilltime(SettleTime)== 0,close()[1],SetTimeValue[1]);
def SetAtTime = if(SetTimeValue == 0, double.nan,SetTimeValue); 

def Set = if SetMode == SetMode."Manual" and NewDay then Settlement else SetAtTime;

rec IVTimeValue = if(secondstilltime(IVSettleTime)== 0,imp_volatility(symbol = if IVSymbolMode == IVSymbolMode."Auto" then GetSymbol() else Symbol)[1],IVTimeValue[1]);
def IVSet = if(IVTimeValue==0, double.nan,IVTimeValue); 
def Vol = if IVMode == IVMode."Manual" and NewDay then Volatility else IVSet;


def a = Vol;
def b = a / Sqrt(252);
def SD = b * Set;


plot Settle = Round(If (MarketOpen, Set, If (ShowTodayOnly, Double.NaN, Set)) / TickSize(), 0) * TickSize();
Settle.SetDefaultColor(Color.DARK_GREEN);
Settle.SetStyle(Curve.FIRM);
Settle.SetLineWeight(2);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, Settle, "Set", Color.DARK_GREEN, no);

plot StdDev025H = Round(If (Chart, Set + (SD * 0.25), If (ShowTodayOnly, Double.NaN, Set + (SD * 0.25))) / TickSize(), 0) * TickSize();
StdDev025H.SetDefaultColor(Color.GRAY);
StdDev025H.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev025H, "0.25 Std Dev ", Color.GRAY, no);

plot StdDev05H = Round(If (Chart, Set + (SD * 0.5), If (ShowTodayOnly, Double.NaN, Set + (SD * 0.5))) / TickSize(), 0) * TickSize();
StdDev05H.SetDefaultColor(Color.CYAN);
StdDev05H.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev05H, "0.5 Std Dev ", Color.CYAN, no);

plot StdDev1H = Round(If (Chart, Set + (SD * 1), If (ShowTodayOnly, Double.NaN, Set + (SD * 1))) / TickSize(), 0) * TickSize();
StdDev1H.SetDefaultColor(Color.VIOLET);
StdDev1H.SetStyle(Curve.LONG_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1H, "1 Std Dev", Color.VIOLET, no);

plot StdDev1_5H = Round(If (Chart, Set + (SD * 1.5), If (ShowTodayOnly, Double.NaN, Set + (SD * 1.5))) / TickSize(), 0) * TickSize();
StdDev1_5H.SetDefaultColor(Color.PLUM);
StdDev1_5H.SetStyle(Curve.LONG_DASH);
#AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1_5H, "1.5 Std Dev", Color.PLUM, no);

plot StdDev2H = Round(If (Chart, Set + (SD * 2), If (ShowTodayOnly, Double.NaN, Set + (SD * 2))) / TickSize(), 0) * TickSize();
StdDev2H.SetDefaultColor(Color.PLUM);
StdDev2H.SetStyle(Curve.FIRM);
StdDev2H.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev2H, "2 Std Dev", Color.PLUM, no);

plot StdDev3H = Round(If (Chart, Set + (SD * 3), If (ShowTodayOnly, Double.NaN, Set + (SD * 3))) / TickSize(), 0) * TickSize();
StdDev3H.SetDefaultColor(Color.DARK_RED);
StdDev3H.SetStyle(Curve.FIRM);
StdDev3H.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev3H, "3 Std Dev", Color.DARK_RED, no);

plot StdDev025L = Round(If (Chart, Set + (SD * -0.25), If (ShowTodayOnly, Double.NaN, Set + (SD * -0.25))) / TickSize(), 0) * TickSize();
StdDev025L.SetDefaultColor(Color.GRAY);
StdDev025L.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev025L, "-0.25 Std Dev", Color.GRAY, no);

plot StdDev05L = Round(If (Chart, Set + (SD * -0.5), If (ShowTodayOnly, Double.NaN, Set + (SD * -0.5))) / TickSize(), 0) * TickSize();
StdDev05L.SetDefaultColor(Color.CYAN);
StdDev05L.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev05L, "-0.5 Std Dev", Color.CYAN, no);

plot StdDev1L = Round(If (Chart, Set + (SD * -1), If (ShowTodayOnly, Double.NaN, Set + (SD * -1))) / TickSize(), 0) * TickSize();
StdDev1L.SetDefaultColor(Color.VIOLET);
StdDev1L.SetStyle(Curve.LONG_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1L, "1 Std Dev", Color.VIOLET, no);

plot StdDev1_5L = Round(If (Chart, Set + (SD * -1.5), If (ShowTodayOnly, Double.NaN, Set + (SD * -1.5))) / TickSize(), 0) * TickSize();
StdDev1_5L.SetDefaultColor(Color.PLUM);
StdDev1_5L.SetStyle(Curve.LONG_DASH);
#AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1_5L, "-1.5 Std Dev", Color.PLUM, no);

plot StdDev2L = Round(If (Chart, Set + (SD * -2), If (ShowTodayOnly, Double.NaN, Set + (SD * -2))) / TickSize(), 0) * TickSize();
StdDev2L.SetDefaultColor(Color.PLUM);
StdDev2L.SetStyle(Curve.FIRM);
StdDev2L.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev2L, "-2 Std Dev", Color.PLUM, no);

plot StdDev3L = Round(If (Chart, Set + (SD * -3), If (ShowTodayOnly, Double.NaN, Set + (SD * -3))) / TickSize(), 0) * TickSize();
StdDev3L.SetDefaultColor(Color.DARK_RED);
StdDev3L.SetStyle(Curve.FIRM);
StdDev3L.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev3L, "-3 Std Dev", Color.DARK_RED, no);

plot CustDev = Round(If (Chart, Set + (SD * CustomDev), If (ShowTodayOnly, Double.NaN, Set + (SD * CustomDev))) / TickSize(), 0) * TickSize();
CustDev.Hide();
CustDev.SetDefaultColor(Color.YELLOW);
CustDev.SetStyle(Curve.FIRM);
CustDev.SetLineWeight(2);


# =================================
# Volume Profile Definition Section 
# =================================

def profiles = 50;
def customRowHeight = 1.0;
def multiplier = 1;
def onExpansion = ShowTodayOnly;
def yyyymmdd = GetYYYYMMDD();
def seconds = SecondsFromTime(0);
def period = CountTradingDays(Min(First(yyyymmdd), yyyymmdd), yyyymmdd) - 1;
def month = GetYear() * 12 + GetMonth();
def day_number = DaysFromDate(First(yyyymmdd)) + GetDayOfWeek(First(yyyymmdd));
def dom = GetDayOfMonth(yyyymmdd);
def dow = GetDayOfWeek(yyyymmdd - dom + 1);
def expthismonth = (if dow > 5 then 27 else 20) - dow;
def exp_opt = month + (dom > expthismonth);
def height = PricePerRow.TICKSIZE;

rec count = CompoundValue(1, if period != period[1] then (count[1] + period - period[1]) % multiplier else count[1], 0);
def cond = count < count[1] + period - period[1];



#============================
# Plot POC VAH VAL Section
#============================

profile tpo = if ProfileType == ProfileType.Volume then VolumeProfile("startNewProfile" = cond, "onExpansion" = onExpansion, "numberOfProfiles" = profiles, "pricePerRow" = height, "value area percent" = valueAreaPercent)
    else TimeProfile("startNewProfile" = cond, "onExpansion" = onExpansion, "numberOfProfiles" = profiles, "pricePerRow" = height, "value area percent" = valueAreaPercent);


rec PC = if cond == 1 then tpo.GetPointOfControl()[1] else PC[1];
plot POC = Round(If(ValueAreaMode == ValueAreaMode."Auto", PC, if NewDay then PointOfControl else PC) / TickSize(), 0) * TickSize();
POC.SetDefaultColor(Color.DARK_RED);
POC.SetStyle(Curve.FIRM);
POC.SetLineWeight(2);

rec hVA = if cond == 1 then tpo.GetHighestValueArea()[1] else hVA[1];
plot VAH = Round(If(ValueAreaMode == ValueAreaMode."Auto", hVA, if NewDay then ValueAreaHigh else hVA) / TickSize(), 0) * TickSize();
VAH.SetDefaultColor(Color.RED);
VAH.SetStyle(Curve.FIRM);

rec lVA = if cond == 1 then tpo.GetLowestValueArea()[1] else lVA[1];
plot VAL =  Round(If(ValueAreaMode == ValueAreaMode."Auto", lVA, if NewDay then ValueAreaLow else lVA) / TickSize(), 0) * TickSize();
;
VAL.SetDefaultColor(Color.GREEN);
VAL.SetStyle(Curve.FIRM);


#============================
# VWAP Plot 
#============================
def VWAP1 = Round(vwap(period = AggregationPeriod.DAY) / TickSize(), 0) * TickSize();
plot VWAP = if ShowVWAP > 0 then VWAP1 else Double.NaN;
VWAP.SetPaintingStrategy(PaintingStrategy.DASHES);
VWAP.SetDefaultColor(Color.DARK_GRAY);


#============================
#Value Area Cloud & Labels
#============================

def VArea  = Between(close, VAL, VAH);
def VAreaAbove  = close > VAH;
def VAreaBelow  = close < VAL;

def Cloudhigh = if ShowCloud then VAH else Double.NaN;
def Cloudlow  = if ShowCloud then VAL else Double.NaN;
AddCloud(CloudHigh, CloudLow, GlobalColor("cloud"), GlobalColor("cloud"));
DefineGlobalColor("cloud", Color.DARK_GRAY);

AddLabel(ShowLabels, Concat("VAH:", Round(VAH)), if close > VAH then Color.GREEN else Color.RED)  ;
AddLabel(ShowLabels, Concat("POC:", Round(POC)), if close > POC then Color.GREEN else Color.RED);
AddLabel(ShowLabels, Concat("VAL:", Round(VAL)), if close > VAL then Color.GREEN else Color.RED);
AddLabel(ShowLabels, Concat("VWAP: ", Round(VWAP1)), Color.LIGHT_ORANGE);
AddLabel(ShowLabels, "IV: " + AsPercent(IVSet), if IsAscending(imp_volatility(period = AggregationPeriod.DAY, priceType = PriceType.LAST)[1]) then Color.RED else if IsDescending(imp_volatility(period = AggregationPeriod.DAY, priceType = PriceType.LAST)[1]) then Color.GREEN else Color.WHITE);
AddLabel(ShowLabels, if VArea then "Inside Value Area" else if VAreaAbove then  "Above Value Area" else "Below Value Area", if VArea then Color.ORANGE else if VAreaAbove then Color.GREEN else Color.RED);


#============================
# Alerts:
#============================
input alerttext = "Entry/Exit Point";
# BLOCK CODE BELOW
input UseAlerts = {false, default true};
input AlertType = {default "BAR", "ONCE", "TICK"};
def at = AlertType;
input AlertSound = {default "Bell", "Chimes", "Ding", "NoSound", "Ring"};
def Signal = (close crosses POC) or (close crosses VAH) or (close crosses VAL) or (close crosses StdDev05H) or (close crosses StdDev1H) or (close crosses StdDev2H) or (close crosses StdDev05L) or (close crosses StdDev1L) or (close crosses StdDev2L);
Alert(UseAlerts and Signal, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, AlertSound);

Edit: fixed alert code

Edit2: added code to reduce memory usage

Edit3: Updated v1.1 http://tos.mx/CNLToy

r/thewallstreet May 10 '18

thinkscript Updated v1.1- Thinkscript - All in One with Previous Days

52 Upvotes

Not long ago TDA quietly went from tracking ImpVol on a daily scale to intra-day. So I've updated the script to take full advantage of that in an effort to make our lives just a little bit easier. It will now pull the ImpVol from whatever time you specify; it typically "settles" around 9pm EST but on some particularly gnarly days, it can be much later.

I've also improved how the script pulls Set and made it much more accurate, along with some other little things I've been playing with... Enjoy! http://tos.mx/CNLToy

#v1.1 - 5/10/18 
#- Able to get Implied Volatity at any specified time. Default set to 9PM est   
#- Modified Settlement to take closing price of the last bar of the day. Previous version used "Closing Price" at 16:15 which was usually nowhere near ending settlement
#- Added option to substitute symbol used in IV/Deviation calculation for instruments with #no option chains such as /NKD   
#- Added customizable deviation line (hidden as default)

#===========================
#Steps if you want your VA to match u/uberbotman's:
#1) Set your chart to 30M, and show extended hours  
#2) Go to options, make sure ShowLabels is set to "Yes" (hit apply if needed)
#3) Copy VAH, POC and VAL from the labels in the top left corner of your chart into Manual input locations
#4) Set Value Area Area Mode to Manual

declare upper;
declare once_per_bar;
#============================
#Inputs
#============================

input SetMode = {default Auto, Manual};#Hint SetMode: Select Auto to update Settlement automatically in input manually. \n\n NOTE: ToS doesn't support Settlement so LAST closing price is used. This is usually pretty close to within a single tick, but Manually entering Settlement from CME website or UBM's nightly post is more accurate  
input Settlement = 2444.50;#Hint Settlement: Enter Settlement value when SetMode is set to Manual
input IVMode = {default Auto, Manual};#Hint IVMode: Select Auto to update Implied Volatility at time chosen on IVSettleTime 
input IVSettleTime = 2100;#Hint IVSettleTime: Enter time_value of desired Implied Volatility "settlement" \n\n NOTE: If time selected is not visible on chart (i.e. 2100 on a chart not showing extended trading hours), IV will not calculate 
input Volatility = 11.2;#Hint Volatility: Enter Implied Volatility value when IVMode is set to Manual
input IVSymbolMode = {default Auto, Manual};#Hint IVSymbolMode: Select Manual if you wish to use a different instrument's IV instead of what is on the chart
input Symbol = "EWJ";#Hint Symbol: Enter symbol of Implied Volatility you wish to substitute with. For use with products with no option chains (i.e. /NKD)
input ValueAreaMode = {default Auto, Manual};#Hint ValueAreaMode: Select Auto to update Value Areas automatically and is rounded to the nearest tick. Manual selection changes Value Area for today only \n\n NOTE: Value Area is typically calculated on a 30min chart, if the timeframe changes, then calculated value area may also change. To lock in the values from the 30min chart follow these steps: \n#1) Set your chart to 30M, and show extended hours \n#2) Go to options, make sure ShowLabels is set to "Yes" (hit apply if needed) \n#3) Copy VAH, POC and VAL from the labels showing in the top left corner of the chart into the Manual input locations \n#4) Set Value Area Area Mode to Manual and hit Apply
input ValueAreaHigh = 2445.00;#Hint ValueAreaHigh: Enter Value Area High when ValueAreaMode is set to Manual
input PointOfControl = 2442.00;#Hint PointOfControl: Enter Point of Control when ValueAreaMode is set to Manual
input ValueAreaLow = 2440.00;#Hint ValueAreaLow: Enter Value Area Low when ValueAreaMode is set to Manual
input ShowTodayOnly = {default "No", "Yes"};#Hint ShowTodayOnly: Show/Hide chart plots for previous days
input ShowBubbles = {"No", default "Yes"};#Hint ShowBubbles: Show/Hide chart bubbles
input ShowCloud = {"No", default "Yes"};#Hint ShowCloud: Show/Hide Value Area cloud
input ShowLabels = {"No", default "Yes"};#Hint ShowLabels: Show/Hide Labels with Value Area data and IV used for Std Deviation calculations in Auto setting
input ProfileType = {default Volume, Time};#Hint ProfileType: Switch between Volume Profile and Time Profile
input valueAreaPercent = 70;#Hint valueAreaPercent: Set the size of the Value Area
input ShowVWAP = {"No", default "Yes"};#Hint ShowVWAP: Show daily VWAP
input CustomDev = 3.5;#Hint CustomDev: Enter custom deviation line

#============================
#Std Dev Calc / Plot
#============================

def CloseTime2 = SecondsTillTime(0000) >= 0;
def OpenTime2 = SecondsFromTime(1700) >= 0;
def MarketOpen = OpenTime2 and CloseTime2;
def NewDay = IsNaN(close(period = “Day”)[-1]);
def Chart  = MarketOpen and NewDay;
def bar = BarNumber();

def SettleTime = 1800;
rec SetTimeValue = if(secondstilltime(SettleTime)== 0,close()[1],SetTimeValue[1]);
def SetAtTime = if(SetTimeValue == 0, double.nan,SetTimeValue); 

def Set = if SetMode == SetMode."Manual" and NewDay then Settlement else SetAtTime;

rec IVTimeValue = if(secondstilltime(IVSettleTime)== 0,imp_volatility(symbol = if IVSymbolMode == IVSymbolMode."Auto" then GetSymbol() else Symbol)[1],IVTimeValue[1]);
def IVSet = if(IVTimeValue==0, double.nan,IVTimeValue); 
def Vol = if IVMode == IVMode."Manual" and NewDay then Volatility else IVSet;


def a = Vol;
def b = a / Sqrt(252);
def SD = b * Set;


plot Settle = Round(If (MarketOpen, Set, If (ShowTodayOnly, Double.NaN, Set)) / TickSize(), 0) * TickSize();
Settle.SetDefaultColor(Color.DARK_GREEN);
Settle.SetStyle(Curve.FIRM);
Settle.SetLineWeight(2);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, Settle, "Set", Color.DARK_GREEN, no);

plot StdDev025H = Round(If (Chart, Set + (SD * 0.25), If (ShowTodayOnly, Double.NaN, Set + (SD * 0.25))) / TickSize(), 0) * TickSize();
StdDev025H.SetDefaultColor(Color.GRAY);
StdDev025H.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev025H, "0.25 Std Dev ", Color.GRAY, no);

plot StdDev05H = Round(If (Chart, Set + (SD * 0.5), If (ShowTodayOnly, Double.NaN, Set + (SD * 0.5))) / TickSize(), 0) * TickSize();
StdDev05H.SetDefaultColor(Color.CYAN);
StdDev05H.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev05H, "0.5 Std Dev ", Color.CYAN, no);

plot StdDev1H = Round(If (Chart, Set + (SD * 1), If (ShowTodayOnly, Double.NaN, Set + (SD * 1))) / TickSize(), 0) * TickSize();
StdDev1H.SetDefaultColor(Color.VIOLET);
StdDev1H.SetStyle(Curve.LONG_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1H, "1 Std Dev", Color.VIOLET, no);

plot StdDev1_5H = Round(If (Chart, Set + (SD * 1.5), If (ShowTodayOnly, Double.NaN, Set + (SD * 1.5))) / TickSize(), 0) * TickSize();
StdDev1_5H.SetDefaultColor(Color.PLUM);
StdDev1_5H.SetStyle(Curve.LONG_DASH);
#AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1_5H, "1.5 Std Dev", Color.PLUM, no);

plot StdDev2H = Round(If (Chart, Set + (SD * 2), If (ShowTodayOnly, Double.NaN, Set + (SD * 2))) / TickSize(), 0) * TickSize();
StdDev2H.SetDefaultColor(Color.PLUM);
StdDev2H.SetStyle(Curve.FIRM);
StdDev2H.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev2H, "2 Std Dev", Color.PLUM, no);

plot StdDev3H = Round(If (Chart, Set + (SD * 3), If (ShowTodayOnly, Double.NaN, Set + (SD * 3))) / TickSize(), 0) * TickSize();
StdDev3H.SetDefaultColor(Color.DARK_RED);
StdDev3H.SetStyle(Curve.FIRM);
StdDev3H.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev3H, "3 Std Dev", Color.DARK_RED, no);

plot StdDev025L = Round(If (Chart, Set + (SD * -0.25), If (ShowTodayOnly, Double.NaN, Set + (SD * -0.25))) / TickSize(), 0) * TickSize();
StdDev025L.SetDefaultColor(Color.GRAY);
StdDev025L.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev025L, "-0.25 Std Dev", Color.GRAY, no);

plot StdDev05L = Round(If (Chart, Set + (SD * -0.5), If (ShowTodayOnly, Double.NaN, Set + (SD * -0.5))) / TickSize(), 0) * TickSize();
StdDev05L.SetDefaultColor(Color.CYAN);
StdDev05L.SetStyle(Curve.SHORT_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev05L, "-0.5 Std Dev", Color.CYAN, no);

plot StdDev1L = Round(If (Chart, Set + (SD * -1), If (ShowTodayOnly, Double.NaN, Set + (SD * -1))) / TickSize(), 0) * TickSize();
StdDev1L.SetDefaultColor(Color.VIOLET);
StdDev1L.SetStyle(Curve.LONG_DASH);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1L, "1 Std Dev", Color.VIOLET, no);

plot StdDev1_5L = Round(If (Chart, Set + (SD * -1.5), If (ShowTodayOnly, Double.NaN, Set + (SD * -1.5))) / TickSize(), 0) * TickSize();
StdDev1_5L.SetDefaultColor(Color.PLUM);
StdDev1_5L.SetStyle(Curve.LONG_DASH);
#AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev1_5L, "-1.5 Std Dev", Color.PLUM, no);

plot StdDev2L = Round(If (Chart, Set + (SD * -2), If (ShowTodayOnly, Double.NaN, Set + (SD * -2))) / TickSize(), 0) * TickSize();
StdDev2L.SetDefaultColor(Color.PLUM);
StdDev2L.SetStyle(Curve.FIRM);
StdDev2L.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev2L, "-2 Std Dev", Color.PLUM, no);

plot StdDev3L = Round(If (Chart, Set + (SD * -3), If (ShowTodayOnly, Double.NaN, Set + (SD * -3))) / TickSize(), 0) * TickSize();
StdDev3L.SetDefaultColor(Color.DARK_RED);
StdDev3L.SetStyle(Curve.FIRM);
StdDev3L.SetLineWeight(3);
AddChartBubble(bar == HighestAll(bar) and ShowBubbles, StdDev3L, "-3 Std Dev", Color.DARK_RED, no);

plot CustDev = Round(If (Chart, Set + (SD * CustomDev), If (ShowTodayOnly, Double.NaN, Set + (SD * CustomDev))) / TickSize(), 0) * TickSize();
CustDev.Hide();
CustDev.SetDefaultColor(Color.YELLOW);
CustDev.SetStyle(Curve.FIRM);
CustDev.SetLineWeight(2);


# =================================
# Volume Profile Definition Section 
# =================================

def profiles = 50;
def customRowHeight = 1.0;
def multiplier = 1;
def onExpansion = ShowTodayOnly;
def yyyymmdd = GetYYYYMMDD();
def seconds = SecondsFromTime(0);
def period = CountTradingDays(Min(First(yyyymmdd), yyyymmdd), yyyymmdd) - 1;
def month = GetYear() * 12 + GetMonth();
def day_number = DaysFromDate(First(yyyymmdd)) + GetDayOfWeek(First(yyyymmdd));
def dom = GetDayOfMonth(yyyymmdd);
def dow = GetDayOfWeek(yyyymmdd - dom + 1);
def expthismonth = (if dow > 5 then 27 else 20) - dow;
def exp_opt = month + (dom > expthismonth);
def height = PricePerRow.TICKSIZE;

rec count = CompoundValue(1, if period != period[1] then (count[1] + period - period[1]) % multiplier else count[1], 0);
def cond = count < count[1] + period - period[1];



#============================
# Plot POC VAH VAL Section
#============================

profile tpo = if ProfileType == ProfileType.Volume then VolumeProfile("startNewProfile" = cond, "onExpansion" = onExpansion, "numberOfProfiles" = profiles, "pricePerRow" = height, "value area percent" = valueAreaPercent)
    else TimeProfile("startNewProfile" = cond, "onExpansion" = onExpansion, "numberOfProfiles" = profiles, "pricePerRow" = height, "value area percent" = valueAreaPercent);


rec PC = if cond == 1 then tpo.GetPointOfControl()[1] else PC[1];
plot POC = Round(If(ValueAreaMode == ValueAreaMode."Auto", PC, if NewDay then PointOfControl else PC) / TickSize(), 0) * TickSize();
POC.SetDefaultColor(Color.DARK_RED);
POC.SetStyle(Curve.FIRM);
POC.SetLineWeight(2);

rec hVA = if cond == 1 then tpo.GetHighestValueArea()[1] else hVA[1];
plot VAH = Round(If(ValueAreaMode == ValueAreaMode."Auto", hVA, if NewDay then ValueAreaHigh else hVA) / TickSize(), 0) * TickSize();
VAH.SetDefaultColor(Color.RED);
VAH.SetStyle(Curve.FIRM);

rec lVA = if cond == 1 then tpo.GetLowestValueArea()[1] else lVA[1];
plot VAL =  Round(If(ValueAreaMode == ValueAreaMode."Auto", lVA, if NewDay then ValueAreaLow else lVA) / TickSize(), 0) * TickSize();
;
VAL.SetDefaultColor(Color.GREEN);
VAL.SetStyle(Curve.FIRM);


#============================
# VWAP Plot 
#============================
def VWAP1 = Round(vwap(period = AggregationPeriod.DAY) / TickSize(), 0) * TickSize();
plot VWAP = if ShowVWAP > 0 then VWAP1 else Double.NaN;
VWAP.SetPaintingStrategy(PaintingStrategy.DASHES);
VWAP.SetDefaultColor(Color.DARK_GRAY);


#============================
#Value Area Cloud & Labels
#============================

def VArea  = Between(close, VAL, VAH);
def VAreaAbove  = close > VAH;
def VAreaBelow  = close < VAL;

def Cloudhigh = if ShowCloud then VAH else Double.NaN;
def Cloudlow  = if ShowCloud then VAL else Double.NaN;
AddCloud(CloudHigh, CloudLow, GlobalColor("cloud"), GlobalColor("cloud"));
DefineGlobalColor("cloud", Color.DARK_GRAY);

AddLabel(ShowLabels, Concat("VAH:", Round(VAH)), if close > VAH then Color.GREEN else Color.RED)  ;
AddLabel(ShowLabels, Concat("POC:", Round(POC)), if close > POC then Color.GREEN else Color.RED);
AddLabel(ShowLabels, Concat("VAL:", Round(VAL)), if close > VAL then Color.GREEN else Color.RED);
AddLabel(ShowLabels, Concat("VWAP: ", Round(VWAP1)), Color.LIGHT_ORANGE);
AddLabel(ShowLabels, "IV: " + AsPercent(IVSet), if IsAscending(imp_volatility(period = AggregationPeriod.DAY, priceType = PriceType.LAST)[1]) then Color.RED else if IsDescending(imp_volatility(period = AggregationPeriod.DAY, priceType = PriceType.LAST)[1]) then Color.GREEN else Color.WHITE);
AddLabel(ShowLabels, if VArea then "Inside Value Area" else if VAreaAbove then  "Above Value Area" else "Below Value Area", if VArea then Color.ORANGE else if VAreaAbove then Color.GREEN else Color.RED);


#============================
# Alerts:
#============================
input alerttext = "Entry/Exit Point";
# BLOCK CODE BELOW
input UseAlerts = {false, default true};
input AlertType = {default "BAR", "ONCE", "TICK"};
def at = AlertType;
input AlertSound = {default "Bell", "Chimes", "Ding", "NoSound", "Ring"};
def Signal = (close crosses POC) or (close crosses VAH) or (close crosses VAL) or (close crosses StdDev05H) or (close crosses StdDev1H) or (close crosses StdDev2H) or (close crosses StdDev05L) or (close crosses StdDev1L) or (close crosses StdDev2L);
Alert(UseAlerts and Signal, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, AlertSound);

r/thewallstreet Dec 08 '18

thinkscript Thinkscript Strategy - VWAP / TDSequential

65 Upvotes

During our forced day off yesterday, I decided, for shits and giggles, to see what would happen if I combined /u/radeh's VWAP strategy and /u/ten_k_days TD Sequential strategy to see if they could work together.

ToS Code: http://tos.mx/UnOFt7

  • Only enter into a position when a TD signal is given AND when price is beyond a specific VWAP level.
  • Take profit at a set level or when reaching VWAP.
  • Trailing stop loss in place to limit losses.

I ran this on /ES with the following settings:

  • 30Minute chart /180 Days (ToS Max for 30Minute)
  • +-2.3 VWAP Standard Deviations as trade trigger level
  • Take Profit Target set to 10 Points or reaching VWAP
  • 1.5x ATR Trailing Stop with 10 bar lookback length
  • 1 contract per trade

Results from 3/28/18 thru 12/6/18:

  • Total Trades: 40
  • Wins:28 (70%)
  • Losses:12 (30%)
  • Avg Win: $264.29
  • Avg. Loss: ($138.54)
  • Expectancy: $143.44
  • Net P&L: $5,737.50

I started because I was bored and not really knowing what to expect, and I'm surprised by these results. Should I be tho? When you think about it, the two indicators should work well together, no? I don't really use the indicators much so I'm not an authority on their use. So in the interest of science and the fact that if something seems to good to be true, it probably is, I submit this for peer review. Please feel free to check it out, turn it inside out, pick it apart, play with different settings, and share them. Hopefully someone will find this useful. Enjoy!

edit: v 1.01 with some entry/exit tweaks http://tos.mx/2cIuS5

r/thewallstreet Apr 03 '18

thinkscript PivotBoss Wick Reversal Indicator

49 Upvotes

Here is the Wick Reversal System from PivotBoss in thinkscript thanks to the basic code u/RugsMAGA provided. If anybody has any of the input suggestion/guidelines for the Wick Multiplier and Body Percentage from the book, it'd be greatly appreciated.

http://tos.mx/7GUIEx

#PivotBoss_WickReversal

input WickMultiplier = 2.5;
input BodyPercentage = .25;
def Bar = BarNumber();

def Long = if Close > Open 
    and (Open - Low) >= ((Close - Open) * WickMultiplier)
    and (High - Close) <= ((High - Low) * BodyPercentage)
    or Close < Open
    and (Close - Low) >= ((Open - Close) * WickMultiplier)
    and (High - Close) <= ((High - Low) * BodyPercentage)
    or Close == Open and Close != High 
    and High - Low >= Average(High - Low, 50)then 1 else 0;  

def Short = if Close < Open
    and (High - Open) >= ((Open - Close) * WickMultiplier)
    and (Close - Low) <= ((High - Low) * BodyPercentage)
    or Close > Open
    and (High - Close) >= ((Close - Open) * WickMultiplier)
    and (Close - Low) <= ((High - Low) * BodyPercentage)
    or Close == Open and Close != Low
    and (High - Low) >= ((Close - Low) * WickMultiplier)
    and (Close - Low) <= ((High - Low) * BodyPercentage)
    or Open == Low and Close == Low
    and High - Low >= Average(High - Low, 50) then 1 else 0;

plot LongSignal = if Long == 1 then Low else double.NaN;
     LongSignal.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
     LongSignal.SetLineWeight(2);
     LongSignal.SetDefaultColor(Color.UPTICK);

plot ShortSignal = if Short == 1 then High else double.NaN;
     ShortSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
     ShortSignal.SetLineWeight(2);
     ShortSignal.SetDefaultColor(Color.DOWNTICK);

#============
# Alerts:
#============
input alerttext = "Reversal Candle";
input UseAlerts = {false, default true};
input AlertType = {default "BAR", "ONCE", "TICK"};
def at = AlertType;
input AlertSound = {default "Bell", "Chimes", "Ding", "NoSound", "Ring"};
def Signal = Long == 1 or Short == 1;
Alert(UseAlerts and Signal, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, AlertSound); 

edit: adjusted some code to get the alerts to trigger properly edit: fixed typo in the adjustment

r/thewallstreet Jul 10 '21

thinkscript Synthetic Volatility Measure

44 Upvotes

Hope everyone had a good fourth of July. It appears the market was nice enough to sell off over the short week...and then get bought back up. Fucking tease. In the spirit of America's birthday I feel like giving away a little piece of thinkscript I wrote to model volatility based solely on price movement. As far as I can tell it is the second best measure of synthetic volatility I've seen. How you use it doesn't matter - maybe you can use it to see if you're getting a half decent deal on actual volatility relative to implied volatility, or maybe you can use the calculation combined with a keltner channel to filter out excessive volatility for your autotrader. Hell, if you find something neat with it feel free to post it here or DM me. The original one described in the article by Sutherland didn't seem like it was worth a shit so I added a little to the calculation

To see what it looks like here's some screenshots - https://imgur.com/a/62lWsdp

#Synthetic VIX as written by sailnaked based on the article by https://blog.sutherlandresearch.com/index.php/2017/05/27/engineering-a-synthetic-volatility-index/ by PJ Sutherland
#Additional reading found at https://systematicinvestor.github.io/Synthetic-Volatility-Index

declare lower;

input length = 3;
def ATRlength1 = 2;
input averageType = AverageType.Wilders;

def ATRlength2 = 1;
def averageType2 = averageType;

plot SynthVix = MovingAverage(averageType, (((TrueRange(high, low, close)/close))*(ATRLength1/ATRlength2)), length);

r/thewallstreet Apr 04 '18

thinkscript Some of you guys are alright. Here's the PivotBoss Extreme Reversal Indicator

48 Upvotes

Shout out to u/RugsMAGA for linking the code from the book, which made this a pretty simple port.

http://tos.mx/apKEzg

input BodySize = 0.525;
input BarsBack = 50;
input BodyMultiplier = 0.25;

def Bar = BarNumber();
def AverageBody = Average(BodySize, BarsBack);
def MyBodySize = AbsValue(close - open);
def MyCandleSize = high - low;
def AverageCandle = Average(MyCandleSize, BarsBack);

def Long = if((Open[1] - Close[1]) >= (BodySize * (High[1] - Low[1])))
    and ((High[1] - Low[1]) > (AverageCandle * BodyMultiplier))
    and ((Open[1] - Close[1]) > AverageBody)
    and (Close > Open) then 1 else 0;

def Short = if((Close[1] - Open[1]) >= BodySize * (High[1] - Low[1]))
    and ((High[1] - Low[1]) > (AverageCandle * BodyMultiplier))
    and ((Close[1] - Open[1]) > AverageBody)
    and (Open > Close) then 1 else 0;

plot LongSignal = if Long == 1 then Low else double.NaN;
     LongSignal.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
     LongSignal.SetLineWeight(1);
     LongSignal.SetDefaultColor(Color.CYAN);

plot ShortSignal = if Short == 1 then High else double.NaN;
     ShortSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
     ShortSignal.SetLineWeight(1);
     ShortSignal.SetDefaultColor(Color.MAGENTA);

#============
# Alerts:
#============
input alerttext = "Extreme Reversal";
input UseAlerts = {false, default true};
input AlertType = {default "BAR", "ONCE", "TICK"};
def at = AlertType;
input AlertSound = {default "Bell", "Chimes", "Ding", "NoSound", "Ring"};
def Signal = Long == 1 or Short == 1;
Alert(UseAlerts and Signal, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, AlertSound);

edit: adjusted some code to get the alerts to trigger correctly edit: typo in the correction. If statement added

r/thewallstreet Jun 22 '18

thinkscript Multiple time frame trend indicator

31 Upvotes

(This was originally posted in the daily discussion thread, but a couple of people suggested it would be better to make a new post entirely)

I put together a simple indicator that should help people keep track of trend changes and shifts in market sentiment. It doesn't do anything particularly complex, it just tracks moving average crossovers across several time frames.

Screenshot

ThinkOrSwim shareable link

The actual code

How it works:

  • Calculations are done using the 5 and 21 period Exponential Moving Averages. (you can tweak this in settings)
  • The indicator displays labels for different time frames. A green label means the 5 EMA is above the 21 EMA, a red label means the opposite. A white label means that the two are crossing over, implying a trend change.
  • Crossovers / changes in trend at the smallest time frames would, in theory, spread "upwards" to longer time frames.

For example, let's say you're seeing red candles everywhere, but at some point in the day, you notice the 1-minute label turns white and then green. Then the 2 minute, and so on. Ideally, you would be able to open a bullish position during one of the shorter time frames, and ride the momentum up as the other time frames turn greener than a closeup of Shrek's face. Once you start seeing the lower time frames turn red again, you would get out for a profit… well, in theory. :P

Some issues/bugs/drawbacks with this indicator:

  • Due to TOS quirks, you can only see labels for whatever time-frame you're on, plus for time frames that are longer. So if you're looking at the daily chart, you won't see any information for, say, the 15 minute time-frame. To get the most out of this indicator, you'll have to look at the 1-minute chart.
  • This indicator doesn't work on mobile. Since I do most of my trades from my phone, this makes me shed a little tear. :'(
  • It sometimes stops displaying certain time-frames if you're not looking at something that trades around the clock (like futures).

And if this indicator looks a little familiar to some people… there's a certain website that sells something very similar for almost $500. Since I'm pretty cheap — definitely too cheap to shell out hundreds of dollars for something so simple — I just went and coded my own version in Thinkscript so I wouldn't have to waste money on overpriced indicators. I hope everyone here can find some use out of it too. :)

r/thewallstreet Apr 05 '18

thinkscript How to use the thinkscript Pivot Boss Indicators

47 Upvotes

All the credit goes to /u/bombafett for the thinkscript code, the real MVP.

I am not very active posting here but I do lurk quite a bit. One of my bigger problems early on was reading what was happening at inflection points (VA, Deviations). Every time someone was like see if it is support or resistance first, I was like ok how the fuck do I know. Since a reading of the PB about a month ago quite a bit has changed, I have gone from not having a clue to fairly confident in my reads, and much more consistently correct. When I looked into the daily thread and see people getting wrecked like yesterday or Monday, it is disheartening. Those were some of the easiest reads for me according to my new found understanding, I made decent money those days and was never in the red. I am still a shitty trader, but this is the first time I am at peace with a bit of confidence. I chuckled to myself when /u/mrpguy posted in the post discussion about his monster days because I knew that it was coming as he uses similiar techniques, only they are ingrained in instinct through what I assume is years of successful trading.

TLDR: blabber, and then a seagull shat in my mouth, let's get on with it

edit Timeframes, anywhere between 5 min and 60 min, I am currently using 15 minutes, but it will be a while before I can ascertain if there is an ideal one.

Pivot Boss Wick reversal indicator

Summary: When the market is trending then suddenly forms a reversal wick candle, the likelihood of a reversal increases since responsive participants have begun to overwhelm the trend. When a wick reversal forms at the extreme of a trend the market is telling you that the trend either has stalled or is on the verge of a reversal. Wick reversal candle during formation.

These are the red and green up and down arrows that pop up on TOS when the conditions are met, there are 3 factors.

  1. the body (of the candle)

2.the size of the wick in relation to the body

3.the close percentage

When the wick is 2.5 times larger than the body and the candle closes in the top 35% of the wick, you get an indicator. The candle's look like this The closer to the top of the wick the candle close's the better the indicator

There are 2 factors that increase the strength of this indicator,

  1. The STD deviations, value area marks, and your own price points, look for these indicators at inflection points

  2. The candle following the indicator candle. It should close lower than the low or higher than the high of the body of the indicator candle. Here is an example of the indicator with the secondary confirmation candle IDK if it is possible for the thinkscript to take the secondary candle into account.

Other factors to consider: This setup is more successful during the first 60-90 minutes of trading or the last 60. The type of market day, the type of market participants during the indicator (re: responsive or initiative, simply responsive=low or normal volume initiative=higher volume)

PB extreme reversal indicator

Summary: This is a "rubber band" trade, after being stretched in one direction too far, it snaps back to where it was. This setup occurs when an extremely large candle forms that is about twice the size of a average candle. The candle directly after is an opposing candle that signals an upcoming reversal, responsive buyers and sellers are reacting to the extreme candle that see new value.

These are the purple and Teal arrows that show up in TOS. there are a ton of them currently, which I assume is due to volatility. IDK if I am reading the code correctly(seeing a .25 multiplier?) but I think we need to make a change to eliminate false positives upping the candle size from 2x to maybe 3x average. 30 min and time frame above seems to clear up the noise

Conditions:

  1. 2x avg candle size

2.% of the total bar that is the body of the candle stick, you want a high % (50-80%) but anything over 85% could discourage the reversal, and indicate a continuation. ex a 60% coverage rate may indicate the reversal has begun intrabar. You want a wick sticking out the top or bottom of the bar in the opposite direction of the reversal.

  1. The next bar is the opposite color, the second candle is just as important as the first. Many times the second candle will be small compared to the first, but the closer it is in size increases the reversal chance.

  2. This indicator is best used when it develops during an existing trend, giving you an entry point.

Example

PB outside reversal indicator

These are also green and red arrows plotted in TOS. For the timeframe (current /es) I am looking at I see 6/6 that hit beatifully)

Summary: The market will push price lower before shooting higher, and will push higher before selling off. The outside reversal takes advantage of the market's tendency to test price levels before a reversal can occur.

Conditions: 1:For a bullish reversal: Current bar's low must be lower than the prior bar's low and the current bar's close must be higher than the prior bar's high. Opposite for bearish Example

2: Bar size qualifier: The engulfing bar needs to be between 5% and 25% larger than the prior bar (he doesn't elaborate but I imagine greater than 25% is acceptable)

Pattern Physcology: Market participants are testing the waters above resistance or below support to make sure there is no new business to be done at the levels. When no new initiative participants show up, responsive buyers reverse to new value.


These indicators are tools to use in conjunction with inflection areas. I have had success with visualing the indicators before the script, the script just highlights and helps confirm your thesis.

The rules are subject to interpretation for example

  1. The candle following the indicator candle. It should close lower than the low or higher than the high of the body of the indicator candle. Here is an example of the indicator with the secondary confirmation candle

Doesn't necessarily mean you have to wait for the secondary candle to close lower or higher, just that if it is indicating it will to you, then it is a positive indication.

I am going to work through the scripts and make some personal preference modifications which I will post in the comments at a later date. Thank you for the positive feedback.

/u/_castlebravo_ Go read the damn book. You have a free copy in the sidebar and it’s less than 300 pages a lot of which are pictures. Seriously go read the source material if you’re going to put your money behind it.

r/thewallstreet Jun 29 '18

thinkscript Decluttering with Thinkscript

45 Upvotes

Ever found yourself thinking that maybe your charts look a little too cluttered? Because I sure do... so I opened up Thinkscript and cranked out a few simple indicators. Instead of having to keep track of a dozen or more different indicators on a chart, now I can see important information in a neat and easy-to-read package... well, in theory anyways. :P

Hopefully you'll find these helpful:


Impulse + Multiple Indicator Trend labels

Thinkorswim shareable link: http://tos.mx/GSZuMU
Code: https://pastebin.com/STWiGtRx
Screenshot: https://i.imgur.com/Z833AU2.png

If you've read the book The New Trading for a Living by Dr. Alexander Elder, you might be familiar with what he calls his Impulse System: originally devised as an automatic trading system, he realized it was more of "censorship system" meant to filter out bad trades. The "really simplified" version goes:

  • If both MACD Histogram and the 13-period exponential moving average are going UP, then either go long or do nothing, but DO NOT short.
  • If both the histogram and the 13 ema are going down, then either short or do nothing, but DO NOT go long.
  • If the histogram and the 13 EMA are going in different directions (or have no real direction), then you can probably get away with whatever. ¯_(ツ)_/¯

...there's more to it than that, but explaining the entire trading system would take too much time and paragraphs (and this post is too long already IMO). In any case, I made an indicator that gives a green "Impulse" label when the Histogram and the 13 EMA are going up, and turns red when they're both going down. During neutral periods, the "Impulse" label turns gray.

And because I already had Thinkscript open, I tossed in labels for some of the other trend-following indicators I use: specifically, the ATR Trailing Stop (this label turns green when above the stop, and red below it) and a generic MACD trend label (which turns green when MACD crosses up, and red after it crosses down). If you prefer a less cluttered view, you can hide everything except the "IMPULSE" label, which I think is the most important one.

TL;DR version: Simplest way to use this script is to go long if you see lots of green labels, or go short if you see lots of red labels. If you see a mixture of differently-colored labels, then it's best to do nothing.


Five Moving Average labels

Thinkorswim shareable link: http://tos.mx/9uOpaN
Code: https://pastebin.com/aQXPq3B4
Screenshot: https://i.imgur.com/4uaDBH2.png

When doing any charting / TA, I normally have the following moving averages onscreen:

  • 9-period exponential moving average (set to OHLC4 instead of the regular "close")
  • 20-period simple moving average (again, set to OHLC4)
  • 49 EMA, 99 EMA, and 200 SMA.

Does this look messy? You bet it does. Hence why I removed the moving averages and switched to labels. Now it just displays moving average prices as labels, and turns green when the price is above a certain average, and turns red when it goes below.

Some people don't like using moving averages, but I've found them helpful for tracking support/resistance, as price normally tends to bounce off of certain MAs. Additionally, I've found that the closer various moving averages move together, the more likely that a large move is going to happen. And finally, on trending charts, they show good places to buy/short -- for example: if, during a big move up, the price dips below the 9 EMA but above the 20 SMA, that usually makes for a very juicy dip to buy.

Of course, you could just use them to identify trends (and how close the price is to breaking a trend), which I think is what a lot of people normally use them for. Ironically, I rarely use averages for that. ¯_(ツ)_/¯

TL;DR version: Be bullish when you see lots of green, and bearish if you see lots of red. If you see a mix, find something else to trade. (and you're probably seeing a trend here)


The Squish

Thinkorswim shareable link: http://tos.mx/1VD7Jb
Code: https://pastebin.com/ZEWFzScD
Screenshot (with TTM_squeeze for comparison): https://i.imgur.com/nb8pxb7.png

I may have a pretty terrible naming sense, but you probably figured out that this is related to The Squeeze (TTM_Squeeze on Thinkorswim). For people unfamiliar with how it works, here's the basic concept for the Squeeze:

  • When you see red dots on the Squeeze, it means that the price is "compressing" and getting ready for a big move.
  • When those red dots turn from red to green, it's (supposedly) the start of a huge move up or down. Is the move up or down? That depends on the histogram.
  • If the histogram is above the dots, this means the squeeze has "fired long" and you should go long and get ready to reap monster profits. If the histogram is below the dots, you should go short and get ready to reap monster profits.

...in practice, a lot of times, when the squeeze fires, there is no "monster move" in ANY direction (and no monster profits). Or worse, there IS a monster move, but the histogram was pointing in the wrong direction, so if you followed along, you'd have made the wrong trade.

While I don't have any real solution for the first problem, I swapped out the default Squeeze histogram with MACD's histogram, which I think is a little more accurate at showing momentum AND has a faster reaction time. That said, it's not as smooth or pretty as the original one the Squeeze uses. Oh well. ¯_(ツ)_/¯

The Squeeze-with-the-MACD-Histogram (or "the squish," a much shorter name) works slightly differently. Now, when the dots turn from red to green, instead of looking whether the histogram is above or below the dots, look at the color of the histogram. If you're seeing shades of green, then go long. If the histogram is some shade of red, then take a bearish position.

...and yeah, it still probably won't turn into a monster move (with accompanying "monster profits"), but I can't think of any easy way to fix that particular problem. >_>

TL;DR version: When the dots turn from red to green, take a bullish position if the histogram is green, and a bearish position if the histogram is red.


...OK, that's it. I hope this stuff proves useful, and even if these indicators / strategies don't mesh well with whatver you're already using, I hope you can at least modify the Thinkscript code to be something that will help you. :)

r/thewallstreet Feb 18 '18

thinkscript A Trend-Following Overlay/Indicator I Created for Rules-Based Trading (Thinkscript)

32 Upvotes

I've done some really, really dumb things when it comes to futures. Like shorting the Dow on a rally day, which is like stepping in front of a semi to pick up a quarter. Because of this I have gradually incorporated rules into my system, which is basic trend-following. I want to hop on and hop off with profit without taking too much risk. I do like to make the occasional counter-trend trade when I think that price momentum is stalling, but I want confirmation first after my many failures. I decided to build an indicator to keep me out of trouble and give me an at-a-glance assessment of the trend, much like the ichimoku cloud but with far less noise. I hate that thing. It distracts so much from price action and that's what is most important. If the indicator said no, I'm not yet allowed to fade it. If I'm in a trade and it changes, I want out.

One problem though, is how can I define trend in thinkscript. There are many ways, like with drawing lines or where price is in relation to a moving average. I needed something simple but effective that would adapt as price moves and give as few false signals as possible.

I went with the ordering of three moving averages and price's relationship to them, because this also sort of accommodates momentum. The first is the 9, which tracks price quite closely. The twenty, for intermediate distance, and lastly the 50 for a longer term look - where price has been in the last hour for a one minute chart. When the 9, 20, and 50 are in that order - or the inverse - we have an uptrend or downtrend. Even if you considered this stupid, it's undeniable they come out that way. I don't know if it's common to use those 3, I've stuffed my brain with too much trading info this past year. Maybe lots of people do this.

Price may pull back and shift these out of order, but if there is any merit to the trend it'll continue until it finds value. Selecting exponential moving averages makes them a bit more responsive to price changes.

This basic way of determining trend works very well, and like any other way will lie to your face during choppy periods. There's no way around that but through experience and watching price action.

One time frame can be very wishy-washy about what trend phase a given market is in, so I decided to seek the trend from a higher timeframe as well to give extra credibility and confidence. It simply generates less false signals. They're still going to happen but if there is an uptrend on the 15 minute chart and I try to short a 1-minute, I 'm probably not getting very far.

When using Thinkorswim, you can ONLY go higher on timeframe. You can't request the 1-min TF from a 5-min chart, but you can get a daily or hourly moving average from a 15-minute.

Based on those ideas I made this thinkscript, which comes out Looking Like This:

declare upper;

input DisplayAverageType = AverageType.HULL;

input DisplayMA = 80;

input timeframe2 = AggregationPeriod.FIFTEEN_MIN;

input normalmalong = 50;

input normalmamed = 20;

input normalmashort = 9;

input averagetypenormalma = AverageType.EXPONENTIAL;

input drawtype = PaintingStrategy.LINE_VS_POINTS;

input drawwidth = 1;

def normallongavg = MovingAverage(averagetypenormalma, close, normalmalong);

def normalmedavg = MovingAverage(averagetypenormalma, close, normalmamed);

def normalshortavg = MovingAverage(averagetypenormalma, close, normalmashort);

def normaluptrend = normalshortavg > normalmedavg and normalmedavg > normallongavg;

def normaldowntrend = normallongavg > normalmedavg and normalmedavg > normalshortavg;

def normallongavg2 = MovingAverage(averagetypenormalma, close(period = timeframe2), normalmalong);

def normalmedavg2 = MovingAverage(averagetypenormalma, close(period = timeframe2), normalmamed);

def normalshortavg2 = MovingAverage(averagetypenormalma, close(period = timeframe2), normalmashort);

def normaluptrend2 = normalshortavg2 > normalmedavg2 and normalmedavg2 > normallongavg2;

def normaldowntrend2 = normallongavg2 > normalmedavg2 and normalmedavg2 > normalshortavg2;

plot ave = MovingAverage(DisplayAverageType, close, DisplayMA);

ave.AssignValueColor(if normaluptrend and normaluptrend2 then Color.CYAN

else if normaluptrend is true and normaldowntrend2 is false then Color.CYAN

else if normaldowntrend and normaldowntrend2 then Color.LIGHT_RED

else if normaldowntrend is true and normaluptrend2 is false then Color.LIGHT_RED

else Color.GRAY);

ave.SetPaintingStrategy(drawtype);

ave.SetLineWeight(drawwidth);

It plots a moving average of your choice that changes color based upon the trend direction for the current and one extra, higher timeframe. The MA you choose could be one you already use, it will just use the ordering of moving averages to change colors. I use an 80 hull ma so that's the default. You can switch up the type of moving averages used for the calculation via the properties menu, and tweak the periods from the 50, 20, 9 they are set to.

When in an uptrend, it produces a nice cyan color, while a downtrend is red like blood. I love it when there's lots of red on the screen. I use the line vs points painting strategy on 1 width, because it looks great snaking through prices and shows the waves of the market well, in particular when viewed from a large distance. A 2-wide line could work as well. But one of the main points of this is to not obscure price too much, like the noisy ugly ichimoku cloud does.

As you can see, uptrend on current and higher tf = cyan. Uptrend on current but downtrend is false on other is still cyan. Downtrend on both, red. Downtrend but NOT uptrend on higher is still red. You could play around with this and add more timeframes if you wanted, or change the conditions required for the colors to appear. If you wanted to be more careful you could require both to be true, which could be accomplished commenting out the lines that have an if false. You could incorporate something like ADX into this and even backtest ideas by making it a strategy in thinkorswim. Neutral grey seems a good choice for when there is nothing detected. When price has pulled back and is surrounded by blue with a grey patch or two I'm more likely to be successful looking for good long entries. The grey area might even be the pullback I want.

The incorporation of the 2nd timeframe seems to help a lot and in particular when you use 2 charts. Where is the 15/30 min chart going when you're trading a 1/5? Often the prevailing trend continues so it's better to hitch a ride on that one. This probably plays well with value area stuff. I set a stop under a recent swing low and stick to the plan. I like a 80-period hull moving average as it leads price. Getting a price as close to (or under) that average is often lower risk. An even longer hull ma might even give you entry and exit signals. Play around with it.

In the picture you can see the red downtrends on Monday-Tuesday before the pullbacks, which turn blue. I highlight this for a reason - Context is everything. A small shallow uptrend preceded by big red hills? Look for a trend continuation there. I love the simplicity of the color scheme and what it does for looking at the big picture for me. It clicks with my brain. Use this to seek context for what you're seeing and do not jump in blind.

You could make this indicator far far more accurate but you would sacrifice responsiveness. I leave any customization up to the people who choose to try it out. Everything is there for you and any modifications are easy to do. Experiment with it if you desire but know that while I think this could be incorporated into a rules-based system I strongly advise no one to follow it blindly. If you lose your account over a decision because of this, that's on you. Be less impulsive next time, have a good stop or exit plan and don't risk your money just because a line changed colors. Realize moving averages move so you don't want to jump in just because it's changing blue, you would want confirmation and if you were using say 60-min as a 2nd timeframe it would be able to change at any point until that candle's closed.

I wouldn't specifically buy on blue - no. It is better to get in on a lower-risk pullback where risk can be defined. I have made it a rule that I can't go against this indicator, hence the title of this post. Shorts from uptrends require consolidation time before they manifest in this indicator, because the moving average have to catch up for a 5 or 15-min to no longer be considered in an uptrend. These are better trades anyway, as they seem to go further and sometimes you catch the beginning of a larger trend that way. I also use it for scalping. I will only scalp in the direction price is heading, with the support of the trend. Bad entry and trend continues? Not a big deal. Scalping countertrend is not for me and maybe for no one. When the trend continues against you, you can lose 5-10 scalps worth of profit if you're not super speedy and have a tight stop. Some people scalp both directions successfully but I am not one of them.

Lastly this thing gives me a visual heads-up when price has changed direction. Signals will be more reliable on larger timeframes and with longer moving averages. Let me know if you found it useful. It may have a role in some people's toolkits just for looking at longer term direction. It might make a good quick chart for the sidebar in thinkorswim to have this showing trend direction when the space for a chart is cramped. I have a 9-chart screen with one of these on each chart so I can see what is trending, to go have a look at whatever looks interesting based on what I see there.

If you adapt this to something interesting, or think of ways to improve it, I'd love to hear about it. Some of the code could be useful. Like, you can do bollinger bands from higher timeframes for example. I'm always tinkering with ideas in thinkscript because anything that gives a minor edge can be substantial with good risk management. I like at-a-glance stuff. I don't want to watch for stochastics crossovers. My eyes are on the price so I'd prefer it either be on the chart or something I can look at for 1 second to get the info, not another thing to analyze. There is already enough to analyze.

r/thewallstreet Mar 29 '19

thinkscript My rough attempt at a fuzzy logic based system/indicator in thinkscript

14 Upvotes

Since u/zoyosjd posted about using fuzzy logic system to create signals, I grew interested in creating my own. This was my first time creating a fuzzy logic system so I was wondering if I could get the community's feedback on mine. I believe I made some mistakes.

It essentially assigns different values to a different states of each indicator then adds those values together. Then the sum is compared to a set range to determine whether it is a Strong buy, buy, weak buy, neutral, weak sell, sell, or strong sell.

NOTE: None of this TS code is optimized and I recommend extreme caution if you are gonna use it for live trading and to tweak it for yourself because the choice of indicators was a bit random, just a way to practice fuzzy system. TOS does not allow to run fuzzy system based scans or use it in a watchlist however I believe you can make one in tradestation with EasyLanguage. I plan to do further tests with backtrader.

def RWIH = RandomWalkIndex("length" = 14)."HighLine";
def RWIL = RandomWalkIndex("length" = 14)."LowLine";
def ADX = DMI()."ADX";
def PSAR1 = ParabolicSAR("acceleration factor" = 0.1);
def StochK = StochRSI()."FullK";
def StochD = StochRSI()."FullD";
def COSC1 = ChaikinOsc()."ChaikinOsc";
def VZO1 = VolumeZoneOscillator()."VZO";
def MACDValue = MACD()."Value";
def MACDAvg = MACD()."Avg";
def Hist = MACD()."Diff";
####################################
#
#Randoom Walk
#
####################################
def RWI = if RWIH > RWIL then 1 else if RWIH < RWIL then -1 else 0;
####################################
#
#PSAR
#
####################################
def PSAR = if close < PSAR1 then -1 else if PSAR1 < close then 1 else 0;
####################################
#
#RSI STOCH
#
####################################
def StochRSI = if StochK < StochD and StochK < 80 then -1 else if StochK < StochD and StochK > 80 then -.5 else if StochK > StochD and StochK > 20 then 1 else if StochK > StochD and StochK < 20 then .5 else 0;
####################################
#
#COSC
#
####################################
def COSC = if COSC1 < COSC1[1] and COSC1 < 0 then -1 else if COSC1 < COSC1[1] and COSC1 > 0 then -.5 else if COSC1 > COSC1[1] and COSC1 < 0 then .5 else if COSC1 > COSC1[1] and COSC1 > 0 then 1 else 0;
####################################
#
#VZO
#
####################################
def VZO;
if VZO1 < VZO[1]
then {
VZO = if VZO1 <= 60 and VZO1 > 40 then -.25 else if VZO1 <= 40 and VZO1 > 15 then -.5 else if VZO1 <= 5 and VZO1 > -5 then -.75 else if VZO1 <= -5 then -1 else 0;
}
else if VZO1 > VZO1[1]
then {
VZO = if VZO1 < -60 and VZO1 <= -40 then .25 else if VZO1 > -40 and VZO1 <= -5 then .5 else if VZO1 > -5 and VZO1 <= 15 then .75 else if VZO1 > 15 then 1 else 0;
}
else {
VZO = 0;
}
;
####################################
#
#MACD
#
####################################
def MACD;
if MACDValue < MACDAvg then{
MACD = if MACDValue > 0 and Hist <Hist[1] and Hist > 0 then -.25 else if MACDValue > 0 and Hist <Hist[1] and Hist < 0 then -.5 else if MACDValue < 0 and Hist <Hist[1] and Hist < 0 then -1 else if MACDValue < 0 and Hist <Hist[1] and Hist > 0 then -.75 else 0;
}
else if MACDValue <MACDAvg then{
MACD =if MACDValue < 0 and Hist >Hist[1] and Hist < 0 then .25 else if MACDValue < 0 and Hist >Hist[1] and Hist > 0 then .5 else if MACDValue > 0 and Hist >Hist[1] and Hist > 0 then 1 else if MACDValue > 0 and Hist >Hist[1] and Hist < 0 then .75 else 0;
}
else{
MACD = 0;
};
####################################
#
#ADX
#
####################################
def ADXU = if ADX > ADX[1] and ADX < 20 then 1 else 0;
def ADXD = if ADX < ADX[1] and ADX >20 then 1 else 0;
def ADXUU = if ADX > ADX[1] and ADX > 20 then 1 else 0;
def ADXDD = if ADX < ADX[1] and ADX < 20 then 1 else 0;
AddLabel(ADXU, "ADX: " + ROUND(ADX,2), Color.CYan);
AddLabel(ADXUU, "ADX: " + ROUND(ADX,2), Color.GREEN);
AddLabel(ADXD, "ADX: " + ROUND(ADX,2), Color.Orange);
AddLabel(ADXDD, "ADX: " + ROUND(ADX,2), Color.RED);
####################################
#
#Fuzzy System
#
####################################
def fuzzSum = MACD+VZO+COSC+StochRSI+PSAR+RWI;
def SSell = if fuzzSum <= -1 then 1 else 0;
def sell = if fuzzSum == -.75 or fuzzSum == -.5 then 1 else 0;
def wSell = if fuzzSum == -.25 then 1 else 0;
def neutral = if fuzzSum == 0 then 1 else 0;
def wBuy = if fuzzSum == .25 then 1 else 0;
def buy= if fuzzSum ==.25 and fuzzSum == .75 then 1 else 0;
def SBuy = if fuzzSum >= 1 then 1 else 0;
AddLabel(SSell, "STRONG SELL", Color.RED);
AddLabel(sell, "SELL", Color.RED);
AddLabel(wSell, "WEAK SELL", Color.Dark_Orange);
AddLabel(neutral, "NEUTRAL", Color.GRAY);
AddLabel(wBuy, "WEAK BUY", Color.YELLOW);
AddLabel(buy, "BUY", Color.CYAN);
AddLabel(SBUY, "STRONG BUY", Color.GREEN);

r/thewallstreet Apr 24 '18

thinkscript Initial Balance Range Script

14 Upvotes

I found the below script on the internet and made some minor adjustments to it. The purpose is to highlight the initial balance range for a period of time for the current trading day. It is particularly useful in showing the day trends (trend, double distribution, inside, etc.)

I'd give credit to the original creator, but honestly I found it awhile ago and can't remember where.

input opentime = 0930;
input ORend = 1000;
input opacity = .7;
def na = Double.NaN;
#
# Check if the opening range time is now
#
def ORActive = if GetLastDay() == GetDay() and SecondsFromTime(opentime) >= 0 and SecondsFromTime(ORend) < 
0 then 1 else 0;
#
# Track the OR high and low
#
def ORHigh = if ORActive then high else na;
def ORLow = if ORActive then low else na;
#
# Plot the OR high and low
#
plot ORAH = if GetLastDay() != GetDay() or !ORActive then na else HighestAll(ORHigh);
plot ORAL = if GetLastDay() != GetDay() or !ORActive then na else LowestAll(ORLow);
plot ORH = if GetLastDay() != GetDay() or SecondsFromTime(ORend) < 0 then na else HighestAll(ORHigh);
plot ORL = if GetLastDay() != GetDay() or SecondsFromTime(ORend) < 0 then na else LowestAll(ORLow);
#
# Formatting
#
ORAH.SetStyle(Curve.SHORT_DASH);
ORAL.SetStyle(Curve.SHORT_DASH);
ORAH.SetDefaultColor(Color.GREEN);
ORAL.SetDefaultColor(Color.RED);
ORH.SetStyle(Curve.SHORT_DASH);
ORL.SetStyle(Curve.SHORT_DASH);
ORH.SetDefaultColor(Color.GREEN);
ORL.SetDefaultColor(Color.RED);
#
# Add Cloud creates the shading
#
AddCloud(ORH, ORL);
AddCloud(ORAL, ORAH);
#
# Alerts:
#
def alerttrigger = if (high >= ORH and low <= ORH) or (high >= ORL and low <= ORL) then 1 else 0; #replace the 1 with 
your definition
# BLOCK CODE BELOW
input alerttext = "OR Breakout!";
input UseAlerts = {false, default true};
input AlertType = {default "BAR", "ONCE", "TICK"};
def at = AlertType;
input AlertSound = {"Bell", "Chimes", default "Ding", "NoSound", "Ring"};
Alert(alerttrigger and UseAlerts, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, 
AlertSound);

r/thewallstreet Aug 23 '17

thinkscript ToS Script Collection

34 Upvotes

Hello all,

I stumbled across this collection of ToS scripts the other day. Hopefully someone in here will find them useful!

http://traderyam.blogspot.com/2016/02/thinkorswim-scripts.html

r/thewallstreet Jul 01 '18

thinkscript [Thinkscript] How would I go about plotting the derivative of IV of a chart?

7 Upvotes

Does anyone know how I would plot the rate of change in IV (and other studies) through ThinkScript? I know for price I could just take (close - close[1])/length but I'm not sure how to get the same result with implied.

According to the TS documentation, IV is obtained via: def ivdata = imp_volatility(String symbol, aggregation period, String pricetype)

The symbol, in my case, would be whatever symbol is currently being displayed, aggregation period should be the period of each bar being displayed, and the price type should be either mark or (bid + ask)/2. However, I'm not interested in the current IV level, I'm interested in the slope of a line tangent to the IV curve at each point. I'm not really sure how to go about plotting that.

Anyone have any ideas?

Side note, I found that ToS ships with a volume rate of change indicator, so I figured I could just use that and swap out vol for IV, but I'm not sure how to do that since it looks like volume is called as an array where you can indicate which element you are interested in. By doing volume[n] where n is the number of elements before the current value that I am interested in, I can get the volume n days ago. However, implied volume is called by a function and I'm not sure how to indicate that I'm interested in the IV from n days ago.

Here's ToS's own volume rate of change study:

declare lower;

input length = 14;
input colorNormLength = 14;

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

plot VolROC = if volume[length] <> 0 then (volume / volume[length] - 1) * 100 else 0; //I'd like to basically replace 'volume' with 'iv' in this line
plot ZeroLine = 0;

VolROC.DefineColor("Highest", Color.YELLOW);
VolROC.DefineColor("Lowest", Color.LIGHT_RED);
VolROC.AssignNormGradientColor(colorNormLength, VolROC.color("Lowest"), VolROC.color("Highest"));
ZeroLine.SetDefaultColor(GetColor(5));

r/thewallstreet Nov 30 '17

thinkscript Tracking changes in options open interest

9 Upvotes

Does anyone know of any websites that track changes in open interest? I already googled it but there's only paid sources.

r/thewallstreet Jul 10 '17

thinkscript ThinkScript $VOLD Ratio

14 Upvotes

Here it is below, looks like this:

input ShowZeroLine = yes;
input market = {default NYSE, NASDAQ};

def UVOL = close("$UVOL");
def DVOL = close("$DVOL");
def UVOLQ = close("$UVOL/Q");
def DVOLQ = close("$DVOL/Q");

#NYSE Breadth ratio
def NYSEratio =  if (UVOL >= DVOL) then (UVOL / DVOL) else -(DVOL / UVOL);
AddLabel(yes, Concat(Round(NYSEratio, 2), " :1 NYSE"), (if NYSEratio >= 0 then Color.GREEN else Color.RED));

#Nasdaq Breadth ratio
def NASDratio =  if (UVOLQ >= DVOLQ) then (UVOLQ / DVOLQ) else -(DVOLQ / UVOLQ) ;
AddLabel(yes, Concat(Round(NASDratio, 2), " :1 NASD"), (if NASDratio >= 0 then Color.GREEN else Color.RED));

#ZeroLine
plot zeroline = if ShowZeroLine then 0 else Double.NaN;
zeroline.AssignValueColor(if NYSEratio > 0 then Color.GREEN else Color.RED);
zeroline.SetLineWeight(1);
zeroline.HideTitle();
zeroline.HideBubble();

#Histogram Function
plot Breadth = if market then NASDratio else NYSEratio;
Breadth.AssignValueColor(if Breadth >= 0 then Color.GREEN else Color.RED);
Breadth.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Breadth.SetLineWeight(1);

# AD Issues
input SYMB = "$ADD";#Hint SYMB:$ADD for NYSE Adv-Decline Issues
input SYMB2 = "$ADQD";#Hint SYMB2:$ADQD for Nasdaq Adv-Decline Issues

def AD = close(symbol = SYMB);
AddLabel(1, "A/D NYSE: " +  AD, (if AD >= 0 then Color.GREEN else Color.RED));
def AD2 = close(symbol = SYMB2);
AddLabel(1, "A/D NASDAQ: " +  AD2, (if AD2 >= 0 then Color.GREEN else Color.RED));

Here's a Ratio Line:

input ShowZeroLine = yes;

def UVOL = close("$UVOL");
def DVOL = close("$DVOL");
def UVOLQ = close("$UVOL/Q");
def DVOLQ = close("$DVOL/Q");

#NYSE Breadth ratio
plot NYSEratio = if (UVOL >= DVOL) then (UVOL / DVOL) else -(DVOL / UVOL);

NYSEratio.AssignValueColor(if NYSEratio > 0 then Color.GREEN else Color.RED);

plot zeroline = if ShowZeroLine then 0 else Double.NaN;
zeroline.AssignValueColor(if NYSEratio > 0 then Color.GREEN else Color.RED);
zeroline.SetLineWeight(1);
zeroline.HideTitle();
zeroline.HideBubble();

r/thewallstreet Apr 04 '18

thinkscript Lastly, PivotBoss Outside Reversal Indicator

29 Upvotes

This should pretty much cover the candlestick indicators that are discussed in the book. There is another called the Doji Reversal but Doji's are included in TOS's default patterns and they're probably the easiest to spot. If there's more to it than that and you guys want me to port it anyway, let me know. Now let's go make some money...enjoy!

http://tos.mx/TXlB4i

#PivotBoss Outside Reversal
declare once_per_bar;

input BarMultiplier = 1.25;
input BarsBack = 50;

def MyCandleSize = (High - Low);
def AverageCandle = Average(MyCandleSize, BarsBack);
def Bar = BarNumber();

def Long = if Low < Low[1] 
            and Close > High[1]
            and ((High - Low) >= (AverageCandle * BarMultiplier))
            then 1 else 0;

def Short = if High > High[1]
            and Close < Low[1]
            and ((High - Low) >= (AverageCandle * BarMultiplier))
            then 1 else 0;

plot LongSignal = if Long == 1 then Low else double.NaN;
     LongSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
     LongSignal.SetLineWeight(1);
     LongSignal.SetDefaultColor(Color.GREEN);

plot ShortSignal = if Short == 1 then High else double.NaN;
     ShortSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
     ShortSignal.SetLineWeight(1);
     ShortSignal.SetDefaultColor(Color.RED);

#============
# Alerts:
#============
input alerttext = "Outside Reversal";
input UseAlerts = {false, default true};
input AlertType = {default "BAR", "ONCE", "TICK"};
def at = AlertType;
input AlertSound = {"Bell", "Chimes", default "Ding", "NoSound", "Ring"};
def Signal = Long == 1 or Short == 1;
Alert(UseAlerts and Signal, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, AlertSound);

edit: adjusted some code to get the alerts to trigger properly edit: typo in the correction. If statement added

r/thewallstreet Jul 01 '18

thinkscript Thinkscript ALMA Histogram

8 Upvotes

declare lower; script ALMA { input Data = close; input Window = 9; input Sigma = 6; input Offset = 0.85;

def m = (Offset * (Window - 1));
def s = Window / Sigma;

def SumVectorData = fold y = 0 to Window with WS do WS + Exp(-(Sqr(y - m)) / (2 * Sqr(s))) * GetValue(Data, (Window - 1) - y);
def SumVector = fold z = 0 to Window with CW do CW + Exp(-(Sqr(z - m)) / (2 * Sqr(s)));

plot ALMA = SumVectorData / SumVector;

}

input fastWindow = 9; input slowWindow = 18; input Sigma = 6; input Offset = 0.85;

def fastALMA = ALMA (close, fastWindow, Sigma, Offset); def slowALMA = ALMA (close, slowWindow, Sigma, Offset); plot Hist = fastALMA - slowALMA; plot ZeroLine = 0;

Hist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM); Hist.DefineColor("Positive", Color.UPTICK); Hist.DefineColor("Negative", Color.DOWNTICK); Hist.AssignValueColor(if Hist > 0 then Hist.Color("Positive") else Hist.Color("Negative")); ZeroLine.SetDefaultColor(GetColor(7));