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:

barbaros

Active member
VIP
@barbaros so, do you use any other indicators ? as you are saying this is lagging three candles.
I use a few indicators detailed on this site. I will try to put some time a side this weekend to look into the TV script more. From what I can tell so far, is it looks for the recent high and low pivot, then marks entries for buy and sell when breaks out of those zones. May be it doesn't re-paint the way it is coded. I'm not sure. If a pivot high and low is drawn for the past bars for the current bar, meaning, as the current bar starts, the new high and low pivot points are determined, you will need to be quick to enter the trade before the current bar crosses the breakout points. What I don't know is if you will have enough time to catch the entry or not.
 

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

cswu1211

Member
VIP
Does anyone has an idea on "Vegas Tunnel"?! It seems TradingView has some info https://www.tradingview.com/script/SBHSgNSs-Vegas-Tunnel/

Code:
study("Vegas Tunnel", overlay=true)
length = input(21, minval=1)
fib1 = input(55)
fib2 = input(89)
fib3 = input(144)
fib4 = input(233)

avg = ema(close, length)

fp1 = syminfo.mintick*fib1
fp2 = syminfo.mintick*fib2
fp3 = syminfo.mintick*fib3
fp4 = syminfo.mintick*fib4
plot(avg, color=fuchsia, linewidth=2)

plot(avg + fp1)
plot(avg + fp2)
plot(avg + fp3)
plot(avg + fp4)

plot(avg - fp1)
plot(avg - fp2)
plot(avg - fp3)
plot(avg - fp4)
 
Last edited:

Bladeof300

New member
I have been trying to convert this code for the VQI - Volatility Quality Index - myself, but I cant seem to figure out the nz, cum, and tr functions. This is how far I've made it and I will also include the original code.

Code:
// ORIGiNAL TRADING VIEW
// @author LazyBear
// @credits Thomas Stridsman - http://www.3pips.com/volatility-quality-index-vq/
// If you use this code in its original/modified form, do drop me a note.
//
study("Volatility Quality Index [LazyBear]", shorttitle="VQI_LB")


length_slow=input(9, title="Fast EMA Length")
length_fast=input(200, title="Slow EMA Length")

vqi_t=iff((tr != 0) and ((high - low) != 0) ,(((close-close[1])/tr)+((close-open)/(high-low)))*0.5,nz(vqi_t[1]))
vqi = abs(vqi_t) * ((close - close[1] + (close - open)) * 0.5)
vqi_sum=cum(vqi)
plot(vqi_sum, color=red, linewidth=2)
plot(sma(vqi_sum,length_slow), color=green, linewidth=2)
plot(sma(vqi_sum,length_fast),color=orange, linewidth=2)

//
MY ATTEMPT
input length_slow = 9;
input length_fast = 200;
input averageType = AverageType.EXPONENTIAL;
input averageType2 = AverageType.SIMPLE;

def vqi_t = if((tr != 0) and ((high - low) != 0) , (((close - close[1]) / tr) + ((close - open) / (high - low))) * 0.5, nz(vqi_t[1]));

def vqi = AbsValue(vqi_t) * ((close - close[1] + (close - open)) * 0.5);

def vqi_sum = cum(vqi);

plot signal = ExpAverage(vqi);

plot MOVER = MovingAverage(vqi_sum, ExpAverage(length_slow));

plot BASE = MovingAverage(vqi_sum, ExpAverage(length_fast));[/CODE]
made it
 

NEKSUS

New member
Hello!

Maybe someone will convert this indicator for TOS? (without alertS) I'll be very thankful !
heatmap volumes

Code:
//@version=4

study(title="Heatmap Volume [xdecow]", shorttitle="HVol [xdecow]", max_bars_back=2000, format=format.volume)



//------------------------------------------------------------------------------
// Inputs


length          = input(610, title="MA Length", type=input.integer, minval=2)
slength         = input(610, title='Std Length', type=input.integer, minval=2)
cmode           = input('Heatmap', 'Color Mode', options=['Heatmap', 'Up/Down'])
zmode           = input('Backgrounds', 'Display Heatmap Zones as', options=['None', 'Lines', 'Backgrounds', 'Both'])
bcolor_enabled  = input(true, 'Colored bars')
osc             = input(false, 'Show as oscillator')

thresholdExtraHigh  = input(4, title="Extra High Volume Threshold", type=input.float)
thresholdHigh       = input(2.5, title="High Volume Threshold", type=input.float)
thresholdMedium     = input(1, title="Medium Volume Threshold", type=input.float)
thresholdNormal     = input(-0.5, title="Normal Volume Threshold", type=input.float)



//------------------------------------------------------------------------------
// Colors


// heatmap colors
chm1 = #ff0000 // extra high red
chm2 = #ff7800 // high orange
chm3 = #ffcf03 // medium yellow
chm4 = #a0d6dc // normal
chm5 = #1f9cac // low


// heatmap colors
chmthresholdExtraHigh = input(chm1, 'Heatmap Extra High')
chmthresholdHigh      = input(chm2, 'Heatmap High')
chmthresholdMedium    = input(chm3, 'Heatmap Medium')
chmthresholdNormal    = input(chm4, 'Heatmap Normal')
chmthresholdLow       = input(chm5, 'Heatmap Low')


// up colors
cupthresholdExtraHigh = input(#00FF00, 'Up Extra High')
cupthresholdHigh      = input(#30FF30, 'Up High')
cupthresholdMedium    = input(#60FF60, 'Up Medium')
cupthresholdNormal    = input(#8FFF8F, 'Up Normal')
cupthresholdLow       = input(#BFFFBF, 'Up Low')


// down colors
cdnthresholdExtraHigh = input(#FF0000, 'Down Extra High')
cdnthresholdHigh      = input(#FF3030, 'Down High')
cdnthresholdMedium    = input(#FF6060, 'Down Medium')
cdnthresholdNormal    = input(#FF8F8F, 'Down Normal')
cdnthresholdLow       = input(#FFBFBF, 'Down Low')


// threshold colors
cthresholdExtraHighUp = cmode == 'Heatmap' ? chmthresholdExtraHigh : cupthresholdExtraHigh
cthresholdHighUp      = cmode == 'Heatmap' ? chmthresholdHigh : cupthresholdHigh
cthresholdMediumUp    = cmode == 'Heatmap' ? chmthresholdMedium : cupthresholdMedium
cthresholdNormalUp    = cmode == 'Heatmap' ? chmthresholdNormal : cupthresholdNormal
cthresholdLowUp       = cmode == 'Heatmap' ? chmthresholdLow : cupthresholdLow

cthresholdExtraHighDn = cmode == 'Heatmap' ? chmthresholdExtraHigh : cdnthresholdExtraHigh
cthresholdHighDn      = cmode == 'Heatmap' ? chmthresholdHigh : cdnthresholdHigh
cthresholdMediumDn    = cmode == 'Heatmap' ? chmthresholdMedium : cdnthresholdMedium
cthresholdNormalDn    = cmode == 'Heatmap' ? chmthresholdNormal : cdnthresholdNormal
cthresholdLowDn       = cmode == 'Heatmap' ? chmthresholdLow : cdnthresholdLow



//------------------------------------------------------------------------------
// Calcs


length := length > bar_index + 1 ? bar_index + 1 : length
slength := slength > bar_index + 1 ? bar_index + 1 : slength


pstdev(Series, Period) =>
    mean = sum(Series, Period) / Period
    summation = 0.0
    for i=0 to Period-1
        sampleMinusMean = nz(Series[i]) - mean
        summation := summation + sampleMinusMean * sampleMinusMean
    return = sqrt(summation / Period)


mean    = sma(volume, length)
std     = pstdev(volume, slength)
stdbar  = (volume - mean) / std
dir     = close > open
v       = osc ? volume - mean : volume
mosc    = osc ? 0 : mean


bcolor = stdbar > thresholdExtraHigh ? dir ? cthresholdExtraHighUp : cthresholdExtraHighDn :
  stdbar > thresholdHigh  ? dir ? cthresholdHighUp : cthresholdHighDn :
  stdbar > thresholdMedium ? dir ? cthresholdMediumUp : cthresholdMediumDn :
  stdbar > thresholdNormal ? dir ? cthresholdNormalUp : cthresholdNormalDn :
  dir ? cthresholdLowUp : cthresholdLowDn


// heatmap lines
zshow_lines = zmode == 'Lines' or zmode == 'Both'
zshow_backgrounds = zmode == 'Backgrounds' or zmode == 'Both'

tst = highest(v, min(300, bar_index+1)) * 9999
ts0 = osc ? lowest(v, min(300, bar_index+1)) * 9999 : 0
ts1 = std * thresholdExtraHigh + mosc
ts2 = std * thresholdHigh + mosc
ts3 = std * thresholdMedium + mosc
ts4 = std * thresholdNormal + mosc


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


barcolor(bcolor_enabled ? bcolor : na, editable=false)


// hidden heatmap lines to fill
pt = plot(zshow_backgrounds ? tst : na, color=na, display=display.none, editable=false)
p0 = plot(zshow_backgrounds ? ts0 : na, color=na, display=display.none, editable=false)

p1 = plot(zshow_backgrounds ? ts1 : na, color=na, display=display.none, editable=false)
p2 = plot(zshow_backgrounds ? ts2 : na, color=na, display=display.none, editable=false)
p3 = plot(zshow_backgrounds ? ts3 : na, color=na, display=display.none, editable=false)
p4 = plot(zshow_backgrounds ? ts4 : na, color=na, display=display.none, editable=false)


// heatmap fills
tpf = 85
fill(pt, p1, chm1, transp=tpf, title='Extra High heatmap zone')
fill(p1, p2, chm2, transp=tpf, title='High heatmap zone')
fill(p2, p3, chm3, transp=tpf, title='Medium heatmap zone')
fill(p3, p4, chm4, transp=tpf, title='Normal heatmap zone')
fill(p4, p0, chm5, transp=tpf, title='Low heatmap zone')


// volume
plot(v, color=bcolor, style=plot.style_columns, title='Volume', transp=0, editable=false)


// moving average
plot(osc ? na : mean, color=#000000, linewidth=2, title='Moving Average', style=plot.style_line, transp=0, display=display.none)


// heatmap lines
tpp = 50
plot(zshow_lines ? ts1 : na, color=chm1, title='Extra High heatmap line', transp=tpp)
plot(zshow_lines ? ts2 : na, color=chm2, title='High heatmap line', transp=tpp)
plot(zshow_lines ? ts3 : na, color=chm3, title='Medium heatmap line', transp=tpp)
plot(zshow_lines ? ts4 : na, color=chm4, title='Normal heatmap line', transp=tpp)



//------------------------------------------------------------------------------
// Alerts


conditionExtraHigh  = stdbar > thresholdExtraHigh
conditionHigh       = stdbar <= thresholdExtraHigh and stdbar > thresholdHigh
conditionMedium     = stdbar <= thresholdHigh and stdbar > thresholdMedium
conditionNormal     = stdbar <= thresholdMedium and stdbar > thresholdNormal
conditionLow        = stdbar <= thresholdNormal

alertcondition(conditionExtraHigh, title='Any Extra High Vol', message='Any Bar Extra High Volume Threshold')
alertcondition(conditionExtraHigh and open < close, title='Up Extra High', message='Up Bar Extra High Volume Threshold')
alertcondition(conditionExtraHigh and open > close, title='Down Extra High', message='Down Bar Extra High Volume Threshold')

alertcondition(conditionHigh, title='Any High Vol', message='Any Bar High Volume Threshold')
alertcondition(conditionHigh and open < close, title='Up High Vol', message='Up Bar High Volume Threshold')
alertcondition(conditionHigh and open > close, title='Down High Vol', message='Down Bar High Volume Threshold')

alertcondition(conditionMedium, title='Any Medium Vol', message='Any Bar Medium Volume Threshold')
alertcondition(conditionMedium and open < close, title='Up Medium Vol', message='Up Bar Medium Volume Threshold')
alertcondition(conditionMedium and open > close, title='Down Medium Vol', message='Down Bar Medium Volume Threshold')
 
Last edited:

Prison Mike

Member
I get that this is a TOS forum but could someone help me understand this script? What is it calculating? Float? I see that it finds highest highs, lowest lows but of what?

Would love to use it in a scan.

https://www.tradingview.com/script/Q5mTO9AZ-blackcat-L1-Banker-Entry-Indicator/

Code:
    // ____  __    ___   ________ ___________  ___________ __  ____ ___
   // / __ )/ /   /   | / ____/ //_/ ____/   |/_  __<  / // / / __ |__ \
  // / __  / /   / /| |/ /   / ,< / /   / /| | / /  / / // /_/ / / __/ /
// / /_/ / /___/ ___ / /___/ /| / /___/ ___ |/ /  / /__  __/ /_/ / __/
// /_____/_____/_/  |_\____/_/ |_\____/_/  |_/_/  /_/  /_/  \____/____/                                         

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

study("[blackcat] L1 Banker Entry Indicator", 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


//model of banker model with customized input threshold
bankerthreshold = input(3, title="banker entry threshold", type=input.integer, minval = 1)
bankermodel = (3)*(xsa(((close - lowest(low,27))/(highest(high,27) - lowest(low,27)))*(100),5,1)) - (2)*(xsa(xsa(((close - lowest(low,27))/(highest(high,27) - lowest(low,27)))*(100),5,1),3,1))
pumpdumpsoon = iff(crossover(bankermodel,bankerthreshold),100,0)
longshortentry = iff((bankermodel <= 3),50,0)
bankermove = iff((bankermodel < 5),25,0)

//model banker pump or dump start soon
ppumpdumpsoon = plot(pumpdumpsoon,color=color.green, linewidth=3,style=plot.style_area, transp=30)
//model long short entry
plongshortentry = plot(longshortentry,color=color.orange, linewidth=3,style=plot.style_area, transp=30)
//model banker move
pbankermove = plot(bankermove,color=color.yellow, linewidth=3,style=plot.style_area, transp=70)

@BenTen @XeoNoX @rad14733 @horserider @markos @Welkin
 
Last edited:

Maila

New member
Hi Guys, Hoping you can help convert this to TOS.
https://www.tradingview.com/script/GQZct22g-NM-Improved-Linear-Regression-Bull-and-Bear-Power-v02/

I have partially coded it to get started. I'm still learning and there are mistakes.

Here is what I have so far. Can you guys helps me correct and simplify this?

Code:
input smooth = yes;
input window = 10;
input smap = 5;

def h_value = Highest(high[1], window);
def l_value = Lowest(low[1], window);

def h_bar = BarNumber() - GetMaxValueOffset(close, window);
def l_bar = BarNumber() - GetMinValueOffset(close, window);

def _height = h_value - close;
def _length = BarNumber() - h_bar;
def _ret = _height + (_height / _length);

plot bear = If (_ret > 0, 0 - _ret, 0);

def h_height = close - l_value;
def h_length = BarNumber() - l_bar;
def h_ret = h_height + (h_height / h_length);
def h_ret2 = h_height + (h_height / h_length);
plot bull =  If (h_ret > 0, 0 + h_ret, 0);

script ALMA {
    input Data = close;
    input Window = 10;
    input Offset = 0.85;
    input Sigma = 6;

    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 Offset = 0.85;
input Sigma = 6;

plot zeroline = 0;
plot direction = if smooth then ALMA(bull + bear, smap, 0.9, Sigma) else bull*3 + bear*3;

bull.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
bear.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
bull.AssignValueColor(color.green);
bear.AssignValueColor(color.red);

direction.SetPaintingStrategy(PaintingStrategy.LINE);
direction.SetLineWeight(2);
direction.DefineColor("bull", color.green);
direction.DefineColor("bear", color.red);
direction.AssignValueColor(if direction > direction[1] then direction.color("bull") else if direction < direction[1] then direction.color("bear") else if direction > bull then direction.color("bull") else if direction<bear then direction.color("bear") else color.yellow );
 

GreenCup

New member
VIP
I was wondering if I can get this strategy converted over from trading view.

https://www.tradingview.com/script/FEJvYRkw-Heikin-Ashi-Price-Action-Crypto-LONG-Strategy/

I tired this so far

Code:
input aggregationPeriod = AggregationPeriod.FIFTEEN_MIN;

def close = close(period = aggregationPeriod);
def open = open(period = aggregationPeriod);
def high = high(period = aggregationPeriod);
def low = low(period = aggregationPeriod);

def HAclose = (open + high + low + close ) / 4;
def HAopen = CompoundValue( 1, ( HAopen[1] + HAclose[1] ) / 2, HAclose );
def HAhigh = Max(Max(high , HAopen), HAclose);
def HAlow = Min(Min(low , HAopen), HAhigh);


def long = HAclose > HAhigh[1] and HAclose > HAopen  and HAhigh[1] > HAhigh[2] and close > high[3];

def short =  HAclose < HAopen and HAclose < HAlow[1];


AddChartBubble(long, high, "Bullish", Color.LIGHT_GREEN, no);
AddChartBubble(short, high, "Bearish", Color.LIGHT_RED, no);
 

BenTen

Administrative
Staff
VIP
@GreenCup I don't think that code from TradingView was using Heiken Ashi at all. It was just using the standard open, close, high, and low candles. I don't see where HA was being defined.
 

GreenCup

New member
VIP
@GreenCup I don't think that code from TradingView was using Heiken Ashi at all. It was just using the standard open, close, high, and low candles. I don't see where HA was being defined.
Thanks for looking at this @BenTen.

I was thinking this line of code was doing something for the Heiken Ashi
security(heikinashi(syminfo.tickerid), timeframe.period, close) : close

Should this be sufficient? I was thinking so
def HAclose = (open + high + low + close ) / 4;

This where I'm confused as I get multiple bubble charts on TOS compared to TV
strategy.entry("long",1,when=long)
strategy.close("long",when=short)
 

BenTen

Administrative
Staff
VIP
@GreenCup Oops, you're right. Sorry about that.

I found an issue with your code. You accidentally added "close > high[3]" into the long condition. The TradingView version has this one commented out. But even when I fixed it, the signals still aren't the same.

Next, I changed my chart type to Heiken Ashi candles and used the default open, high, low, and close. That didn't work either.

That code is rather simple and I think you converted it correctly. I'm not able to figure out the exact issue. :(
 

GreenCup

New member
VIP
No worries thanks for looking this over @BenTen

figured it out, I needed AddOrder instead, now to figure out stop loss

AddOrder(OrderType.BUY_AUTO, long, arrowcolor = Color.YELLOW, name = "LONG");
AddOrder(OrderType.SELL_TO_CLOSE, short, arrowcolor = Color.YELLOW, name = "CLOSE");
 
Last edited:

krish_555

New member
VIP
I use a few indicators detailed on this site. I will try to put some time a side this weekend to look into the TV script more. From what I can tell so far, is it looks for the recent high and low pivot, then marks entries for buy and sell when breaks out of those zones. May be it doesn't re-paint the way it is coded. I'm not sure. If a pivot high and low is drawn for the past bars for the current bar, meaning, as the current bar starts, the new high and low pivot points are determined, you will need to be quick to enter the trade before the current bar crosses the breakout points. What I don't know is if you will have enough time to catch the entry or not.
okay thanks. please let us know. once you have a modified one. Thank you.
 

robert7774

New member
Can someone code a tradeview indicator for TOS, here is the link

https://www.tradingview.com/v/Zb0taqNF/

Code:
//@version=3
study("red-sell green-buy TP and SL",overlay=true)

///////////// RSI
RSIlength = input( 16 ,title="RSI Period Length")
RSIvalue = input( 45 ,title="RSI Value Range")
RSIoverSold = 0 + RSIvalue
RSIoverBought = 100 - RSIvalue
price = close
vrsi = rsi(price, RSIlength)


///////////// Bollinger Bands
BBlength = input(20, minval=1,title="Bollinger Bands SMA Period Length")
BBmult = input(2.0, minval=0.001, maxval=50,title="Bollinger Bands Standard Deviation")
BBbasis = sma(price, BBlength)
BBdev = BBmult * stdev(price, BBlength)
BBupper = BBbasis + BBdev
BBlower = BBbasis - BBdev
source = close
buyEntry = crossover(source, BBlower)
sellEntry = crossunder(source, BBupper)
plot(BBbasis, color=aqua,title="Bollinger Bands SMA Basis Line")
p1 = plot(BBupper, color=silver,title="Bollinger Bands Upper Line")
p2 = plot(BBlower, color=silver,title="Bollinger Bands Lower Line")
fill(p1, p2)


///////////// Colors
switch1=input(true, title="Enable Bar Color?")
switch2=input(true, title="Enable Background Color?")
TrendColor =  RSIoverSold and (price[1] < BBlower and price > BBlower)  ? green : na
barcolor(switch1?TrendColor:na)
bgcolor(switch2?TrendColor:na,transp=50)
//

length = input(10)

bband(length, mult) =>
    sma(close, length) + mult * stdev(close, length)
keltner(length, mult) =>
    ema(close, length) + mult * ema(tr, length)

e1 = (highest(high, length) + lowest(low, length)) / 2 + sma(close, length)
osc = linreg(close - e1 / 2, length, 0)
diff = bband(length, 2) - keltner(length, 1)
osc_color = osc[1] < osc[0] ? osc[0] >= 0 ? #00ffff : #cc00cc : osc[0] >= 0 ? #009b9b : #ff9bff
mid_color = diff >= 0 ? green : red
//
method = input(defval="ATR", options=["ATR", "Traditional", "Part of Price"], title="Renko Assignment Method")
methodvalue = input(defval=14.0, type=float, minval=0, title="Value")
pricesource = input(defval="Close", options=["Close", "Open / Close", "High / Low"], title="Price Source")
useClose = pricesource == "Close"
useOpenClose = pricesource == "Open / Close" or useClose
useTrueRange = input(defval="Auto", options=["Always", "Auto", "Never"], title="Use True Range ")
isOscillating=input(defval=true, type=bool, title="Oscillating")
normalize=input(defval=false, type=bool, title="Normalize")
vol = useTrueRange == "Always" or (useTrueRange == "Auto" and na(osc))? tr : osc
op = useClose ? close : open
hi = useOpenClose ? close >= op ? close : op : high
lo = useOpenClose ? close <= op ? close : op : low

if method == "ATR"
    methodvalue := atr(round(methodvalue))
if method == "Part of Price"
    methodvalue := close/methodvalue

currclose = na
prevclose = nz(currclose[1])
prevhigh = prevclose + methodvalue
prevlow = prevclose - methodvalue
currclose := hi > prevhigh ? hi : lo < prevlow ? lo : prevclose

direction = na
direction := currclose > prevclose ? 1 : currclose < prevclose ? -1 : nz(direction[1])
directionHasChanged = change(direction) != 0
directionIsUp = direction > 0
directionIsDown = direction < 0

barcount = 1
barcount := not directionHasChanged and normalize ? barcount[1] + barcount : barcount
vol := not directionHasChanged ? osc[1] + osc : osc
res = barcount > 1 ? vol/barcount : vol



// Conditions

longCond = na
shortCond = na
longCond :=   RSIoverSold and (price[1] < BBlower and price > BBlower) or  direction > 0 and  change(direction) != 0
shortCond :=  direction < 0 and  change(direction) != 0

// 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(false, "Take Profit Long")
isTPs = input(false, "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

// Stop Loss

isSLl = input(false, "Stop Loss Long")
isSLs = input(false, "Stop Loss Short")
sl= 0.0
sl := input(3, "Stop Loss %", type=float)
long_sl = isSLl and crossunder(low, (1-(sl/100))*last_open_longCondition) and longCondition == 0 and in_longCondition == 1
short_sl = isSLs and crossover(high, (1+(sl/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 or long_sl ? 1 : 0
short_close = short_tp or short_sl ? 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 = "Buy Signal", text = "B", style=shape.triangleup, location=location.belowbar, color = green, editable = false, transp = 0)
plotshape(shortCondition, title = "Sell Signal", text = "S", style=shape.triangledown, location=location.abovebar, color = red, 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)

ltp = iff(long_tp and last_longCondition > nz(last_long_close[1]), (1+(tp/100))*last_open_longCondition, na)
plot(ltp, style=cross, linewidth=3, color = white, editable = false)
stp = iff(short_tp and last_shortCondition > nz(last_short_close[1]), (1-(tp/100))*last_open_shortCondition, na)
plot(stp, style = cross, linewidth=3, color = white, editable = false)

plotshape(long_sl and last_longCondition > nz(last_long_close[1]), text ="SL", title="Stop Loss Long", style=shape.triangledown,
   location=location.abovebar, color = red, editable = false, transp = 0)
plotshape(short_sl and last_shortCondition > nz(last_short_close[1]), text ="SL", title="Stop Loss Short", style=shape.triangleup,
   location=location.belowbar, color = lime, editable = false, transp = 0)

lsl = iff(long_sl and last_longCondition > nz(last_long_close[1]), (1-(sl/100))*last_open_longCondition, na)
plot(lsl, style=cross, linewidth=3, color = white, editable = false)
ssl = iff(short_sl and last_shortCondition > nz(last_short_close[1]), (1+(sl/100))*last_open_shortCondition, na)
plot(ssl, style = cross, linewidth=3, color = white, editable = false)

alertcondition(bton(longCondition), title="Buy Alert")
alertcondition(bton(shortCondition), title="Sell 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")
alertcondition(bton(long_sl and last_longCondition > nz(last_long_close[1])), title="Stop Loss Long")
alertcondition(bton(short_sl and last_shortCondition > nz(last_short_close[1])), title="Stop Loss Short")
 

Remix919

New member
Hi there, can someone help me convert the following TradingView script into ThinkorSwim? I just recently switched platforms and the Dynamic Support Resistance v2 script is a really good and indicator to show areas of support and resistance. When price passes through an S/R level it is automatically reversed to either support or resistance. I've done a pretty thorough search through the forums but haven't found this particular script converted yet. Thanks!!

Code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue

//@version=4
study("Support Resistance - Dynamic v2", "SRv2", overlay = true)
prd = input(defval = 10, title="Pivot Period", minval = 4, maxval = 30)
ppsrc = input(defval = 'High/Low', title="Source", options = ['High/Low', 'Close/Open'])
maxnumpp = input(defval = 20, title =" Maximum Number of Pivot", minval = 5, maxval = 100)
ChannelW = input(10, title = "Maximum Channel Width %", minval = 1)
maxnumsr = input(5, title =" Maximum Number of S/R", minval = 1, maxval = 10)
min_strength = input(2, title =" Minimum Strength", minval = 1, maxval = 10)
linestyle = input(defval = 'Dashed', title = "Line Style", options = ['Solid', 'Dotted', 'Dashed'])
linewidth = input(defval = 2, title = "Line Width", minval = 1, maxval = 4)
resistancecolor = input(defval = color.red, title = "Resistance Color", type = input.color)
supportcolor = input(defval = color.lime, title = "Support Color", type = input.color)
showpp = input(false, title = "Show Point Points")

float ph = na, float pl = na
float src1 =  ppsrc == 'High/Low' ? high : max(close, open)
float src2 =  ppsrc == 'High/Low' ? low: min(close, open)
ph := pivothigh(src1, prd, prd)
pl := pivotlow(src2, prd, prd)

plotshape(ph and showpp, text = "H",  style = shape.labeldown, color = na, textcolor = color.red, location = location.abovebar, transp = 0, offset = -prd)
plotshape(pl and showpp, text = "L",  style = shape.labelup, color = na, textcolor = color.lime, location = location.belowbar, transp = 0, offset = -prd)

//calculate maximum S/R channel zone width
prdhighest =  highest(300)
prdlowest = lowest(300)
cwidth = (prdhighest - prdlowest) * ChannelW / 100

var pivotvals= array.new_float(0)

if ph or pl
    array.unshift(pivotvals, ph ? ph : pl)
    if array.size(pivotvals) > maxnumpp // limit the array size
        array.pop(pivotvals)

get_sr_vals(ind)=>
    float lo = array.get(pivotvals, ind)
    float hi = lo
    int numpp = 0
    for y = 0 to array.size(pivotvals) - 1
        float cpp = array.get(pivotvals, y)
        float wdth = cpp <= lo ? hi - cpp : cpp - lo
        if wdth <= cwidth // fits the max channel width?
            lo := cpp <= lo ? cpp : lo
            hi := cpp > lo ? cpp : hi
            numpp := numpp + 1
    [hi, lo, numpp] 

var sr_up_level = array.new_float(0)
var sr_dn_level = array.new_float(0)
sr_strength = array.new_float(0)

find_loc(strength)=>
    ret = array.size(sr_strength)
    if ret > 0
        for i = array.size(sr_strength) - 1 to 0
            if strength <= array.get(sr_strength, i)
                break
            ret := i
    ret

check_sr(hi, lo, strength)=>
    ret = true
    if array.size(sr_up_level) > 0
        for i = 0 to array.size(sr_up_level) - 1
            //included?
            if array.get(sr_up_level, i) >= lo and array.get(sr_up_level, i) <= hi  or
               array.get(sr_dn_level, i) >= lo and array.get(sr_dn_level, i) <= hi
                if strength >= array.get(sr_strength, i)
                    array.remove(sr_strength, i)
                    array.remove(sr_up_level, i)
                    array.remove(sr_dn_level, i)
                    ret
                else
                    ret := false
                break
    ret

//get min time
var int btime = time
btime := na(time[1]) ? btime : min(btime, time - time[1])

round_it(value)=>
    round(value / syminfo.mintick) * syminfo.mintick

draw_line(ycoor, Lstyle)=>
    line.new(x1 = bar_index,
             y1 = ycoor,
             x2 = bar_index - 1,
             y2 = ycoor,
             extend = extend.both,
             color = ycoor >= close ? resistancecolor : supportcolor,
             style = Lstyle,
             width = linewidth)

st = security(syminfo.tickerid, 'D', time)
cl = security(syminfo.tickerid, 'D', time_close)
opened = timenow > st and timenow < cl
    
draw_label(ycoor)=>
    label.new(x = opened ? time + btime * 30 : time[100],
              y = ycoor, text = tostring(ycoor),
              color = ycoor >= close ? color.red : color.lime,
              textcolor = ycoor >= close ? color.white : color.black,
              style = label.style_labeldown,
              xloc = xloc.bar_time,
              yloc = yloc.price)

set_lx(lab, lin)=>
    label.set_x(lab, x = opened ? time + btime * 30 : time[100])
    label.set_color(lab, color = label.get_y(lab) >= close ? color.red : color.lime)
    label.set_textcolor(lab, textcolor = label.get_y(lab) >= close ? color.white : color.black)
    line.set_color(lin, color = line.get_y1(lin) >= close ? resistancecolor : supportcolor)

var line l1 = na, var line l2 = na, var line l3 = na, var line l4 = na, var line l5 = na, var line l6 = na, var line l7 = na, var line l8 = na, var line l9 = na, var line l10 = na
var label lb1 = na, var label lb2 = na, var label lb3 = na, var label lb4 = na, var label lb5 = na, var label lb6 = na, var label lb7 = na, var label lb8 = na, var label lb9 = na, var label lb10 = na

set_lx(lb1, l1), set_lx(lb2, l2), set_lx(lb3, l3), set_lx(lb4, l4), set_lx(lb5, l5), set_lx(lb6, l6), set_lx(lb7, l7), set_lx(lb8, l8), set_lx(lb9, l9), set_lx(lb10, l10)

if ph or pl
    //because of new calculation, remove old S/R levels
    array.clear(sr_up_level)
    array.clear(sr_dn_level)
    array.clear(sr_strength)
    //find S/R zones
    for x = 0 to array.size(pivotvals) - 1
        [hi, lo, strength] = get_sr_vals(x)
        if check_sr(hi, lo, strength)
            loc = find_loc(strength)
            // if strength is in first maxnumsr sr then insert it to the arrays
            if loc < maxnumsr and strength >= min_strength
                array.insert(sr_strength, loc, strength)
                array.insert(sr_up_level, loc, hi)
                array.insert(sr_dn_level, loc, lo)
                // keep size of the arrays = 5
                if array.size(sr_strength) > maxnumsr
                    array.pop(sr_strength)
                    array.pop(sr_up_level)
                    array.pop(sr_dn_level)
    
    line.delete(l1), line.delete(l2), line.delete(l3), line.delete(l4), line.delete(l5), line.delete(l6), line.delete(l7), line.delete(l8), line.delete(l9), line.delete(l10)
    label.delete(lb1), label.delete(lb2), label.delete(lb3), label.delete(lb4), label.delete(lb5), label.delete(lb6), label.delete(lb7), label.delete(lb8), label.delete(lb9), label.delete(lb10)
    if array.size(sr_up_level)
        Lstyle = linestyle == 'Dashed' ? line.style_dashed :
                 linestyle == 'Solid' ? line.style_solid :
                 line.style_dotted
        for x = 0 to array.size(sr_up_level) - 1
            float mid = round_it((array.get(sr_up_level, x) + array.get(sr_dn_level, x)) / 2)
            if x == 0
                l1 := draw_line(mid, Lstyle)
                lb1 := draw_label(mid)
            if x == 1
                l2 := draw_line(mid, Lstyle)
                lb2 := draw_label(mid)
            if x == 2
                l3 := draw_line(mid, Lstyle)
                lb3 := draw_label(mid)
            if x == 3
                l4 := draw_line(mid, Lstyle)
                lb4 := draw_label(mid)
            if x == 4
                l5 := draw_line(mid, Lstyle)
                lb5 := draw_label(mid)
            if x == 5
                l6 := draw_line(mid, Lstyle)
                lb6 := draw_label(mid)
            if x == 6
                l7 := draw_line(mid, Lstyle)
                lb7 := draw_label(mid)
            if x == 7
                l8 := draw_line(mid, Lstyle)
                lb8 := draw_label(mid)
            if x == 8
                l9 := draw_line(mid, Lstyle)
                lb9 := draw_label(mid)
            if x == 9
                l10 := draw_line(mid, Lstyle)
                lb10 := draw_label(mid)

f_crossed_over()=>
    ret = false
    if array.size(sr_up_level) > 0
        for x = 0 to array.size(sr_up_level) - 1
            float mid = round_it((array.get(sr_up_level, x) + array.get(sr_dn_level, x)) / 2)
            if close[1] <= mid and close > mid
                ret := true
    ret

f_crossed_under()=>
    ret = false
    if array.size(sr_up_level) > 0
        for x = 0 to array.size(sr_up_level) - 1
            float mid = round_it((array.get(sr_up_level, x) + array.get(sr_dn_level, x)) / 2)
            if close[1] >= mid and close < mid
                ret := true
    ret

alertcondition(f_crossed_over(), title='Resistance Broken', message='Resistance Broken')
alertcondition(f_crossed_under(), title='Support Broken', message='Support Broken')
 

rad14733

Well-known member
VIP
@Remix919 Does that code do anything S/R indicators here or standard in TOS don't do...??? Did you check before asking someone to do your coding for you...??? Chances are it isn't all that different than other S/R indicators... If you try the others and they truly don't compare, only then should you be asking for code from another platform to be converted...
 

Remix919

New member
@Remix919 Does that code do anything S/R indicators here or standard in TOS don't do...??? Did you check before asking someone to do your coding for you...??? Chances are it isn't all that different than other S/R indicators... If you try the others and they truly don't compare, only then should you be asking for code from another platform to be converted...

I did quite a bit of searching on the forums and tried several S/R indicator codes that I could find, but haven't found anything that is similar to this particular type of S/R indicator, and I think it is quite a good one. I also did try all the S/R studies in ToS but most are pivot-based and I didn't find anything similar to this.
 

pkcfc

New member
VIP
Code:
study(title="Madrid Bollinger Bands Width", shorttitle="MBBW")
src = input(close, type=source)
length = input(34, minval=1), mult = input(2.0, minval=0.001, maxval=50)

basis = sma(src, length)
dev = stdev(src, length)
upper1 = basis + dev
lower1 = basis - dev
upper2 = basis + 2*dev
lower2 = basis - 2*dev

bbw = (upper2 - lower2)*100/lower2

// Output
plot(bbw, color=bbw-ema(bbw,5)>=0?teal:navy, linewidth=2, style=area)
Hey Guys, I found this interesting indicator on TradingView and was wondering if anyone can help me port this to Thinkscript. https://www.tradingview.com/script/Gvi066TT-Madrid-Bollinger-Bands-Width/
 

pkcfc

New member
VIP
@BenTen Thanks! But is there a way it can be plotted smoothly like it is on TradingView? Also In the TradingView Script it seems they're subtracting the EMA(Bandwidth,5) from the Bandwidth to Create the output.
 

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