Convert TradingView Indicator to ThinkorSwim

javin82

New member
I need help converting a pine script indicator into a think script study for Thinkorswim. The name of the indicator is called Range. It is a reversal indicator and plots long and short signals. If you can help me with this, please let me know. Thank you!

PineScript code below:
Code:
//////////////
//@version=3
study("Range fv2",overlay=true)
showTrendLine = input(false, title="Show Trend Line")
colorBars = input(true, title="Color Bars?")
filterTrend = input(true, title="Filter Trend?")

//Source
src = close

//Sampling Period
per = input(defval=25, minval=1, title="Sampling Period")

//Range Multiplier
mult = input(defval=2, minval=0, title="Range Multiplier")

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Definitions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

//Smooth Average Range
smoothrng(x, t, m)=>
    wper      = (t/3) - 1
    avrng     = sma(abs(x - x[1]), t)
    smoothrng = sma(avrng, wper)*m
    smoothrng
smrng = smoothrng(src, per, mult)

//Range Filter
rngfilt(x, r)=>
    rngfilt  = x
    rngfilt := x > nz(rngfilt[1]) ? ((x - r) < nz(rngfilt[1]) ? nz(rngfilt[1]) : (x - r)) : ((x + r) > nz(rngfilt[1]) ? nz(rngfilt[1]) : (x + r))
    rngfilt
filt = rngfilt(src, smrng)

//Filter Direction
upward   = 0.0
upward  := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])

//Target Bands
hband = filt + smrng
lband = filt - smrng

//Colors
filtcolor = upward > 0 ? lime : downward > 0 ? red : orange
barcolor  = (src > filt) and (src > src[1]) and (upward > 0) ? lime : (src > filt) and (src < src[1]) and (upward > 0) ? green : (src < filt) and (src < src[1]) and (downward > 0) ? red : (src < filt) and (src > src[1]) and (downward > 0) ? maroon : orange
barcolor(colorBars ? barcolor : na)

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Plots
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

//Range Filter
if filterTrend == true
    showTrendLine := false
filtplot = plot(filterTrend ? filt : na, color=filtcolor, linewidth=4, title="Range Filter")
//
Factor=input(3, minval=1,maxval = 100)
Pd=input(3, minval=1,maxval = 100)

Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp = 0.0
TrendDown = 0.0
linecolor = na
up = na
down = na
Tsl = 0.0
Trend = 0.0
TrendUp := close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown := close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend := close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl := Trend==1? TrendUp: TrendDown
linecolor := Trend == 1 ? green : red
plot(showTrendLine ? Tsl : na, color = linecolor , style = line , linewidth = 3,title = "SuperTrend")

// Strategy


longCond = na
shortCond = na
longCond :=crossunder(Tsl,filt)
shortCond :=crossover(Tsl,filt)

// Count your long short conditions for more control with Pyramiding

sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])

if longCond
    sectionLongs := sectionLongs + 1
    sectionShorts := 0

if shortCond
    sectionLongs := 0
    sectionShorts := sectionShorts + 1

// Pyramiding

pyrl = 1


// These check to see your signal and cross references it against the pyramiding settings above

longCondition = longCond and sectionLongs <= pyrl
shortCondition = shortCond and sectionShorts <= pyrl

// Get the price of the last opened long or short

last_open_longCondition = na
last_open_shortCondition = na
last_open_longCondition := longCondition ? open : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? open : nz(last_open_shortCondition[1])

// Check if your last postion was a long or a short

last_longCondition = na
last_shortCondition = na
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])

in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition

// Take profit

isTPl = input(true, "Take Profit Long")
isTPs = input(true, "Take Profit Short")
tp = input(5, "Take Profit ", type=float)
long_tp = isTPl and crossover(high, (1+(tp/100))*last_open_longCondition) and longCondition == 0 and in_longCondition  == 1
short_tp = isTPs and crossunder(low, (1-(tp/100))*last_open_shortCondition) and shortCondition == 0 and in_shortCondition == 1


// Create a single close for all the different closing conditions.

long_close = long_tp  ? 1 : 0
short_close = short_tp ? 1 : 0

// Get the time of the last close

last_long_close = na
last_short_close = na
last_long_close := long_close ? time : nz(last_long_close[1])
last_short_close := short_close ? time : nz(last_short_close[1])


// Alerts & Signals

bton(b) => b ? 1 : 0
plotshape(longCondition , title="Long", color=green, textcolor=green, transp=0,
          style=shape.triangleup, location=location.belowbar, size=size.small,text="LONG",offset=0)


plotshape(shortCondition, title="Short", color=red, textcolor=red, transp=0,
          style=shape.triangledown, location=location.abovebar, size=size.small,text="SHORT",offset=0)


//plotshape(longCondition, title = "BUY Signal", text = "Buy", style=shape.triangleup, location=location.belowbar, color = blue, editable = false, transp = 0)
//plotshape(shortCondition, title = "SELL Signal", text = "Sell", style=shape.triangledown, location=location.abovebar, color = black, editable = false, transp = 0)

plotshape(long_tp and last_longCondition > nz(last_long_close[1]), text ="TP", title="Take Profit Long", style=shape.triangledown,
   location=location.abovebar, color = red, editable = false, transp = 0)
plotshape(short_tp and last_shortCondition > nz(last_short_close[1]) , text ="TP", title="Take Profit Short", style=shape.triangleup,
   location=location.belowbar, color = lime, editable = false, transp = 0)

alertcondition(bton(longCondition), title="Long Alert")
alertcondition(bton(shortCondition), title="Short Alert")
alertcondition(bton(long_tp and last_longCondition > nz(last_long_close[1])), title="Take Profit Long")
alertcondition(bton(short_tp and last_shortCondition > nz(last_short_close[1])), title="Take Profit Short")

Any help I can get with this will be greatly appreciated! Thank you!

Admin's Notes:

You can now use this thread to make your own request. If there is a TradingView script that you would like to see in ThinkorSwim, please post the source code and link to that script below. We'll try our best to help you with the conversion.

Below are the TradingView scripts that have been converted to TOS.
 
Last edited by a moderator:

tg703

New member
Hi, I'm in search of a script that builds pivots based on VWAP high/low values instead of price high/low values. Optimally it would include Classic and Fib versions out to R5/S5, across day/week/month timeframes.

Here's the only example of a Tradingview version I could find, it's proven to be very accurate in my use so far:
https://www.tradingview.com/script/6uviIKSP-VWAP-Pivots-Classic-Camarilla-Woodie/

Anyone heard of anything like this, or could code it? I'm not quite proficient or familiar enough with thinkScript to piece it together. And to clarify - I don't necessarily want the above script converted exactly as is, since there's a lot of extra stuff in there. Just a simpler version with Classic+Fib pivots using the VWAP values.
 
Last edited:

Volatility Trading Range

VTR is a momentum indicator that shows if a stock is overbought or oversold based on its Weekly and Monthly average volatility trading range.

Download the indicator

Investingtogive

New member
VIP
Does anyone know how to convert Trading View code to TOS ? This is the Trading View code for the SuperTrend ATR - RSI.

Code:
study(title = "SuperTrend ATR + RSI", shorttitle = "SuperTrend ATR + RSI", overlay = true)

//Mode
Factor=input(title="Super Trend", defval=3, minval=1,maxval = 100)
ATR=input(title="ATR", defval=7, minval=1,maxval = 100)
RSI = input(title="RSI", defval=7, minval=1, maxval = 100)

//Super Trend ATR
Up=hl2-(Factor*atr(ATR))
Dn=hl2+(Factor*atr(ATR))

TUp=close[1]>TUp[1]? max(Up,TUp[1]) : Up
TDown=close[1]<TDown[1]? min(Dn,TDown[1]) : Dn

Trend = close > TDown[1] ? 1: close< TUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TUp: TDown

linecolor = Trend == 1 ? green : red

//RSI
src = close,

ep = 2 * RSI - 1
auc = ema( max( src - src[1], 0 ), ep )
adc = ema( max( src[1] - src, 0 ), ep )
x1 = (RSI - 1) * ( adc * 70 / (100-70) - auc)
ub = iff( x1 >= 0, src + x1, src + x1 * (100-70)/70 )
x2 = (RSI - 1) * ( adc * 30 / (100-30) - auc)
lb = iff( x2 >= 0, src + x2, src + x2 * (100-30)/30 )

//Affichage
plot(avg(ub, lb), color=purple, style = line, linewidth=1, title="RSI")
plot(Tsl, color = linecolor , style = line , linewidth = 1,title = "SuperTrend ATR")
 

netarchitech

Well-known member
VIP
@Investingtogive @BenTen I tried to convert the "SuperTrend ATR + RSI" TV script, but ran into a couple of issues...

2020-11-19-18-01-47.png


Code:
##
# TradingView SuperTrend ATR + RSI Indicator Conversion (attempt)
# 11.19.2020
##

## Mode
input Factor = 3;
input ATR = 7;
input RSI = 7;

def src = close;

## SuperTrend ATR
def Up = hl2 - (Factor * ATR(ATR));
def Dn = hl2 + (Factor * ATR(ATR));

def TUp = if src[1] > TUp[1] then Max(Up, TUp[1]) else Up;
def TDown = if src[1] < TDown[1] then Min(Dn, TDown[1]) else Dn;

def Trend = if src > TDown[1] then 1 else if src < TUp[1] then -1 else !IsNaN(Trend[1]);
def Tsl = if Trend == 1 then TUp else TDown;

plot ATRline = if Trend == 1 then Color.GREEN else Color.RED;
ATRline.DefineColor("Up", Color.GREEN);
ATRline.DefineColor("Down", Color.RED);
ATRline.AssignValueColor(if Tsl > Tsl[1] then ATRline.Color("Up") else ATRline.Color("Down"));
ATRline.SetPaintingStrategy(PaintingStrategy.LINE);
    
## RSI
def ep = 2 * RSI - 1;
def auc = ExpAverage( Max( src - src[1], 0 ), ep );
def adc = ExpAverage( Max( src[1] - src, 0 ), ep );
def x1 = (RSI - 1) * ( adc * 70 / (100 - 70) - auc);
def ub = if x1 >= 0 then src + x1 else (src + x1 * (100 - 70) / 70);
def x2 = (RSI - 1) * ( adc * 30 / (100 - 30) - auc);
def lb = if x2 >= 0 then src + x2 else (src + x2 * (100 - 30) / 30);

plot RSIline = (Average(ub, lb));
RSIline.SetDefaultColor(Color.MAGENTA);
RSIline.SetPaintingStrategy(PaintingStrategy.LINE);

Hope this helps...

Good Luck and Good Trading :)
 

Investingtogive

New member
VIP
@netarchitech Thanks again for the head start. I was able to use your converted code and figure out the other issues. Here is the resulting code. Now I have to see if it's a worth while indicator to use.

Code:
##
# TradingView SuperTrend ATR + RSI Indicator Conversion (attempt)
# 11.19.2020
##

## Mode
input Factor = 3;
input ATR = 7;
input RSI = 7;

def src = close;

## SuperTrend ATR
def Up = hl2 - (Factor * ATR(ATR));
def Dn = hl2 + (Factor * ATR(ATR));

def TUp = if src[1] > TUp[1] then Max(Up, TUp[1]) else Up;
def TDown = if src[1] < TDown[1] then Min(Dn, TDown[1]) else Dn;

def Trend = if src > TDown[1] then 1 else if src < TUp[1] then -1 else Trend[1];

   
## RSI
def ep = 2 * RSI - 1;
def auc = ExpAverage( Max( src - src[1], 0 ), ep );
def adc = ExpAverage( Max( src[1] - src, 0 ), ep );
def x1 = (RSI - 1) * ( adc * 70 / (100 - 70) - auc);
def ub = if x1 >= 0 then src + x1 else (src + x1 * (100 - 70) / 70);
def x2 = (RSI - 1) * ( adc * 30 / (100 - 30) - auc);
def lb = if x2 >= 0 then src + x2 else (src + x2 * (100 - 30) / 30);

plot ATRline = (ub + lb) / 2;
ATRline.DefineColor("Up", Color.GREEN);
ATRline.DefineColor("Down", Color.RED);
ATRline.AssignValueColor(if Trend == 1 then ATRline.Color("Up") else ATRline.Color("Down"));
ATRline.SetPaintingStrategy(PaintingStrategy.LINE);
ATRline.SetDefaultColor(GetColor(1));
 

J007RMC

Well-known member
2019 Donor
ZigZag Fibs

Wondering if it's possible to make this indicator TOS


Code:
//@version=4
//
study("ZigZag ++ fibs", overlay=true)
//
///////////////
// FUNCTIONS //
///////////////

// Function outputs 1 when it's the first bar of the D/W/M/Y
is_newbar(res) =>
    ch = 0
    if(res == 'Y')
        t  = year(time('D'))
        ch := change(t) != 0 ? 1 : 0
    else
        t = time(res)
        ch := change(t) != 0 ? 1 : 0
    ch

// Rounding levels to min tick
nround(x) =>
    n = round(x / syminfo.mintick) * syminfo.mintick

////////////
// INPUTS //
////////////

pp_type                = input(title = 'Pivot Type',               defval = "Fibonacci", options = ["Traditional", "Fibonacci", "Woodie", "Camarilla"])
pp_period              = input(title = "Period",                   defval = "Day",  type = input.string, options = ['Day', 'Week', 'Month', 'Year'])
show_historical_levels = input(title = "Show Historical Levels?",  defval = false,  type = input.bool)
show_level_value       = input(title = "Show Levels Value?",       defval = true,   type = input.bool)
show_current_levels    = input(title = "Show Current Levels",      defval = false,  type = input.bool)

pp_res = pp_period == 'Day' ? 'D' : pp_period == 'Week' ? 'W' : pp_period == 'Month' ? 'M' : 'Y'

/////////////////////
// Get HLC from HT //

// Calc Open
open_cur = 0.0
open_cur := is_newbar(pp_res) ? open : open_cur[1]

popen = 0.0
popen := is_newbar(pp_res) ? open_cur[1] : popen[1]

// Calc High
high_cur = 0.0
high_cur := is_newbar(pp_res) ? high : max(high_cur[1], high)

phigh = 0.0
phigh := is_newbar(pp_res) ? high_cur[1] : phigh[1]

// Calc Low
low_cur = 0.0
low_cur := is_newbar(pp_res) ? low : min(low_cur[1], low)

plow = 0.0
plow := is_newbar(pp_res) ? low_cur[1] : plow[1]

// Calc Close
pclose = 0.0
pclose := is_newbar(pp_res) ? close[1] : pclose[1]


////////////////////////////
// CALCULATE PIVOT POINTS //
////////////////////////////

PP = 0.0
R1 = 0.0, R2 = 0.0, R3 = 0.0
S1 = 0.0, S2 = 0.0, S3 = 0.0

if (pp_type == "Traditional")
    PP := (phigh + plow + pclose) / 3
    R1 := PP     + (PP   - plow)
    S1 := PP     - (phigh - PP)
    R2 := PP     + (phigh - plow)
    S2 := PP     - (phigh - plow)
    R3 := phigh  + 2 * (PP   - plow)
    S3 := plow   - 2 * (phigh - PP)
 
if (pp_type == "Fibonacci")
    PP := (phigh + plow + pclose) / 3
    R1 := PP + (phigh - plow) * 0.382
    S1 := PP - (phigh - plow) * 0.382
    R2 := PP + (phigh - plow) * 0.618
    S2 := PP - (phigh - plow) * 0.618
    R3 := PP + (phigh - plow) * 1.000
    S3 := PP - (phigh - plow) * 1.000
 
if (pp_type == "Woodie")
    PP := (phigh + plow + 2 * popen) / 4
    R1 := PP + (PP - plow)
    S1 := PP - (phigh - PP)
    R2 := PP + (phigh - plow)
    S2 := PP - (phigh - plow)
    R3 := phigh + 2 * (PP - plow)
    S3 := plow  - 2 * (phigh - PP)
   
if (pp_type == "Camarilla")
    PP := (phigh + plow + pclose) / 3
    R1 := pclose + (phigh - plow) * 1.1/12
    S1 := pclose - (phigh - plow) * 1.1/12
    R2 := pclose + (phigh - plow) * 1.1/6
    S2 := pclose - (phigh - plow) * 1.1/6
    R3 := pclose + (phigh - plow) * 1.1/4
    S3 := pclose - (phigh - plow) * 1.1/4

// Projected levels

prPP = 0.0
prR1 = 0.0, prR2 = 0.0, prR3 = 0.0
prS1 = 0.0, prS2 = 0.0, prS3 = 0.0
 
if (pp_type == "Traditional")
    prPP := (high_cur + low_cur + close) / 3
    prR1 := prPP     + (prPP   - low_cur)
    prS1 := prPP     - (high_cur - PP)
    prR2 := prPP     + (high_cur - low_cur)
    prS2 := prPP     - (high_cur - low_cur)
    prR3 := phigh  + 2 * (prPP   - low_cur)
    prS3 := plow   - 2 * (high_cur - PP)  
 
//////////////
// PLOTTING //

bars_sinse = 0
bars_sinse := is_newbar(pp_res) ? 0 : bars_sinse[1] + 1

////////////////////////
// PLOT PIVOTS LEVELS //

vpp_p = line.new(bar_index[min(bars_sinse, 300)], PP, bar_index, PP, color=color.gray,  style =  line.style_solid, extend = extend.none)
vs1_p = line.new(bar_index[min(bars_sinse, 300)], S1, bar_index, S1, color=color.red,   style =  line.style_solid, extend = extend.none)
vs2_p = line.new(bar_index[min(bars_sinse, 300)], S2, bar_index, S2, color=color.red,   style =  line.style_solid, extend = extend.none)
vs3_p = line.new(bar_index[min(bars_sinse, 300)], S3, bar_index, S3, color=color.red,   style =  line.style_solid, extend = extend.none)
vr1_p = line.new(bar_index[min(bars_sinse, 300)], R1, bar_index, R1, color=color.green, style =  line.style_solid, extend = extend.none)
vr2_p = line.new(bar_index[min(bars_sinse, 300)], R2, bar_index, R2, color=color.green, style =  line.style_solid, extend = extend.none)
vr3_p = line.new(bar_index[min(bars_sinse, 300)], R3, bar_index, R3, color=color.green,   style =  line.style_solid, extend = extend.none)

// delete previous lines in the same period
if (not is_newbar(pp_res) or not show_historical_levels)
    line.delete(vpp_p[1])
    line.delete(vs1_p[1])
    line.delete(vs2_p[1]) 
    line.delete(vs3_p[1]) 
    line.delete(vr1_p[1])
    line.delete(vr2_p[1]) 
    line.delete(vr3_p[1])



// Add labels
label_vpp = label.new(bar_index, PP, text=show_level_value ? ("P"  + " " + tostring(nround(PP))) : "P",  style= label.style_none)
label_vs1 = label.new(bar_index, S1, text=show_level_value ? ("S1" + " " + tostring(nround(S1))) : "S1", style= label.style_none)
label_vs2 = label.new(bar_index, S2, text=show_level_value ? ("S2" + " " + tostring(nround(S2))) : "S2", style= label.style_none)
label_vs3 = label.new(bar_index, S3, text=show_level_value ? ("S3" + " " + tostring(nround(S3))) : "S3", style= label.style_none)
label_vr1 = label.new(bar_index, R1, text=show_level_value ? ("R1" + " " + tostring(nround(R1))) : "R1", style= label.style_none)
label_vr2 = label.new(bar_index, R2, text=show_level_value ? ("R2" + " " + tostring(nround(R2))) : "R2", style= label.style_none)
label_vr3 = label.new(bar_index, R3, text=show_level_value ? ("R3" + " " + tostring(nround(R3))) : "R3", style= label.style_none)
   
label.delete(label_vpp[1])
label.delete(label_vs1[1])
label.delete(label_vs2[1])
label.delete(label_vs3[1])
label.delete(label_vr1[1])
label.delete(label_vr2[1])
label.delete(label_vr3[1])   
   
// Projected levels   
line vpp_pr = na
line vs1_pr = na
line vs2_pr = na
line vs3_pr = na
line vr1_pr = na
line vr2_pr = na
line vr3_pr = na

if (show_current_levels)
   
    vpp_pr = line.new(bar_index[1], prPP, bar_index, prPP, color=color.gray,  style =  line.style_dashed, extend = extend.right)
    vs1_pr = line.new(bar_index[1], prS1, bar_index, prS1, color=color.red,   style =  line.style_dashed, extend = extend.right)
    vs2_pr = line.new(bar_index[1], prS2, bar_index, prS2, color=color.red,   style =  line.style_dashed, extend = extend.right)
    vs3_pr = line.new(bar_index[1], prS3, bar_index, prS3, color=color.red,   style =  line.style_dashed, extend = extend.right)
    vr1_pr = line.new(bar_index[1], prR1, bar_index, prR1, color=color.green, style =  line.style_dashed, extend = extend.right)
    vr2_pr = line.new(bar_index[1], prR2, bar_index, prR2, color=color.green, style =  line.style_dashed, extend = extend.right)
    vr3_pr = line.new(bar_index[1], prR3, bar_index, prR3, color=color.green, style =  line.style_dashed, extend = extend.right)
       
    line.delete(vpp_pr[1])
    line.delete(vs1_pr[1])
    line.delete(vs2_pr[1])
    line.delete(vs3_pr[1])
    line.delete(vr1_pr[1])
    line.delete(vr2_pr[1])
    line.delete(vr3_pr[1])
//
Pivot = input(false, title="Show Pivot High/Lows")
LP = input(defval = 4, title = "Left bars for Pivot")
RP = input(defval = 3, title = "Right bars for Pivot")

PH1 = pivothigh(LP,RP)
PH  = valuewhen(PH1,PH1,0)
plotshape(Pivot and barstate.ishistory?PH1:na,style=shape.circle, color=#FF4500, text = "PH", textcolor=color.orange,location=location.abovebar,  offset=-3, transp = 0, title="Pivot High")
plot(Pivot?PH:na,style=plot.style_circles, linewidth=2,color=security(syminfo.tickerid,timeframe.period,high,barmerge.lookahead_off)<=PH?#FF4500:na,title="Pivot High")

PL1 = pivotlow(LP,RP)
PL  = valuewhen(PL1,PL1,0)
plotshape(Pivot and barstate.ishistory?PL1:na,style=shape.circle, color=#6B8E23, text = "PL", textcolor=color.orange,location=location.belowbar,  offset=-3, transp = 0,title="Pivot High")
plot(Pivot?PL:na,style=plot.style_circles, linewidth=2, color=security(syminfo.tickerid,timeframe.period,low,barmerge.lookahead_off)>=PL?#6B8E23:na,title="Pivot High")

// inputs
Depth       = input(12, title="Depth")  // Depth
Deviation   = input(5, title="Deviation")  // Deviation

// ZigZag
lastlow = 0.0, lasthigh = 0.0
lastlow := nz(lastlow[1])
lasthigh := nz(lasthigh[1])

data(x) =>
    d = security(syminfo.tickerid, timeframe.period, x, gaps = barmerge.gaps_off,  lookahead = barmerge.lookahead_on)
    d
getLow(x, y, z, a) =>
    lastlow = y
    v = data(x)
    m = v==lastlow or data(z) - v > a*syminfo.mintick
    if v!=lastlow
        lastlow := v
    if m
        v := 0.0
    [v,lastlow]
getHigh(x, y, z, a) =>
    lasthigh = y
    v = data(x)
    m = v==lasthigh or v - data(z) > a*syminfo.mintick
    if v!=lasthigh
        lasthigh := v
    if m
        v := 0.0
    [v,lasthigh]

[v,e] = getLow(lowest(Depth), lastlow, low, Deviation)
lastlow := e
zBB =  v != 0.0
[v1,e1] = getHigh(highest(Depth), lasthigh, high, Deviation)
lasthigh := e1
zSS = v1 != 0.0

zigzagDirection = -1
zigzagHigh = 0
zigzagLow = 0
zigzagDirection := zBB ? 0 : zSS ? 1 : nz(zigzagDirection[1], -1)
virtualLow = zigzagLow[1] + 1
if not zBB or (zBB and zigzagDirection == zigzagDirection[1] and low > low[virtualLow])
    zigzagLow := nz(zigzagLow[1]) + 1
virtualHigh = zigzagHigh[1] + 1
if not zSS or (zSS and zigzagDirection == zigzagDirection[1] and high < high[virtualHigh])
    zigzagHigh := nz(zigzagHigh[1]) + 1
a=bar_index-zigzagLow
b=bar_index-zigzagHigh
var color c = na, c := fixnan(a < b[1] ? color.lime : a > b[1] ? color.red : na)
line zigzag = line.new(bar_index-zigzagLow, low[zigzagLow], bar_index-zigzagHigh, high[zigzagHigh], color=c, style=line.style_solid, width=4)
if (zigzagDirection == zigzagDirection[1])
    line.delete(zigzag[1])
   
zzPrevHigh = zigzagHigh[1]
zzPrevLow = zigzagLow[1]  
if not na(zzPrevHigh[1])
    zzPrevHigh := zzPrevHigh[1] + 1
if not na(zzPrevLow[1])
    zzPrevLow := zzPrevLow[1] + 1
if zigzagDirection != zigzagDirection[1]
    if zigzagDirection == 1
        zzPrevHigh := zigzagHigh[1] + 1
    if zigzagDirection == 0
        zzPrevLow := zigzagLow[1] + 1
       

//
f_draw_infopanel(_x, _y, _line, _text, _color)=>
    _rep_text = ""
    for _l = 0 to _line
        _rep_text := _rep_text + "\n"
    _rep_text := _rep_text + _text
    var label _la = na
    label.delete(_la)
    _la := label.new(
         x=_x, y=_y,
         text=_rep_text, xloc=xloc.bar_time, yloc=yloc.price,
         color=color.black, style=label.style_labelup, textcolor=_color, size=size.large)

info_label_off = input(50, title="Info panel offset")
position=input(8500,minval=-0.00001)
posx = timenow + round(change(time)*info_label_off)
posy = position


f_draw_infopanel(posx, posy, 0, "Zigzag", a < b ? color.lime : color.red)
 

Trigun1127

New member
Hey guys I'm looking for an ATR trailing stop band. We all know how ATR trailing stops work but I basically want a band plotted above for taking profit. Here is an exact video of what I'm looking for.

I would prefer it as well if I can customize length of the ATR along with its multiplier, colors for long short switches, and whether or not I want to use a line or dots or whatever. That all might just be included but I have never programmed before.
 

shreyb

New member
Hi,

can anyone help me convert this free RVOL indicator I found on trading view to TOS (thinkScript). The goal is to find the RVOL oof a stock compared to the last 20 days. Ex compare the current vol up till 10 EST to the avg vol up till 10 EST for the last 20 days.

Any help would be appreciated,

Thanks.

Code Below:

Code:
//@version=4
// Created by Matthew J. Slabosz
// www.zenandtheartoftrading.com
study(title="Volume (RVOL By Time of Day)", shorttitle="Volume+")
// Get user input
type = input(title="Market", defval='Stocks', type=input.string, options=['Forex', 'Crypto', 'Futures', 'Stocks', 'TSX Stocks'])
lookback = input(title="Lookback Period", type=input.integer, defval=15)
alertPercent = input(title="Alert At RVOL %", type=input.float, defval=0.0)
barColorOption = input(title="Color Scheme", defval='Price', type=input.string, options=['Heatmap', 'Traffic', 'Trigger', 'Price'])
// Get order/tick volume data
totalVolume = volume - volume
for i = 1 to lookback by 1
    if type == "Forex"
        totalVolume := totalVolume + (timeframe.period == "1" ? 0 :
           timeframe.period == "3" ? 0 : timeframe.period == "5" ? volume[i * 288] :
           timeframe.period == "10" ? volume[i * 144] :
           timeframe.period == "15" ? volume[i * 96] :
           timeframe.period == "30" ? volume[i * 48] :
           timeframe.period == "45" ? volume[i * 32] :
           timeframe.period == "60" ? volume[i * 24] :
           timeframe.period == "120" ? volume[i * 12] :
           timeframe.period == "180" ? volume[i * 8] :
           timeframe.period == "240" ? volume[i * 6] :
           timeframe.period == "D" ? volume[i * 5] :
           timeframe.period == "W" ? volume[i * 4] : 0)
    if type == "Crypto"
        totalVolume := totalVolume + (timeframe.period == "1" ? 0 :
           timeframe.period == "3" ? 0 : timeframe.period == "5" ? volume[i * 288] :
           timeframe.period == "10" ? volume[i * 144] :
           timeframe.period == "15" ? volume[i * 96] :
           timeframe.period == "30" ? volume[i * 48] :
           timeframe.period == "45" ? volume[i * 32] :
           timeframe.period == "60" ? volume[i * 24] :
           timeframe.period == "120" ? volume[i * 12] :
           timeframe.period == "180" ? volume[i * 8] :
           timeframe.period == "240" ? volume[i * 6] :
           timeframe.period == "D" ? volume[i * 7] :
           timeframe.period == "W" ? volume[i * 4] : 0)
    if type == "Stocks"
        totalVolume := totalVolume + (timeframe.period == "1" ? 0 :
           timeframe.period == "3" ? 0 : timeframe.period == "5" ? volume[i * 78] :
           timeframe.period == "10" ? volume[i * 39] :
           timeframe.period == "15" ? volume[i * 26] :
           timeframe.period == "30" ? volume[i * 13] :
           timeframe.period == "45" ? volume[i * 9] :
           timeframe.period == "60" ? volume[i * 7] :
           timeframe.period == "120" ? volume[i * 4] :
           timeframe.period == "180" ? volume[i * 3] :
           timeframe.period == "240" ? volume[i * 2] :
           timeframe.period == "D" ? volume[i * 5] :
           timeframe.period == "W" ? volume[i * 4] : 0)
    if type == "TSX Stocks"
        totalVolume := totalVolume + (timeframe.period == "1" ? 0 :
           timeframe.period == "3" ? 0 : timeframe.period == "5" ? volume[i * 79] :
           timeframe.period == "10" ? volume[i * 40] :
           timeframe.period == "15" ? volume[i * 27] :
           timeframe.period == "30" ? volume[i * 14] :
           timeframe.period == "45" ? volume[i * 9] :
           timeframe.period == "60" ? volume[i * 7] :
           timeframe.period == "120" ? volume[i * 4] :
           timeframe.period == "180" ? volume[i * 3] :
           timeframe.period == "240" ? volume[i * 2] :
           timeframe.period == "D" ? volume[i * 5] :
           timeframe.period == "W" ? volume[i * 4] : 0)
    if type == "Futures"
        totalVolume := totalVolume + (timeframe.period == "1" ? 0 :
           timeframe.period == "3" ? 0 : timeframe.period == "5" ? volume[i * 273] :
           timeframe.period == "15" ? volume[i * 138] :
           timeframe.period == "15" ? volume[i * 92] :
           timeframe.period == "30" ? volume[i * 46] :
           timeframe.period == "45" ? volume[i * 31] :
           timeframe.period == "60" ? volume[i * 23] :
           timeframe.period == "120" ? volume[i * 12] :
           timeframe.period == "180" ? volume[i * 8] :
           timeframe.period == "240" ? volume[i * 6] :
           timeframe.period == "D" ? volume[i * 4] :
           timeframe.period == "W" ? volume[i * 4] : 0)
       
// Calculate average volume for this bar
avgVolume = totalVolume / lookback
// Calculate relative volume percentage for this bar
volumePercent = volume / avgVolume
// Determine if this candle exceeds the average
alert = alertPercent == 0.0 and volume > avgVolume and timeframe.period != "1" and
   timeframe.period != "3" or alertPercent != 0.0 and volumePercent >= alertPercent
  
// Determine volume bar color
barColor = color.gray
// Heatmap Color Scheme
if barColorOption == "Heatmap" and volumePercent >= 0.25
    barColor := #005000
if barColorOption == "Heatmap" and volumePercent >= 0.50
    barColor := #007000
if barColorOption == "Heatmap" and volumePercent >= 0.75
    barColor := #009900
if barColorOption == "Heatmap" and volumePercent >= 1
    barColor := #00dd00
if barColorOption == "Heatmap" and volumePercent >= 2
    barColor := #00ff00
   
// Traffic Light Color Scheme
if barColorOption == "Traffic" and volumePercent >= 1.00
    barColor := #ff1d00
if barColorOption == "Traffic" and volumePercent >= 1.50
    barColor := color.orange
if barColorOption == "Traffic" and volumePercent >= 2.0
    barColor := color.green
if barColorOption == "Traffic" and volumePercent >= 3.0
    barColor := #00ff00
// Trigger Color Scheme
if barColorOption == "Trigger"
    barColor := alert ? color.teal : color.gray
// Colored Scheme
if barColorOption == "Price" and close >= open
    barColor := #5cbcb3
if barColorOption == "Price" and close < open
    barColor := #f37e7c
if alertPercent != 0.0 and volumePercent >= alertPercent
    barColor := color.teal
   
// Draw average volume column
plot(avgVolume, style=plot.style_columns, color=color.gray, title="Average Bars", transp=66)
// Draw current volume column
plot(volume, style=plot.style_columns, color=barColor, title="Volume Bars", transp=0)
// Draw data
plot(avgVolume, style=plot.style_line, color=color.purple, title="Average Line", transp=0)
plot(volumePercent, style=plot.style_line, color=color.blue, title="Percentage", transp=100)
// Send out an alert if this candle meets our conditions
alertcondition(alert, title="Volume Alert!", message="Volume signal for {{ticker}}")
 
I am looking for LBR RSI indicator (three-period RSI of this one period change), but so far no luck. Here is the description from LBR and Connor's "Street Smart" book.

This Pattern uses a one-period rate of change or "momentum" function. This is simply, the difference between today's close and yesterday's close. (i.e., if today;,, closing price was 592 and yesterday's closing price was 596, the difference is -4.)
A three-period RSI of this one period change is calculated. (Most software charting packages allow the user to do studies on studies in just this way.)

Thank you in advance!

Code:
I found TradingView Code:
//@version=3
////////////////////////////////////////////////////////////////////////////////////////////////
//// Momentum Pinball, when you get a buy/sell signal, wait for the next day
//// enter on the high or low of the first hour and place a stop in the low/high
//// of the first hour. If the day you get filled closes profitable you can decide to close
//// the trade buy the end of the day or hold overnight and exit the following morning
////////////////////////////////////////////////////////////////////////////////////////////
study("Momentum Pinball")

rocPeriod = input(title="ROC Period", type=integer, defval=1)
rsiPeriod = input (title="RSI Period", type=integer, defval=3)
oversoldLevel = 30
overboughtLevel = 70

lbrrsi = rsi(roc(close, rocPeriod), rsiPeriod)

buySetup = lbrrsi < oversoldLevel
sellSetup = lbrrsi > overboughtLevel

plotshape(buySetup, color=green, style=shape.triangleup, location=location.bottom)
plotshape(sellSetup, color=red, style=shape.triangledown, location=location.top)
hline(overboughtLevel, title='Overbought', color=#5E606B, linestyle=dashed, linewidth=2)
hline(oversoldLevel, title='Oversold', color=#5E606B, linestyle=dashed, linewidth=2)
plot(lbrrsi, color=#5E606B)
 
Last edited:

hanimusa

New member
@BenTen Hi BenTen
can you please help me for coding this indicator to thinkorswim

Code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at [URL]https://mozilla.org/MPL/2.0/[/URL]
// © blackcat1402
//@version=4

study("[blackcat] L2 KDJ Trading System", overlay=false)

//functions
xrf(values, length) =>
    r_val = float(na)
    if length >= 1
        for i = 0 to length by 1
            if na(r_val) or not na(values[i])
                r_val  :=  values[i]
                r_val
    r_val
xsa(src,len,wei) =>
    sumf = 0.0
    ma = 0.0
    out = 0.0
    sumf  :=  nz(sumf[1]) - nz(src[len]) + src
    ma  :=  na(src[len]) ? na : sumf/len
    out  :=  na(out[1]) ? ma : (src*wei+out[1]*(len-wei))/len
    out

xfl(cond, lbk) =>
    out = 0.0
    itemp = 0
    for i = lbk to 0 by 1
        if itemp > 0
            out := 0.0
            itemp := itemp[1] - 1
            itemp
        else
            if cond[i] == false
                out := 0.0
                out
            else
                out := 1.0
                itemp := lbk + 1
                itemp
    out

// inputs
n1 = input(9, title="n1", type=input.integer, minval = 1)
n2 = input(3, title="n2", type=input.integer, minval = 1)
n3 = input(3, title="n3", type=input.integer, minval = 1)

rsv = (((close - lowest(low,n1)) / (highest(high,n1) - lowest(low,n1))) * 100)
k = xsa(rsv,n2,1)
d = xsa(k,n3,1)
j = 3*k-2*d

//plot KD candles
plotcandle(k, d, k, d, color=k>=d?color.yellow:na)
plotcandle(k, d, k, d, color=d>k?color.fuchsia:na)

//short entry
shortentry = iff(xfl(k[1]>d[1] and k<=d and j>50,4), 75, 100)
pse0 = plot(shortentry,color=color.red, linewidth=2,style=plot.style_line, transp=0)

//threshold lines
h1 = hline(80,color=color.red, linestyle=hline.style_dotted)
h2 = hline(20, color=color.yellow, linestyle=hline.style_dotted)
h3 = hline(10,color=color.lime, linestyle=hline.style_dotted)
h4 = hline(90, color=color.fuchsia, linestyle=hline.style_dotted)
fill(h2,h3,color=color.yellow,transp=70)
fill(h1,h4,color=color.fuchsia,transp=70)

//long entry definitions
x = lowest(j,2)==lowest(j,8)
re = iff(crossover(j,xrf(j+0.01,1)) and x and j<19,25,0)
ple0 = plot(re,color=color.yellow, linewidth=1,style=plot.style_area, transp=0)

//define confirmed long entry signal syn
css = ((close-lowest(low,8))/(highest(high,8)-lowest(low,8))*100)
hh = crossunder(ema(css,3),20)
ce = hh[1]
aa = xrf(close,1)
bbb = xsa(max(close-aa,0),5,1)/xsa(abs(close-aa),5,1)*1000
hhh = bbb-lowest(bbb,10)
ss = (sma(hhh,2)*3+hhh*13)/16
longentry1 = iff(ss>13,sma(ss,2),ss)/6
longentry2 = iff(crossover(longentry1,1) and (longentry1<30),30,1)
ii = longentry2==30
syn = iff(ce and ii, 25, 0)
ple1 = plot(syn,color=color.green, linewidth=1,style=plot.style_area, transp=0)[/i][/i][/i]
 

gameg2l

New member
you got Blackcat's script, too :D
I tried this one, but prefer the one I got on #99 post
Really helpful for dip buy, accuracy is uncanny on large caps.
I only was able to find resources for coding the KDJ, unable to figure out how the histogram was rendered.. :/
 

New Indicator: Buy the Dip

Check out our Buy the Dip indicator and see how it can help you find profitable swing trading ideas. Scanner, watchlist columns, and add-ons are included.

Download the indicator

Similar threads

Top