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:

nktkobby

New member
VIP
Hello All,

I came across this indicator from trading view and I was hoping if someone would help me convert it to TOS format. Thanks

Code:
study(title = "Insync Index [LazyBear]", shorttitle="II_LB")
src=close
div = input(10000, title="EMO Divisor", minval=1)
emoLength = input(14, minval=1, title="EMO length")
fastLength = input(12, minval=1, title="MACD Fast EMA Length")
slowLength=input(26,minval=1, title="MACD Slow EMA Length")
signalLength=input(9,minval=1, title="MACD Signal Length")
mfiLength = input(20, minval=1, title="MFI Length")

calc_emo() => sma(div * change(hl2) * (high - low) / volume, emoLength)
calc_macd(source) =>
    fastMA = ema(source, fastLength)
    slowMA = ema(source, slowLength)
    fastMA - slowMA

calc_mfi(length) =>
    src = hlc3
    upper = sum(volume * (change(src) <= 0 ? 0 : src), length)
    lower = sum(volume * (change(src) >= 0 ? 0 : src), length)
    mf = rsi(upper, lower)
    mf

calc_dpo(period_) => 
    isCentered = false
    barsback = period_/2 + 1
    ma = sma(close, period_)
    dpo = isCentered ? close[barsback] - ma : close - ma[barsback]
    dpo

calc_roc(source, length) =>
    roc = 100 * (source - source[length])/source[length]
    roc

calc_stochD(length, smoothD, smoothK) =>
    k = sma(stoch(close, high, low, length), smoothK)
    d = sma(k, smoothD)
    d

calc_stochK(length, smoothD, smoothK) =>
    k = sma(stoch(close, high, low, length), smoothK)
    //d = sma(k, smoothD)
    k

lengthBB=input(20, title="BB Length"), multBB=input(2.0, title="BB Multiplier")   
lengthCCI=input(14, title="CCI Length")
dpoLength=input(18, title="DPO Length")
lengthROC=input(10, title="ROC Length")
lengthRSI=input(14, title="RSI Length")
lengthStoch=input(14, title="Stoch Length"),lengthD=input(3, title="Stoch D Length"), lengthK=input(1, title="Stoch K Length")
lengthSMA=input(10, title="MA Length")

bolinslb=sma( src,lengthBB ) - multBB * ( stdev( src,lengthBB ) )
bolinsub=sma( src,lengthBB ) + multBB * ( stdev( src,lengthBB ) )
bolins2= (src- bolinslb ) / ( bolinsub - bolinslb )
bolinsll=( bolins2 < 0.05 ? -5 : ( bolins2 > 0.95 ? 5 : 0 ) )
cciins= ( cci(src, lengthCCI) > 100 ? 5 :  ( cci(src, lengthCCI ) < -100 ? -5 : 0 ) )
emvins2= calc_emo() - sma( calc_emo(),lengthSMA)
emvinsb= ( emvins2 < 0 ? ( sma( calc_emo() ,lengthSMA ) < 0 ? -5 : 0 ) : 0 )
emvinss= ( emvins2 > 0 ? ( sma( calc_emo() ,lengthSMA ) > 0 ? 5  : 0 ) : 0 )
macdins2= calc_macd( src) - sma( calc_macd( src) ,lengthSMA )
macdinsb= ( macdins2 < 0 ? ( sma( calc_macd( src),lengthSMA ) < 0 ? -5 : 0 ) : 0 )
macdinss=( macdins2 > 0 ? ( sma( calc_macd( src),lengthSMA) > 0 ? 5 : 0 ) : 0 )
mfiins=( calc_mfi( mfiLength ) > 80 ? 5 : ( calc_mfi( mfiLength ) < 20 ? -5 : 0 ) )
pdoins2=calc_dpo( dpoLength ) - sma( calc_dpo( dpoLength ),lengthSMA )
pdoinsb=( pdoins2 < 0 ? ( sma( calc_dpo( dpoLength ),lengthSMA) < 0 ? -5 : 0 ) :0 )
pdoinss=( pdoins2 > 0 ? ( sma( calc_dpo( dpoLength ),lengthSMA) > 0 ? 5 : 0 ) :0 )
rocins2=calc_roc( src,lengthROC  ) - sma( calc_roc( src,lengthROC ),lengthSMA  )
rocinsb=( rocins2 < 0 ? ( sma( calc_roc( src,lengthROC ),lengthSMA  ) < 0 ? -5 : 0 ) : 0 )
rocinss = ( rocins2 > 0 ? ( sma( calc_roc( src,lengthROC ),lengthSMA ) > 0 ? 5 : 0 ) : 0 )
rsiins= ( rsi(src, lengthRSI ) > 70 ? 5  : ( rsi(src, lengthRSI )  < 30 ? -5 : 0 ) )

stopdins=( calc_stochD(lengthStoch,lengthD,lengthK ) > 80 ? 5 : ( calc_stochD(lengthStoch,lengthD, lengthK ) < 20 ? -5 : 0 ) )
stopkins=( calc_stochK(lengthStoch,lengthD,lengthK) > 80 ? 5 : ( calc_stochK(lengthStoch,lengthD, lengthK ) < 20 ? -5 : 0 ) )

iidx = 50 + cciins + bolinsll + rsiins + stopkins + stopdins + mfiins + emvinsb + emvinss + rocinss + rocinsb + nz(pdoinss[10]) + nz(pdoinsb [10]) + macdinss + macdinsb
ml=plot(50, color=gray, title="Line50")
ll=plot(5, color= green, title="Line5")
ul=plot(95, color = red, title="Line95")

plot(25, color= green, style=3, title="Line25")
plot(75, color = red, style=3, title="Line75")

fill(ml, ll, color=red)
fill(ml, ul, color=green)

il=plot(iidx, color=maroon, linewidth=2, title="InsyncIndex")
fill(ml,il,black)

bc = iidx >= 50 ? (iidx >= 95 ? #336600 : iidx >= 75 ? #33CC00 : #00FF00) :
    (iidx <= 5 ? #990000 : iidx <= 25? #CC3300 :  #CC9900)

ebc = input(false, title="Enable Barcolors")
barcolor(ebc?bc:na)
 

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

Colin

New member
Code:
study(title="Divergence Indicator", format=format.price, resolution="")
len = input(title="RSI Period", minval=1, defval=14)
src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=5)
lbL = input(title="Pivot Lookback Left", defval=5)
rangeUpper = input(title="Max of Lookback Range", defval=60)
rangeLower = input(title="Min of Lookback Range", defval=5)
plotBull = input(title="Plot Bullish", defval=true)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=false)
plotBear = input(title="Plot Bearish", defval=true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=false)
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
osc = rsi(src, len)

plot(osc, title="RSI", linewidth=2, color=#8D1699)
hline(50, title="Middle Line", linestyle=hline.style_dotted)
obLevel = hline(70, title="Overbought", linestyle=hline.style_dotted)
osLevel = hline(30, title="Oversold", linestyle=hline.style_dotted)
fill(obLevel, osLevel, title="Background", color=#9915FF, transp=90)

plFound = na(pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
    bars = barssince(cond == true)
    rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low

oscHL = osc[lbR] > valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Lower Low

priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound

plot(
     plFound ? osc[lbR] : na,
     offset=-lbR,
     title="Regular Bullish",
     linewidth=2,
     color=(bullCond ? bullColor : noneColor),
     transp=0
     )

plotshape(
     bullCond ? osc[lbR] : na,
     offset=-lbR,
     title="Regular Bullish Label",
     text=" Bull ",
     style=shape.labelup,
     location=location.absolute,
     color=bullColor,
     textcolor=textColor,
     transp=0
     )

//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low

oscLL = osc[lbR] < valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Higher Low

priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound

plot(
     plFound ? osc[lbR] : na,
     offset=-lbR,
     title="Hidden Bullish",
     linewidth=2,
     color=(hiddenBullCond ? hiddenBullColor : noneColor),
     transp=0
     )

plotshape(
     hiddenBullCond ? osc[lbR] : na,
     offset=-lbR,
     title="Hidden Bullish Label",
     text=" H Bull ",
     style=shape.labelup,
     location=location.absolute,
     color=bullColor,
     textcolor=textColor,
     transp=0
     )

//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High

oscLH = osc[lbR] < valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Higher High

priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1)

bearCond = plotBear and priceHH and oscLH and phFound

plot(
     phFound ? osc[lbR] : na,
     offset=-lbR,
     title="Regular Bearish",
     linewidth=2,
     color=(bearCond ? bearColor : noneColor),
     transp=0
     )

plotshape(
     bearCond ? osc[lbR] : na,
     offset=-lbR,
     title="Regular Bearish Label",
     text=" Bear ",
     style=shape.labeldown,
     location=location.absolute,
     color=bearColor,
     textcolor=textColor,
     transp=0
     )

//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High

oscHH = osc[lbR] > valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Lower High

priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1)

hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound

plot(
     phFound ? osc[lbR] : na,
     offset=-lbR,
     title="Hidden Bearish",
     linewidth=2,
     color=(hiddenBearCond ? hiddenBearColor : noneColor),
     transp=0
     )

plotshape(
     hiddenBearCond ? osc[lbR] : na,
     offset=-lbR,
     title="Hidden Bearish Label",
     text=" H Bear ",
     style=shape.labeldown,
     location=location.absolute,
     color=bearColor,
     textcolor=textColor,
     transp=0
     )
 

MerryDay

Well-known member
VIP
@Colin a search of this forum returned 269 results for RSI divergences. Which ones did you try and how did they differ substantially from this one??? When preparing your answer, please provide screenshots of this indicator compared to the TOS ones that you tried, along with commentary as to what the issues are.
 

Agiambini

New member
hi, i'm needing to include the tradingview code in TOS, can someone help me.
TKS

the name is XTL+VMA

Code:
float k=0
float pdm=0
float mdm=0
float mdmS=0
float pdmS=0
float s=0
float pdi=0
float mdi=0
float pdiS=0
float mdiS=0
float d=0
float s1=0
float iS=0
float hhv=0
float llv=0
float d1=0
float vI=0
float vma=0
color vmaC=#FF5252
var red=#FF5252
var green=#4CAF50
var blue=#2196F3
var black=#363A45

study("XTL+VMA", overlay=true)
// XTL Input
update_candles_color = input(true, title="Activate (XTL)")
cci_period = input(35, minval=1, title="CCI Period")
fixed_Value = input(37, title="TGT Value")
// VMA Input
show_trend_direction = input(true, title="Activate Trend Direction (VMA)")
vma_length = input(6, title="VMA Length")
src= input(close, title="Source")


// XTL Logic
cci_values = cci(close, cci_period)

var color bar_color = na

if (cci_values < -fixed_Value)
    bar_color := #ff4000
if (-fixed_Value <= cci_values and cci_values <= fixed_Value)
    bar_color := #ffffff
if (cci_values > fixed_Value)
    bar_color := #003cff
    
// VMA Logic
k := 1.0 / vma_length
pdm := max((src - src[1]), 0)
mdm := max((src[1] - src), 0)
pdmS := ((1 - k) * nz(pdmS[1]) + k * pdm)
mdmS := ((1 - k) * nz(mdmS[1]) + k * mdm)
s := pdmS + mdmS
pdi := pdmS / s
mdi := mdmS / s
pdiS := ((1 - k) * nz(pdiS[1]) + k * pdi)
mdiS := ((1 - k) * nz(mdiS[1]) + k * mdi)
d := abs(pdiS - mdiS)
s1 := pdiS + mdiS
iS := ((1 - k) * nz(iS[1]) + k * d / s1)
hhv := highest(iS, vma_length)
llv := lowest(iS, vma_length) 
d1 := hhv - llv
vI := (iS - llv) / d1
vma := (1 - k * vI) * nz(vma[1]) + k * vI * src
vmaC := (vma > vma[1]) ? green : (vma < vma[1]) ? red : (vma == vma[1]) ? blue : black

// Drawing VWA
plot(vma, color=show_trend_direction ? vmaC:black, linewidth=3, title="VMA")
// Change candles color (XTL)
barcolor(update_candles_color ? bar_color : na)
 

rad14733

Well-known member
VIP
@Agiambini Welcome to the usethinkscript forums... Do you have a link to the original script in Tradingview as well as an image of the Study on a chart...??? We don't generally just convert scripts upon request unless there is ample interest, and especially not for new members who only joining minutes ago simply to ask for code conversion... If we did this for each and every request we would never get any of our own coding done... It should also be considered poor forum etiquette...

All that being said, have you used the search feature in an effort to exhaustively research these forums to see if a comparable Thinkscript might already exist, or one that could be further modified to suit your needs...??? Another option is to learn Thinkscript, which should also be considered an expectation... Why expect others to do your coding and then entrust that code to potentially make you money without understanding how it works...???

Trust me, I get more tired of writing this same message over and over again more than members may dislike having to read it...
 

rad14733

Well-known member
VIP
@haha54 I've looked into Adaptive RSI before so I went ahead and wrote the following version for Thinkorswim...

Ruby:
# ARSI
#hint: Adaptive Relative Strength Index Indicator for Thinkscript
# Created by rad14733 for usethinkscript.com
# Plots a colored line on the upper chart based on trend direction.
# v1.0 : 2021-03-28 : Initial Release

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

def rsi = 2 * AbsValue(rsi(length, price, averageType) / 100 - 0.5);

def arsiData = rsi * price + (1 - rsi) * (if isNaN(arsiData[1]) then 0 else arsiData[1]);

plot arsi = arsiData;
arsi.DefineColor("UpTrend", Color.GREEN);
arsi.DefineColor("DownTrend", Color.RED);
arsi.SetLineWeight(2);
arsi.SetPaintingStrategy(PaintingStrategy.LINE);
arsi.SetStyle(Curve.FIRM);
arsi.AssignValueColor(if arsi > arsi[1] then arsi.Color("UpTrend") else arsi.Color("DownTrend"));

# END - ARSI

CL1ciE4.png
 
Last edited:

haha54

Member
Hello,
I was reading this about Adaptive RSI at Trading View. I could not find this RSI here. Can this code be converted to TOS?
https://www.tradingview.com/script/tSpy2kw2-Adaptive-RSI/
Thanks
Nice job Rad it looks great. It should make trading easier for anyone that uses it. I also like the way your lower RSI version looks. If you get a chance can you post the code for that? Those are the only 2 indicators I am going to use.
 

rad14733

Well-known member
VIP
Nice job Rad it looks great. It should make trading easier for anyone that uses it. I also like the way your lower RSI version looks. If you get a chance can you post the code for that? Those are the only 2 indicators I am going to use.
I'll try to get it posted after the market opens... I am just finishing up adding an average line at the moment...
 

gravityflyer

New member
VIP
Hi all,

I was at a dinner party this weekend and met a fellow trader. We geeked out most of the evening chatting trading strategies, and he said that he primarily uses the Potential Breakout (PBO) indicator by ChannelTrend on Trading View.

EaQAH5P.png


I took a look at PBO the other night, and it does appear to be rather promising if used in conjunction with other forms of confirmation. Unfortunately it is a protected script, and I'm trying to figure out what the author used in its creation. The author does say he uses the Bollinger Band Width indicator (20,1) as its basis, although I think he may have done some sort of smoothing? I also suspect that his signal line is perhaps based on the Projection Oscillator? In fact, it looks rather similar to Motion Wave's Projection Oscillator: https://www.motivewave.com/studies/projection_oscillator.htm.

Any thoughts or observations would be greatly appreciated! 🙌
 

Ramesh16

Member
VIP
//method = user defined, default is EMA
//pboPeriod = user defined, default is 14
//sigPeriod = user defined, default is 3
//index = current bar number, LOE = less or equal

mHigh = linRegLine(period, high)[1]; //returns the slope (m) of Linear Regresion line
mLow = linRegLine( period, low)[1];
count = 0;
pbw = 0, pu = 0, pl = Double.MAX_VALUE;
for (i = (index-pboPeriod + 1); i LOE index; i++) //move back 1 period
high = high;
low = low;
vHigh = high + (mHigh * (count));
vLow = low + (mLow * (count));
if (vHigh moreThan pu) pu = vHigh;
if (vLow lessThan pl) pl = vLow;
count++;
endFor
Plot1: PBO = 100 * (price - pl) / (pu - pl);
Plot2: SIG = ma(method, sigPeriod, pbo);
buy = crossedAbove(PBO, SIG);
sell = crossedBelow(PBO, SIG);


######## from the above link, code
 

gravityflyer

New member
VIP
//method = user defined, default is EMA
//pboPeriod = user defined, default is 14
//sigPeriod = user defined, default is 3
//index = current bar number, LOE = less or equal

mHigh = linRegLine(period, high)[1]; //returns the slope (m) of Linear Regresion line
mLow = linRegLine( period, low)[1];
count = 0;
pbw = 0, pu = 0, pl = Double.MAX_VALUE;
for (i = (index-pboPeriod + 1); i LOE index; i++) //move back 1 period
high = high;
low = low;
vHigh = high + (mHigh * (count));
vLow = low + (mLow * (count));
if (vHigh moreThan pu) pu = vHigh;
if (vLow lessThan pl) pl = vLow;
count++;
endFor
Plot1: PBO = 100 * (price - pl) / (pu - pl);
Plot2: SIG = ma(method, sigPeriod, pbo);
buy = crossedAbove(PBO, SIG);
sell = crossedBelow(PBO, SIG);


######## from the above link, code
@Ramesh16,

Yes, that is the Motion Wave code for their Projection Oscillator. Do you suspect it is similar to the Trading View PBO? If so, perhaps we can translate the Motion Wave code for ThinkScript?
 

gravityflyer

New member
VIP
Hi all,

I was at a dinner party this weekend and met a fellow trader. We geeked out most of the evening chatting trading strategies, and he said that he primarily uses the Potential Breakout (PBO) indicator by ChannelTrend on Trading View.

EaQAH5P.png


I took a look at PBO the other night, and it does appear to be rather promising if used in conjunction with other forms of confirmation. Unfortunately it is a protected script, and I'm trying to figure out what the author used in its creation. The author does say he uses the Bollinger Band Width indicator (20,1) as its basis, although I think he may have done some sort of smoothing? I also suspect that his signal line is perhaps based on the Projection Oscillator? In fact, it looks rather similar to Motion Wave's Projection Oscillator: https://www.motivewave.com/studies/projection_oscillator.htm.

Any thoughts or observations would be greatly appreciated! 🙌

So upon further inspection it is clear the original author of the Potential Breakout (PBO) indicator is using a cross-over technique with the Bollinger Band Width indicator and some sort of oscillator. Unfortunately I'm still stuck in terms of identifying the oscillator.

The closest substitute I could find for the PBO is Matt Dougherty's Linear Regression Projection Bands, which seems to be somewhat similar to Motion Wave's Projection Oscillator...

Code:
#credit: Matt Dougherty

Input PB_length = 14;#hint PB_length:Length of the ProjectionBands. Larger values spread the bands further apart.
input LR_length = 10;#hint LR_length:The Linear Regression length. The shorter the length, the more volatile the chart. A good default is 10.

def UPB = ProjectionBands(PB_length).MaxBound;
#def LR_UPB = Inertia(UPB, 10);
def LR_UPB = LinearRegCurve(0, LR_length, UPB);

plot data1 = LR_UPB;
def Min_LR_UPB = if data1 < data1[1] && data1 < data1 [-1] then 1 else 0;

plot D_Min_LR = if Min_LR_UPB == 1 then LR_UPB else double.nan;
D_Min_LR.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
D_Min_LR.SetLineWeight(3);
D_Min_LR.SetDefaultColor(Color.UPTICK);

def Max_LR_UPB = if data1 > data1[1] && data1 > data1 [-1] then 1 else 0;plot D_Max_LR = if Max_LR_UPB == 1 then
LR_UPB else double.nan;

D_Max_LR.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
D_Max_LR.SetLineWeight(3);
D_Max_LR.SetDefaultColor(Color.DOWNTICK);

Although the above code is rather close approximation to the PBO, it is not exact. Some buy/sell signals are the same, while other signals are either late or early. 🙄

Perhaps someone with better ThinkScript coding skills than myself can convert Motion Wave's Projection Oscillator?

Any thoughts, suggestions, or substitutes welcomed!
 

ashfordtrader

New member
Please help convert this pivot points script from TradingView. It's called "floor trader pivots"

////////////////////////////////////////////////////////////
// Copyright by HPotter v1.0 10/07/2014
// Pivot points simply took the high, low, and closing price from the previous period and
// divided by 3 to find the pivot. From this pivot, traders would then base their
// calculations for three support, and three resistance levels. The calculation for the most
// basic flavor of pivot points, known as ‘floor-trader pivots’, along with their support and
// resistance levels.
////////////////////////////////////////////////////////////
study(title="Pivot Point", shorttitle="Pivot Point", overlay = true)
width = input(2, minval=1)
xHigh = security(tickerid,"D", high[1])
xLow = security(tickerid,"D", low[1])
xClose = security(tickerid,"D", close[1])
vPP = (xHigh+xLow+xClose) / 3
vR1 = vPP+(vPP-xLow)
vS1 = vPP-(xHigh - vPP)
vR2 = vPP + (xHigh - xLow)
vS2 = vPP - (xHigh - xLow)
vR3 = xHigh + 2 * (vPP - xLow)
vS3 = xLow - 2 * (xHigh - vPP)
plot(vS1, color=#ff0000, title="S1", style = circles, linewidth = width)
plot(vS2, color=#ff002a, title="S2", style = circles, linewidth = width)
plot(vS3, color=#ff014a, title="S3", style = circles, linewidth = width)
plot(vR1, color=#009600, title="R1", style = circles, linewidth = width)
plot(vR2, color=#006F00, title="R2", style = circles, linewidth = width)
plot(vR3, color=#004900, title="R3", style = circles, linewidth = width)
 

rad14733

Well-known member
VIP
@ashfordtrader You didn't bother posting a link to the original code, nor did you post an image of what this looks like on a chart...

We don't just convert code on request unless there is ample interest... You're more than welcome to convert the code to Thinkscript but we aren't obligated to do your coding for you... I've probably typed this same type of response ten times today, which takes a lot of my time that could be better spent doing my own coding... That's how many requests we get almost every day...

Would you be up to converting ten scripts a day for others, for free...??? Think about it...!!! And trust me, I'm not singling you out... It's just frustrating to have members constantly thinking that others have nothing better to do than write their code for them...

These forums are here for members to learn and to graciously share their personal code to others, not to expect others to do their work for them... Maybe I should just sit back and start asking others to do my coding for me after 37 years of doing my own research, learning different languages, and spending hours upon hours doing what I've never expected others to do for me...

Again, this is directed towards EVERYONE, not just you so don't take it as such...
 

joe362

Member
@rad14733 @MerryDay

Can someone help me to change the trading view scrip to the TOS study?
(that indicator calls the Optimized Trend Tracker )

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

//created by: @Anil_Ozeksi
//developer: ANIL ÖZEKŞİ
//author: @kivancozbilgic

study("Optimized Trend Tracker","OTT", overlay=true)
src = input(close, title="Source")
length=input(2, "OTT Period", minval=1)
percent=input(1.4, "OTT Percent", type=input.float, step=0.1, minval=0)
showsupport = input(title="Show Support Line?", type=input.bool, defval=true)
showsignalsk = input(title="Show Support Line Crossing Signals?", type=input.bool, defval=true)
showsignalsc = input(title="Show Price/OTT Crossing Signals?", type=input.bool, defval=false)
highlight = input(title="Show OTT Color Changes?", type=input.bool, defval=false)
showsignalsr = input(title="Show OTT Color Change Signals?", type=input.bool, defval=false)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
mav = input(title="Moving Average Type", defval="VAR", options=["SMA", "EMA", "WMA", "TMA", "VAR", "WWMA", "ZLEMA", "TSF"])
Var_Func(src,length)=>
    valpha=2/(length+1)
    vud1=src>src[1] ? src-src[1] : 0
    vdd1=src<src[1] ? src[1]-src : 0
    vUD=sum(vud1,9)
    vDD=sum(vdd1,9)
    vCMO=nz((vUD-vDD)/(vUD+vDD))
    VAR=0.0
    VAR:=nz(valpha*abs(vCMO)*src)+(1-valpha*abs(vCMO))*nz(VAR[1])
VAR=Var_Func(src,length)
Wwma_Func(src,length)=>
    wwalpha = 1/ length
    WWMA = 0.0
    WWMA := wwalpha*src + (1-wwalpha)*nz(WWMA[1])
WWMA=Wwma_Func(src,length)
Zlema_Func(src,length)=>
    zxLag = length/2==round(length/2) ? length/2 : (length - 1) / 2
    zxEMAData = (src + (src - src[zxLag]))
    ZLEMA = ema(zxEMAData, length)
ZLEMA=Zlema_Func(src,length)
Tsf_Func(src,length)=>
    lrc = linreg(src, length, 0)
    lrc1 = linreg(src,length,1)
    lrs = (lrc-lrc1)
    TSF = linreg(src, length, 0)+lrs
TSF=Tsf_Func(src,length)
getMA(src, length) =>
    ma = 0.0
    if mav == "SMA"
        ma := sma(src, length)
        ma

    if mav == "EMA"
        ma := ema(src, length)
        ma

    if mav == "WMA"
        ma := wma(src, length)
        ma

    if mav == "TMA"
        ma := sma(sma(src, ceil(length / 2)), floor(length / 2) + 1)
        ma

    if mav == "VAR"
        ma := VAR
        ma

    if mav == "WWMA"
        ma := WWMA
        ma

    if mav == "ZLEMA"
        ma := ZLEMA
        ma

    if mav == "TSF"
        ma := TSF
        ma
    ma
  
MAvg=getMA(src, length)
fark=MAvg*percent*0.01
longStop = MAvg - fark
longStopPrev = nz(longStop[1], longStop)
longStop := MAvg > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop =  MAvg + fark
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := MAvg < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and MAvg > shortStopPrev ? 1 : dir == 1 and MAvg < longStopPrev ? -1 : dir
MT = dir==1 ? longStop: shortStop
OTT=MAvg>MT ? MT*(200+percent)/200 : MT*(200-percent)/200
plot(showsupport ? MAvg : na, color=#0585E1, linewidth=2, title="Support Line")
OTTC = highlight ? OTT[2] > OTT[3] ? color.green : color.red : #B800D9
pALL=plot(nz(OTT[2]), color=OTTC, linewidth=2, title="OTT", transp=0)
alertcondition(cross(OTT[2], OTT[3]), title="Color ALARM", message="OTT Has Changed Color!")
alertcondition(crossover(OTT[2], OTT[3]), title="GREEN ALERT", message="OTT GREEN BUY SIGNAL!")
alertcondition(crossunder(OTT[2], OTT[3]), title="RED ALERT", message="OTT RED SELL SIGNAL!")
alertcondition(cross(MAvg, OTT[2]), title="Cross Alert", message="OTT - Support Line Crossing!")
alertcondition(crossover(MAvg, OTT[2]), title="Crossover Alarm", message="Support Line BUY SIGNAL!")
alertcondition(crossunder(MAvg, OTT[2]), title="Crossunder Alarm", message="Support Line SELL SIGNAL!")
alertcondition(cross(src, OTT[2]), title="Price Cross Alert", message="OTT - Price Crossing!")
alertcondition(crossover(src, OTT[2]), title="Price Crossover Alarm", message="PRICE OVER OTT - BUY SIGNAL!")
alertcondition(crossunder(src, OTT[2]), title="Price Crossunder Alarm", message="PRICE UNDER OTT - SELL SIGNAL!")
buySignalk = crossover(MAvg, OTT[2])
plotshape(buySignalk and showsignalsk ? OTT*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
sellSignallk = crossunder(MAvg, OTT[2])
plotshape(sellSignallk and showsignalsk ? OTT*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
buySignalc = crossover(src, OTT[2])
plotshape(buySignalc and showsignalsc ? OTT*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
sellSignallc = crossunder(src, OTT[2])
plotshape(sellSignallc and showsignalsc ? OTT*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0,display=display.none)
longFillColor = highlighting ? (MAvg>OTT ? color.green : na) : na
shortFillColor = highlighting ? (MAvg<OTT ? color.red : na) : na
fill(mPlot, pALL, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, pALL, title="DownTrend Highligter", color=shortFillColor)
buySignalr = crossover(OTT[2], OTT[3])
plotshape(buySignalr and showsignalsr ? OTT*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
sellSignallr = crossunder(OTT[2], OTT[3])
plotshape(sellSignallr and showsignalsr ? OTT*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
 

MerryDay

Well-known member
VIP
@joe362 It appears to be a moving average study. The single largest group of studies on this forum are moving average studies, scanners, watchlist, etc. So it is probably doable. Did you read through any of the studies already posted?
If there is one similar best course would be to post in that thread w/ any modifications you are looking for.
If none of the studies match, here are some suggestions of the information needed to assist further.
Without a screenshot, there isn't much more to add.
 

Similar threads

Top