Welcome! Log In Create A New Profile

Get Earnings and Seasonal Trends - Subscribe Today!

Advanced

Fun with ThinkScript

Posted by robert 
Re: Fun with ThinkScript
August 24, 2019 10:44AM
Does anyone have a auto support/resistance line script that plots near price instead of near time?
Let me explain...

I've been using a system recently which emphasizes that time is irrelevant on finding support/resistance near to the current price for trading. Most scripts will find S/R from recent high and low pivots, but you end up with a bunch of lines that are too far away from the current price to be relevant right now, e.g. next resistance line is $10 up but today's trading range is $2, then who cares?
Since how far back S/R is shouldn't matter (3 days or 5 years), I just want to plot the lines nearest to the current price, regardless of when they occurred.

Thanks



Edited 1 time(s). Last edit at 08/24/2019 10:47AM by Cyph3r.
Re: Fun with ThinkScript
August 27, 2019 11:54AM
Hi Robert,

Very new to this forum but have read through the posts. Thanks for a lot of your contribution. Its priceless.

Is there an active link to your TOS screen share somewhere I could use ?

Thanks again
Re: Fun with ThinkScript
September 05, 2019 08:14PM
I’m looking for a way to put a VPOC on each candle regardless of time frame. Does anyone have an idea of how to do this? Thanks
mgv
Converting a bubble study to a scan
September 15, 2019 10:34AM
I have wanted to convert a thinkscript into a scan that only features a single bubble related to implied volatility percentile - different from the one included in Thinkorswim. I would like to make it possible to search stocks that have the percentile in a particular range. This study doesn't work with the scan's "add condition" screen. Any help is appreciated to make this usable.

TOS IV Percentile

Thanks!

declare lower;

# Mark Laczynski
# 3.13.2014

# look at 1 year of history
input length = 252;
#clean up the IV data from TOS
rec clean_iv_r = if (isNaN(imp_volatility()) and !isNaN(close)) then clean_iv_r[1] else imp_volatility();

rec iv_today_r = GetValue(clean_iv_r, -length);


rec bar_number_of_todays_iv_projected_back =
if IsNaN(bar_number_of_todays_iv_projected_back[1]) then 0
else if (isNaN(iv_today_r)) then BarNumber()
else bar_number_of_todays_iv_projected_back [1];


rec iv_today_projected_back_r =
if(IsNAN(iv_today_projected_back_r[1])) then double.nan
else if(!isNaN(iv_today_r)) then iv_today_r
else if(isNaN(clean_iv_r)) then double.nan
else iv_today_projected_back_r[1];

rec is_considered_for_counting_r =
if(isNan(iv_today_projected_back_r)) then double.nan
else if (BarNumber() - bar_number_of_todays_iv_projected_back != 0) then double.nan
else 1;

rec count_is_under_iv_today_r =
if if (isNan(close)) then double.nan
else (isNan(is_considered_for_counting_r )) then 0
else if (clean_iv_r < iv_today_projected_back_r and !isNan(is_considered_for_counting_r )) then count_is_under_iv_today_r[1] + 1
else count_is_under_iv_today_r[1];


AddLabel(yes,concat("Percentile: ", round(count_is_under_iv_today_r * 100 / length,2)));
hello
September 17, 2019 02:31AM
Someone please show me how to create a scan/alert system to run at Market open to find stocks in a watchlist that has the current price at or above Previous day's High, or at or lower that Previous day's Low... I truly appreciate the help!!! Thanks!
Help with script
September 22, 2019 08:49AM
Would like some help to change this script for daily instead of weekly, Also keep the candle colors to stay red and green, Only the REVERSAL AND BREAKOUT candles to change colors.

Thanks for the help

def weekly_reversal = high > high[1] and close<low[1] and open> open[1];
def breakout_up = high[1] > high[2] and close[1] < low[2] and open[1] >open[2] and close > high[1];
def breakout_down = high[1] > high[2] and close[1] < low[2] and open[1] >open[2] and close<low[1];

assignPriceColor(if weekly_reversal then Color.Blue else if breakout_up then color.green else if breakout_down then color.red else color.white);

#Alert
def alerttrigger1 = weekly_reversal;

input alerttext = "!!!!!! TREND Reversal !!!!!";

input UseAlerts = {false, default true};

input AlertType = {default "BAR", "ONCE", "TICK"};

def at = AlertType;

input AlertSound = {"Chimes", "Ring", default "Bell", "NoSound", "Ding"};

Alert (alerttrigger1 and UseAlerts, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, AlertSound);
Help with study
September 23, 2019 07:39AM
Would like to change this study to daily, Also only change candle colors for the REVERSAL and BREAKOUT candles.

Thanks for any help with this.



def weekly_reversal = high > high[1] and close<low[1] and open> open[1];
def breakout_up = high[1] > high[2] and close[1] < low[2] and open[1] >open[2] and close > high[1];
def breakout_down = high[1] > high[2] and close[1] < low[2] and open[1] >open[2] and close<low[1];

assignPriceColor(if weekly_reversal then Color.Blue else if breakout_up then color.green else if breakout_down then color.red else color.white);

#Alert
def alerttrigger1 = weekly_reversal;

input alerttext = "!!!!!! TREND Reversal !!!!!";

input UseAlerts = {false, default true};

input AlertType = {default "BAR", "ONCE", "TICK"};

def at = AlertType;

input AlertSound = {"Chimes", "Ring", default "Bell", "NoSound", "Ding"};

Alert (alerttrigger1 and UseAlerts, alerttext, if at == 1 then Alert.ONCE else if at == 2 then Alert.TICK else Alert.BAR, AlertSound);
Re: Fun with ThinkScript
September 28, 2019 06:48PM
I'm looking for a Volume Profile that shows buying and selling, other platforms have like tradingview but ToS just seems to have one block that i assume is total volume. Looking all around and not having any luck.
Re: Fun with ThinkScript
October 01, 2019 07:50PM
Is there a way to get a star step on close chart? Thanks
Hull Moving Avrage
October 08, 2019 01:29PM
I would love it if I had a column that would indicate if the Hull Moving Average went for bullish to bearish or vice-versa within a bar or two.

Current TDA Code
[
code]
#
# TD Ameritrade IP Company, Inc. (c) 2008-2019
#

input price = close;
input length = 20;
input displace = 0;

plot HMA = MovingAverage(AverageType.HULL, price, length)[-displace];

HMA.DefineColor("Up", GetColor(1));
HMA.DefineColor("Down", GetColor(0));
HMA.AssignValueColor(if HMA > HMA[1] then HMA.color("Up"winking smiley else HMA.color("Down"winking smiley);
[/code]
declare a variable in Scan Stock Hacker
October 10, 2019 04:58PM
Hi all,
I have a script which I use to screen for stocks that are fit into criteria.
The code is a bit long and I got this error:
The complexity of the expression suggests that it may not be reliable with real-time data.

Is there any solution to overcome this error/warning?
Thanks.



Edited 1 time(s). Last edit at 10/12/2019 08:25AM by Sonima.
Re: Fun with ThinkScript
October 21, 2019 01:36AM
Hello, I was wondering if anyone can code something that would display the gap statistics of a ticker.
Something along the lines of this.
Thanks in advance.

could some one convert this indicator to TOS !!eye rolling smiley
October 22, 2019 06:08AM
// Vertex.mq4 версия 0.1а

#property copyright ""
#property link ""

#property indicator_separate_window
#property indicator_buffers 3
#property indicator_minimum 0

#property indicator_color1 Gray
#property indicator_width1 1

#property indicator_color2 Red
#property indicator_width2 2

#property indicator_color3 DodgerBlue
#property indicator_width3 2

extern int TrendPeriod = 30;
extern int ForcePeriod = 35; // для аналогии с TD&FI устанавливаем ForcePeriod = 3 * TrendPeriod

extern double LineValue = 0.25;
extern double VerticalShift = 0;
extern bool alertsOn = true;
extern bool alertsOnCurrent = true;
extern bool alertsMessage = true;
extern bool alertsSound = true;
extern bool alertsEmail = false;
extern bool alertsNotificaton = false;
extern string soundfile = "alert2.wav";

double line[];
double pos_values[];
double neg_values[];

double values[];
double ema[];
double dema[];
double force[];
double trend[];

int init() {
IndicatorBuffers(8);

SetIndexStyle(0, DRAW_LINE); SetIndexBuffer(0, line);
SetIndexStyle(1, DRAW_HISTOGRAM); SetIndexBuffer(1, pos_values); SetIndexEmptyValue(1,VerticalShift);
SetIndexStyle(2, DRAW_HISTOGRAM); SetIndexBuffer(2, neg_values); SetIndexEmptyValue(2,VerticalShift);

SetIndexBuffer(3, values);
SetIndexBuffer(4, ema);
SetIndexBuffer(5, dema);
SetIndexBuffer(6, force);
SetIndexBuffer(7, trend);

return(0);
}

int deinit() {

return(0);
}

int start() {
int idx;
int counted = IndicatorCounted();
if (counted < 0) return (-1);
if (counted > 0) counted--;
int limit = MathMin(Bars-counted,Bars-1);

for (idx = limit; idx >= 0; idx--) ema[idx] = iMA(NULL, 0, TrendPeriod, 0, MODE_EMA, PRICE_CLOSE, idx);
for (idx = limit; idx >= 0; idx--) dema[idx] = iMAOnArray(ema, 0, TrendPeriod, 0, MODE_EMA, idx);

for (idx = limit; idx >= 0; idx--) {
double ema_direct = ema[idx] - ema[idx+1];
double dema_direct = dema[idx] - dema[idx+1];
double delta = MathAbs(ema[idx] - dema[idx]) / Point;
double direct = 0.5*(ema_direct + dema_direct) / Point;
force[idx] = delta * MathPow(direct, 3);
double extremum = FindExtremum(force, ForcePeriod, idx);
if (extremum > 0.0) values[idx] = force[idx] / extremum; else values[idx] = 0.0;
}

for (idx = limit; idx >= 0; idx--) {
line[idx] = VerticalShift+LineValue;
if (values[idx] > 0.0) {pos_values[idx] = VerticalShift+MathAbs(values[idx]); neg_values[idx] = VerticalShift+0.0;}
else if (values[idx] < 0.0) {pos_values[idx] = VerticalShift+0.0; neg_values[idx] = VerticalShift+MathAbs(values[idx]);}
else {pos_values[idx] = VerticalShift+0.0; neg_values[idx] = VerticalShift+0.0;}
}
for (idx=limit; idx>=0; idx--)
{
trend[idx] = trend[idx+1];
if (pos_values[idx]>line[idx])trend[idx] = 1;
if (neg_values[idx]>line[idx])trend[idx] =-1;
}
if (alertsOn)
{
if (alertsOnCurrent)
int whichBar = 0;
else whichBar = 1;
if (trend[whichBar] != trend[whichBar+1])
if (trend[whichBar] == 1)
doAlert("Red crossed line"winking smiley;
else doAlert("Blue crossed line"winking smiley;
}
return(0);
}

double FindExtremum(double& data[], int count, int index) {
double result = 0.0;
for (int idx = count - 1; idx >= 0; idx--)
if (result < MathAbs(data[index+idx])) result = MathAbs(data[index+idx]);
return (result);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void doAlert(string doWhat)
{
static string previousAlert="nothing";
static datetime previousTime;
string message;

if (previousAlert != doWhat || previousTime != Time[0]) {
previousAlert = doWhat;
previousTime = Time[0];

//
//
//
//
//

message = StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Vertex ",doWhat);
if (alertsMessage) Alert(message);
if (alertsEmail) SendMail(StringConcatenate(Symbol()," Vertex "winking smiley,message);
if (alertsNotificaton) SendNotification(StringConcatenate(Symbol()," Vertex ",message));
if (alertsSound) PlaySound(soundfile);
}
}
Re: Fun with ThinkScript
November 06, 2019 01:02AM
Is there a way to make a watchlist up for FP/HRFP or a box in the watchlist when it fires up turns green and fires down red ? Thanks for what you do .
Re: Fun with ThinkScript
November 07, 2019 10:50PM
Hello, Can You help me to code an scan using TTM Squeeze under this condition:

- When the Histogram value of TTM Squeeze is "positive", I would like to find the MINIMUM negative value of the "previous range of the Histogram Negative area".

- Plot when the Positive Histogram value is greater than the [MINIMUM * -1]



<a href="[imgur.com] src="[i.imgur.com]; title="source: imgur.com" /></a>


Thanks in advance.
NMR
Re: Fun with ThinkScript
November 14, 2019 02:21PM
Hi everyone- quick question on TOS scripting:

I have some code in my MACD setting that makes the background pink or green depending on which direction the MACD line is pointing. THe problem is that is makes all of the backgrounds pink or red (all of my other studied)

This is the code:
AssignBackgroundColor( if Value >= Value[1] then
Color.LIGHT_GREEN else Color.PINK);

Is there a way to only make the background of the MACD study a color?

Thank you in advance !!
background of the MACD study
November 15, 2019 04:50PM
See Robert's post: link
Re: Fun with ThinkScript
November 16, 2019 12:19PM
Up arrow when price reverses and closes above the high of the lowest bar

Hi All,

I'm stuck on coding the situation for: Up arrow when price reverses and closes above the high of the lowest bar in a 21 day price channel.

Does anyone know if there's some code for this, or has any ideas about how to do this?

Thanks
TOS label sizing
November 15, 2019 07:30PM
Is there a way to customize label size and/or give a label rudimentary animation based on criteria?
I am adding a label to an existing indicator but the label covers up some data produced by the (colored dot or triangle). I added a plot line with higher value for temp stopgap but would really like to be able to reduce label vertical size so i don't have to have that extra plot line because it increase the space used by the indicators

I am a new forum member but frequent this forum. Great information and tools

thanks in advance
Re: Fun with ThinkScript
November 17, 2019 06:25PM
Hello everyone thank you for the add Robert. I am new here and eager to learn some coding. I just started the tutorial on TOS however I am wondering if anyone knows how to write a formula to provide the turn over ratio. Any information would be greatly appreciated. Thank you.
TOS Correlation() study question
November 17, 2019 11:50PM
I want to be able to trade stock in inverse pairs-to help manage overall risk. I stumbled across this study that came with TOS. I wrote small label and scan study to help in my pair search. My question is there a more efficient way to reach my goal?
I tried inverse SPDRs but I didn't find real any good candidates other than Consumer Cyclical and Consumer Staples sectors.

Here is the simple scan script if anyone wants it-keep in mind I am fairly new to thinkscript so it is basic
-------------------------------------------------------------------------------------------------------------------------
input length = 252; #hint length: the agg-bar length being compared
input TypeOfCorreltion = {default "Direct", "Inverse"};
input correlationWithSecurity = "SPX";#hint correlationWithSecurity; The security that the stock is correlated with
#input inarow = 10;#hint inarow:The number of agg-bars in a row
plot scan;
switch(TypeOfCorreltion)
{
case "Direct":
scan = Correlation(close, close(correlationWithSecurity), length) > .9;#greater then 0.9 indicates a high correlation
case "Inverse":
scan = Correlation(close, close(correlationWithSecurity), length) < .9;
}
---------------------------------------------------------------------------------------------------------------------

thanks
Turn Over Ratio
November 17, 2019 06:21PM
Hello everyone. Does anyone know how I could formulate the turn over ratio for a watchlist column? Any help would be greatly appreciated. Thanking you in advance. Michael
Help with reversal study
November 19, 2019 11:20PM
Hi, i use this script to plot an arrows when a reversal move is detected, this indicator is based on zigzaghighlow, when a reversal is detected plot an arrow if the price turn and go to the new trend the plot of signal keep in the chart, but if the plot appear and the price do not turn and continue with the movement the arrow dissapear, my quiestion is ¿Can you helpme to modify the script to keep in the chart all the arrows no matter if the price turn on or not? i need to know how much times the signal annunce the correct reveral and how much times the signal fail. Thank a lot for your help.

def p = close;
def c = close;
def o = open;
def h = high;
def l = low;
def vv = open < close and close > close[1];
def vr = close < open and close < close[1];

def mm_superFast = 9;
def mm_fast = 14;
def mm_slow = 21;
def displace = 0;

def ema_superFast = ExpAverage(p[-displace], mm_superFast);
def ema_fast = ExpAverage(p[-displace], mm_fast);
def ema_slow = ExpAverage(p[-displace], mm_slow);

def comprar = ema_superFast > ema_fast and ema_fast > ema_slow and low > ema_superFast;
def stopCompra = ema_superFast <= ema_fast;
def comprarAhora = !comprar[1] and comprar;
def senalCompra = CompoundValue(1, if comprarAhora and !stopCompra then 1 else if senalCompra[1] == 1 and stopCompra then 0 else senalCompra[1], 0);

def vender = ema_superFast < ema_fast and ema_fast < ema_slow and h < ema_superFast;
def stopVenta = ema_superFast >= ema_fast;
def venderAhora = !vender[1] and vender;
def senalVenta = CompoundValue(1, if venderAhora and !stopVenta then 1 else if senalVenta[1] == 1 and stopVenta then 0 else senalVenta[1], 0);

def porcentaje = .01;
def revAmount = .05;
def atrreversal = 2.0;
def atrlength = 5;

def averagelength = 5;
def averagetype = AverageType.EXPONENTIAL;
def averageh = MovingAverage(averagetype, h, averagelength);
def averagel = MovingAverage(averagetype, l, averagelength);
def ph = averageh;
def pl = averagel;

def EI = ZigZagHighLow("price h" = ph, "price l" = pl, "percentage reversal" = porcentaje, "absolute reversal" = revAmount, "atr length" = atrlength, "atr reversal" = atrreversal);

rec EISave = if !IsNaN(EI) then EI else GetValue(EISave, 1);
def chg = (if EISave == ph then ph else pl) - GetValue(EISave, 1);
def isUp = chg >= 0;

#Señal de entrada
def EIL = if !IsNaN(EI) and !isUp then pl else GetValue(EIL, 1);
def EIH = if !IsNaN(EI) and isUp then ph else GetValue(EIH, 1);
def dir = CompoundValue(1, if EIL != EIL[1] or pl == EIL[1] and pl == EISave then 1 else if EIH != EIH[1] or ph == EIH[1] and ph == EISave then -1 else dir[1], 0);
def senal = CompoundValue(1, if dir > 0 and pl > EIL then if senal[1] <= 0 then 1 else senal[1] else if dir < 0 and ph < EIH then if senal[1] >= 0 then -1 else senal[1] else senal[1], 0);

def enCALL = senal > 0 and senal[1] <= 0;
def enPUT = senal < 0 and senal[1] >= 0;
Alert(vr and senal > 0 and senal[1] <= 0, "EN CALL", Alert.BAR, Sound.Ring);
Alert(vv and senal < 0 and senal[1] >= 0, "EN PUT", Alert.BAR, Sound.Ring);

plot p_enCALL = enCALL;
p_enCALL.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
p_enCALL.assignValueColor(if vr then Color.GREEN else Color.GRAY);
p_enCALL.SetLineWeight(5);

plot p_enPUT = enPUT;
p_enPUT.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
p_enPUT.assignValueColor(if vv then Color.RED else Color.GRAY);
p_enPUT.SetLineWeight(5);
Keltner Channel label
November 20, 2019 11:01PM
I am trying get a simple label to show keltner channel upper and lower band values-using ATR 1&2 upper and lower channels. The result is prints wrong values-in fact prints same value for upper and lower-see pic below

The study itself shows upper channel(1 ATR) 59.36 Lower(1 ATR) 55.88 but label shows 57.46 for upper and lower
here is the code snippet
###########
input ATR_to_Show = {default "1","2"};
input EMA = 21;
def kelt_upper = KeltnerChannels(length = ema, factor = ATr_To_show, "average type" = "EXPONENTIAL", "true range average type" = "EXPONENTIAL"winking smiley."Upper_Band";
def kelt_lower = KeltnerChannels(length = ema, factor = ATr_To_show, "average type" = "EXPONENTIAL", "true range average type" = "EXPONENTIAL"winking smiley."Lower_Band";

addlabel(yes,"ATR:"+round(atr(),2),color.green);
addlabel(yes,"Keltner(:"+atr_to_show+" ATR):"+"U:"+kelt_upper+"| L:"+ round(kelt_lower,2),color.green);
###########
SSScreen Shot of the label
Re: Fun with ThinkScript
November 22, 2019 01:49PM
Hello! I was looking to see if anyone has an automatic study script for a fibonacci Arcs, Fibonacci Spirals or fibonacci fans? or a piece of code that it can get me start on it?
I'd appreciate it so much, Thank you!
Re: Fun with ThinkScript
November 22, 2019 02:37PM
Hi everyone. Looking for a study/scan to do the following:

Scan for when price closes below an ExpMA on a 3Min TF, and alert when the price pops back up above an EXpMA on 3min TF. All within 2 to 5 bars or so. I want to use it at market open for a red to green type move, but not necessarily on the 1y1day or PreMarket, just intraday.

Any advice will greatly be appreciated. I feel it should be easy enough, but not getting much luck with it.

Thank you
Re: How to get Calendar date of Earning
December 05, 2019 07:41PM
Hi all,
I am wondering if it is possible to get the calendar date of earning?

GetEventOffset(Events.EARNINGS)

this gives date (bars) to earning and skip the weekends, so not possible to add today to the value generated by the above code to get the earning date.
Any solution would be appreciated.
Hey,


There’s a few indicators that I’m having trouble coding in ThinkorSwim (TOS) with Thinkscripter, although I think I have figured out parts of the indicators, however I’m new to coding in Thinkscripter, so there may be errors in my code.

Trading with Market Statistics Indicators:
• Skew: (Intraday VWAP – POC (point of control from intraday volume profile) / Standard Deviation, with the Histogram plotted
• Percentage Ratio of Skew to 1 Standard Deviation: ratio of the skew to the size of ONE standard Deviation. 1 StDev of the current VWAP standard Deviations....which is the distance between the bands, represented as a (%) percent
• Each of the formulas with Adlabels on the chart
Daily Trading Statistics:
• Position Sizing:
• Frog SD: Standard Deviation of the Average Daily Range, represented in ($) Dollars
• With Adlabel(s) on the chart


Here’s some links to J Perl’s Trading with Market Statistics on the following thread(s) for context to what I’m referring to:

If anyone is interested in the concepts: Links to all relevant J Perl’s popular/infamous market statistics methodology for the reasoning behind my coding requests, it’s basically a more advanced market/volume profile trading framework:
• Part 1: [www.traderslaboratory.com]
• Part 2: [www.traderslaboratory.com]
• Part 3: [www.traderslaboratory.com]
• Part 4: [www.traderslaboratory.com]
• Part 5: [www.traderslaboratory.com]
• Part 6: [www.traderslaboratory.com]
• Part 7: [www.traderslaboratory.com]
• Part 8: [www.traderslaboratory.com]
• Part 9: [www.traderslaboratory.com]
• Part 10: [www.traderslaboratory.com]
• Part 11: [www.traderslaboratory.com]
• Questions: [www.traderslaboratory.com]
• Selecting a charting timeframe: [www.traderslaboratory.com]
• Wide/big candles or range bars: [www.traderslaboratory.com]


Specifically on each of the indicators, I do have some of the code figured out, here’s what I have so far with each of the indicators.


Trading with Market Statistics Indicators:
• Skew: (Intraday VWAP – POC (point of control from intraday volume profile) / Standard Deviation, with histogram plotted on the chart
• Percentage Ratio of Skew to 1 Standard Deviation: ratio of the skew to the size of ONE standard Deviation. 1 StDev of the current VWAP standard Deviations....which is the distance between the bands, represented as a (%) percent
• Each of the formulas with Adlabels on the chart


The details of what I have figured out so far with Trading with Market Statistics is down below.

Skew:
Concept:
(mean - mode) / standard deviation

Equivalent Skew Equation:
Skew Definition= (Intraday VWAP (volume weighted average price) – POC (point of control from the intraday volume profile))/Standard Deviation


Here’s the Code I have for the Skew: I think it’s right, it might look ugly but I think that the math is at least right, and I got the Adlabel to pull up on the chart and I double checked the math with standard dev calculators online, it might be good to double check the math

Here’s the code for the Skew:

def RTH = GetTime() >= RegularTradingStart(GetYYYYMMDD()) and
GetTime() <= RegularTradingEnd(GetYYYYMMDD());
def n = if RTH and !RTH[1]
then 1
else if RTH
then n[1] + 1
else n[1];
def Avg = (fold i = 0 to n
with s
do s + getValue(close, i)) / n;
def VWAP_ = (fold ii = 0 to n
with ss
do ss + getValue(vwap, ii)) / n;
#StartScript;

def yyyymmdd = GetYYYYMMDD();
def day_number = DaysFromDate(First(yyyymmdd)) + GetDayOfWeek(First(yyyymmdd));


def FirstBar = SecondsFromTime(0945) >= 0 and SecondsFromTime(0945) < 60 or SecondsFromTime(1000) >= 0 and SecondsFromTime(1000) < 60 or SecondsFromTime(1015) >= 0 and SecondsFromTime(1015) < 60 or SecondsFromTime(1030) >= 0 and SecondsFromTime(1030) < 60 or SecondsFromTime(1045) >= 0 and SecondsFromTime(1045) < 60 or SecondsFromTime(1100) >= 0 and SecondsFromTime(1100) < 60 or SecondsFromTime(1115) >= 0 and SecondsFromTime(1115) < 60 or SecondsFromTime(1130) >= 0 and SecondsFromTime(1130) < 60 or SecondsFromTime(1145) >= 0 and SecondsFromTime(1145) < 60 or SecondsFromTime(1200) >= 0 and SecondsFromTime(1200) < 60 or SecondsFromTime(1215) >= 0 and SecondsFromTime(1215) < 60 or SecondsFromTime(1230) >= 0 and SecondsFromTime(1230) < 60 or SecondsFromTime(1245) >= 0 and SecondsFromTime(1245) < 60 or SecondsFromTime(1300) >= 0 and SecondsFromTime(1300) < 60 or SecondsFromTime(1315) >= 0 and SecondsFromTime(1315) < 60 or SecondsFromTime(1330) >= 0 and SecondsFromTime(1330) < 60 or SecondsFromTime(1345) >= 0 and SecondsFromTime(1345) < 60 or SecondsFromTime(1400) >= 0 and SecondsFromTime(1400) < 60 or SecondsFromTime(1415) >= 0 and SecondsFromTime(1415) < 60 or SecondsFromTime(1430) >= 0 and SecondsFromTime(1430) < 60 or SecondsFromTime(1445) >= 0 and SecondsFromTime(1445) < 60 or SecondsFromTime(1500) >= 0 and SecondsFromTime(1500) < 60 or SecondsFromTime(1515) >= 0 and SecondsFromTime(1515) < 60 or SecondsFromTime(1530) >= 0 and SecondsFromTime(1530) < 60 or SecondsFromTime(1545) >= 0 and SecondsFromTime(1545) < 60 or SecondsFromTime(1600) >= 0 and SecondsFromTime(1600) < 60;


def cond = firstbar;
profile VP = VolumeProfile(pricePerRow = PricePerRow.TICKSIZE, startNewProfile = cond, onExpansion = no);
VP.Show(color = Color.BLACK, "volume poc color" = Color.BLUE);

plot VPOC = VP.GetPointOfControl();
VPOC.SetPaintingStrategy(PaintingStrategy.DASHES);
VPOC.SetDefaultColor(GetColor(9));

#EndScript

def StDev = Sqrt((fold iii = 0 to n
with sss = 0
do sss + Sqr(Avg - getValue(close, iii))) / n);

def Skew=(VWAP_ - VPOC)/StDev;



Adlabel
AddLabel(yes, " Skew= " + (Skew), if Skew > .1 then color.lime else if Skew < .1 then color.pink else color.yellow);


The code may look a little messy but I think I have it correct, if you would like to give an alternative code that’s more accurate for the definition of skew above, then please double check that I have it right

I would like this plotted as its own indicator, to see the context of the skew throughout the trading day, such as a histogram.

Plot Histogram:
I would prefer to have a histogram to plot the skew values, this gives context to the skew values as to where it was, and gives some clues as to where it might be going.


Histogram:
Here’s an example of what the histogram might look like:





Notice in the Histogram Example:
• color.green for positive skew values, above + 0.1
• Color.red for negative skew values, below – 0.1
• Color.yellow for neutral/symmetrical skew values, such as between + 0.1 to – 0.1
• Horizontal Axis: displays the timeframe, time of day
• Vertical Axis: Skew values of the zero line, with Standard Deviations up to 2 or 3 SD

Example Code Above to plot the histogram like it’s shown above:

declare lower;

input price = close;
input length = 30;
input ZavgLength = 30;

Although instead of length, I need upticks of the skew and downticks of the skew, kinda like this, not really sure:


Uptick.DefineColor("Positive", Color.UPTICK);
Uptick.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
Downtick.DefineColor("Negative", Color.DOWNTICK);
Downtick.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
data.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
data.SetLineWeight(3);
ZeroLine.SetDefaultColor(GetColor(5));

Uptick.SetDefaultColor(Color.UPTICK);
Uptick.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
Downtick.SetDefaultColor(Color.DOWNTICK);
Downtick.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


#Initialize values
def oneSD = stdev(price,length);
def avgClose = simpleMovingAvg(price,length);
def ofoneSD = oneSD*price[1];
def Zscorevalue = ((price-avgClose)/oneSD);
def avgZv = average(Zscorevalue,20);

#Compute and plot Z-Score
plot Zscore = ((price-avgClose)/oneSD);
Zscore.setPaintingStrategy(paintingStrategy.HISTOGRAM);
Zscore.setLineWeight(2);
Zscore.assignValueColor(if Zscore > 0 then color.green else color.red);

plot avgZscore = average(Zscorevalue,ZavgLength);
avgZscore.setPaintingStrategy(paintingStrategy.LINE);

#This is an optional plot that will display the momentum of the Z-Score average
#plot momZAvg = (avgZv-avgZv[5]);

#Plot zero line and extreme bands
plot zero = 0;
plot two = 2;
plot negtwo = -2;
zero.setDefaultColor(color.black);

Summary: basically, I want the skew formula turned into a histogram like above just with the skew z-score plotted instead of a price z-score.



Percentage Ratio of Skew to 1 Standard Deviation of the VWAP:
is the ratio of the skew to the size of ONE standard Deviation. I put that there as a possible way to monitor how the skew may be stacking up to current volatility, i.e. the current VWAP standard Deviations....which is the distance between the bands (1 StDev of the VWAP). This should be a better measurement that a fixed number, as it is tied to volatility. The higher the %, the smaller the skew, the less likely a trend is in place.


With an Adlabel
Example: Adlabel (Input 1, Input 2, Input 3)
Inputs:
• Input 1: determines when the label will be displayed.
• If you want the label to always be displayed then substitute "yes" for input 1.
• I need it always displayed such as, AddLabel (yes, input 2, input 3)
• Input 2: determines what the label will display.
• Text, “ % Ratio/StDev= “
• The label can display multiple bits of information by utilizing the "+" symbol.
• Represented as a %
• Input 3: determines what color the label will be. "If … then" statements may also be used to determine the label's color based on differing conditions.
• Color.white for the Adlabel

Example: Addlabel(yes, “ % Ratio/StDev= “ + AsPercent(%Ratio), color.white;


Daily Trading Statistics:

Daily Trading Statistics:
• Position Sizing:
• Frog SD: Standard Deviation of the Average Daily Range, represented in ($) Dollars
• With Adlabel(s) on the chart


This is what I have figured out with the Thinkscript code so far.

Intraday Frog Box StDev Conceptual Definition:
The purpose: of the indicator is to discern price action which is part of a directional move rather than price action that is noise. Once price has progressed further than one frog box, it is reasonable to expect that the stock has begun a trend in the direction of the initial move.

Formula: 1 Standard Deviation of Average Daily Range (30 days “length”)

AvgDailyRange(30) / StDev(30), not sure if this formula describes the above formula


Concept: this can be used to find the standard deviation of the average daily range, this can be used to calibrate the position sizing of your average stock that is daytraded based on the StDev

Coding the indicator:

I need to code the Average Daily Range, not the Average True Range, because I need to filter out the overnight gaps into the calculator, but as far as I can tell the formula for average daily range is messy in Thinkscript, here’s a couple of variations I’ve come up with, not sure which one works better for what I’m trying to achieve:

def length = 30;

def dayHigh = DailyHighLow(AggregationPeriod.DAY, length, 30, no).dailyhigh;
def dayLow = DailyHighLow(AggregationPeriod.DAY, length, 30, no).DailyLow;

def ADR_high = (dayHigh + dayHigh[-1] + dayHigh[-2] + dayHigh[-3] + dayHigh[-4]+ dayHigh[-5]+ dayHigh[-6]+ dayHigh[-7]+ dayHigh[-8]+ dayHigh[-9]+ dayHigh[-10]+ dayHigh[-11]+ dayHigh[-12]+ dayHigh[-13]+ dayHigh[-14]+ dayHigh[-15]+ dayHigh[-16]+ dayHigh[-17]+ dayHigh[-18]+ dayHigh[-19]+ dayHigh[-20]+ dayHigh[-21]+ dayHigh[-22]+ dayHigh[-23]+ dayHigh[-24]+ dayHigh[-25]+ dayHigh[-26]+ dayHigh[-27]+ dayHigh[-28]+ dayHigh[-29]+ dayHigh[-30]) / 30;

def ADR_low = (dayLow + dayLow[-1] + dayLow[-2] + dayLow[-3] + dayLow[-4])+ dayLow[-5]+ dayLow[-6]+ dayLow[-7]+ dayLow[-8]+ dayLow[-9]+ dayLow[-10]+ dayLow[-11]+ dayLow[-12]+ dayLow[-13]+ dayLow[-14]+ dayLow[-15]+ dayLow[-16]+ dayLow[-17]+ dayLow[-18]+ dayLow[-19]+ dayLow[-20]+ dayLow[-21]+ dayLow[-22]+ dayLow[-23]+ dayLow[-24]+ dayLow[-25]+ dayLow[-26]+ dayLow[-27]+ dayLow[-28]+ dayLow[-29]+ dayLow[-30] / 30;

Next Average Daily Range Definition:
def ADR=(ADR_high - ADR_low);

Next: I’m not sure if this part is right, because I need 1 standard deviation of the average daily range, not sure if this is the correct way to code this

input numDevDn = -1.0;
input numDevUp = 1.0;
input displace = 0;
input price=close;
def RTH = (RegularTradingEnd(GetYYYYMMDD()) - RegularTradingStart(GetYYYYMMDD())) / AggregationPeriod.DAY;
def n = if RTH and !RTH[1]
then 1
else if RTH
then n[1] + 1
else n[1];
def Avg = (fold i = 0 to n
with s
do s + getValue(close, i)) / n;

def StDev = Sqrt((fold iii = 0 to n
with sss = 0
do sss + Sqr(Avg - getValue(close, iii))) / n);


def Frog_SD=ADR/StDev(length);

However I’m not sure if this formula is doing it for the last 30 days of the average daily range and 1 standard deviation of that range

plot data=Frog_SD;
plot UpperBand = data + numDevUp * StDev;
plot LowerBand = data + numDevDn * StDev;

UpperBand.setDefaultColor(getColor(2));


With an Adlabel:
Example: Adlabel (Input 1, Input 2, Input 3)
Inputs:
• Input 1: determines when the label will be displayed.
• If you want the label to always be displayed then substitute "yes" for input 1.
• I need it always displayed such as, AddLabel (yes, input 2, input 3)
• Input 2: determines what the label will display.
• Text, “ Frog SD= “
• The label can display multiple bits of information by utilizing the "+" symbol.
• Represented in ($) Dollar Amount
• Input 3: determines what color the label will be. "If … then" statements may also be used to determine the label's color based on differing conditions.
• Color.white for the Adlabel

Example:
AddLabel(yes, " Frog SD= " + AsDollars(Upperband-data), color.white);


However, I’m having trouble putting the elements of the code together, I get some errors in Thinkscript, if someone could help this would be great, thanks


Summary:
I need the following indicators to be coded in ThinkorSwim (TOS) with Thinkscripter:

Trading with Market Statistics Indicators:
• Skew: (Intraday VWAP – POC (point of control from intraday volume profile) / Standard Deviation
• Percentage Ratio of Skew to 1 Standard Deviation: ratio of the skew to the size of ONE standard Deviation. 1 StDev of the current VWAP standard Deviations....which is the distance between the bands, represented as a (%) percent
• Each of the formulas with Adlabels on the chart
Daily Trading Statistics:
• Position Sizing:
• Frog SD: Standard Deviation of the Average Daily Range, represented in ($) Dollars
• With Adlabel(s) on the chart


Thanks for taking a look,
Re: Fun with ThinkScript
December 13, 2019 06:52PM
Looking for some help in converting this trading View script over to TOS appreciate any help
//
// @author Jadbrother modified by gero modified by Chaostrader63
//
//@version=2
study(title = "RCI3lines", shorttitle = "RCI3lines"winking smiley
itvs = input(9, "short interval"winking smiley
itvm = input(26, "middle interval"winking smiley
itvl = input(52, "long interval"winking smiley
src = input(close, "source"winking smiley
upperband=input(title="High line[%]",defval=80,type=integer)
middleband=input(title="Mid line[%]",defval=0,type=integer)
lowerband=input(title="Low line[%]",defval=-80,type=integer)
ord(seq, idx, itv) =>
p = seq[idx]
o = 1
s = 0
for i = 0 to itv - 1
if p < seq
o := o + 1
else
if p == seq
s := s+1
o+(s-1)/2.0
o
d(itv) =>
sum = 0.0
for i = 0 to itv - 1
sum := sum + pow((i + 1) - ord(src, i, itv), 2)
sum
rci(itv) => (1.0 - 6.0 * d(itv) / (itv * (itv * itv - 1.0))) * 100.0
hline(upperband,color=gray,linestyle=dashed)
hline(middleband,color=gray,linestyle=dashed)
hline(lowerband,color=gray,linestyle=dashed)
plot(rci(itvs), title = "RCI short", color = red)
plot(rci(itvm), title = "RCI middle", color = blue)
plot(rci(itvl), title = "RCI long", color = green)
Re: No result when looking for correlation with RUA!
December 17, 2019 05:48AM
Hello all,
I draft a very simple script to scan the market as below:

# Russell 3000 Index (RUA), S&P500 index (SPX)
def close2 = close( "SPX" );
def MA1 = SimpleMovingAvg("price" = close2, "length" = 20)."SMA";
def MA2 = SimpleMovingAvg("price" = close2, "length" = 200)."SMA";

def Rul = (close2 > MA1) or (close2 > MA2);

def TT = If(Rul, 1, 0);
plot TTT = TT == 1;


This works as expected. However, when I change the "SPX" to "RUA" (Russell 3000 Index), it won't return any ticker in the scan, although I am sure several stocks fall within this criteria.
Do I need to use another symbol to address the "Russell 3000 Index" or what?
I appreciate if anyone can help.
Sorry, only registered users may post in this forum.

Click here to login