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:

rad14733

Well-known member
VIP
@Zeph465 Welcome to the usethinkscript forums... Did you use the search feature in the upper right corner of the page header to determine whether or not there may be a comparable multiple timeframe moving average script already written here in the forums before posting...??? We expect members, even new ones, to use due diligence to do independent research rather than expecting other to do it for them and simply provide links... I'm fairly certain there is something similar here that could be adapted if it doesn't fully suit your needs...
 

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

Zeph465

New member
@Zeph465 Welcome to the usethinkscript forums... Did you use the search feature in the upper right corner of the page header to determine whether or not there may be a comparable multiple timeframe moving average script already written here in the forums before posting...??? We expect members, even new ones, to use due diligence to do independent research rather than expecting other to do it for them and simply provide links... I'm fairly certain there is something similar here that could be adapted if it doesn't fully suit your needs...
Hi, I did use the search function before I posted. I did find something that looks a bit similar but is vastly different. That code had 3 to 4 lines while this one has way more pieces to it. I am not looking for anyone to do anything for me as mentioned in my post I am more than happy to convert this on my own if someone has a guide that I can read thru to understand the differences between the coding languages. Thank you for your feedback
 

MerryDay

Well-known member
VIP
@Zeph465 I do not know of any free guides that provide the "understanding of the differences between the coding languages". You would have to read in the tradingview what each function and variable is doing and then go to the TOS learning center and do searches for that type of syntax.

If you are conversant in one or the other, it should not be too onerous. Otherwise, modifying one of the plethora of moving average indicators on either this forum or on the internet would probably be the easier route.
HTH
 

rad14733

Well-known member
VIP
@Zeph465 I checked the link you provided, and thanks for that, and it appears to be a trend indicating moving average script... I created on for my own personal use that utilize most of the MA types that one uses but I have only ever used three of those... I can share the code if you are interested... Mine can do Hull, Simple, Exponential, Variable, Weighted, and Wilders...
 

Lukhy11

New member
2019 Donor
VIP
I need help converting a pine script indicator into a think script study for Thinkorswim. The name of the indicator is called Supertrend Buy and Sell I know we have quit a few already but this when has shortstop and longstop plots as well. If you can help me with this would appreciate it. Thank you!

Code Below
Code:
/@version=3
// Copyright (c) 2019-present, Alex Orekhov (everget)
study("SuperTrend Buy And Sell", overlay=true)

length = input(title="ATR Period", type=integer, defval=1)
mult = input(title="ATR Multiplier", type=float, step=0.1, defval=10.0)

atr = mult * atr(length)

longStop = hl2 - atr
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? max(longStop, longStopPrev) : longStop

shortStop = hl2 + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop

dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and close > shortStopPrev ? 1 : dir == 1 and close < longStopPrev ? -1 : dir


longColor = blue
shortColor = blue


//plot
plot(dir == 1 ? longStop : na, title="BuyLine", style=linebr, linewidth=2, color=longColor)
plotshape(dir == 1 and dir[1] == -1 ? longStop : na, title="Buy", style=shape.labelup, location=location.absolute, size=size.normal, text="Buy", transp=0, textcolor = white, color=green, transp=0)

plot(dir == 1 ? na : shortStop, title="SellLine", style=linebr, linewidth=2, color=shortColor)
plotshape(dir == -1 and dir[1] == 1 ? shortStop : na, title="Sell", style=shape.labeldown, location=location.absolute, size=size.normal, text="Sell", transp=0, textcolor = white, color=red, transp=0)

barcolor(dir == 1 ? green: red)

alertcondition(dir == 1 and dir[1] == -1 ? longStop : na, title="Buy", message="Buy!")
alertcondition(dir == 1 and dir[1] == -1 ? longStop : na, title="Buy", message="Buy!")
alertcondition(dir == 1 and dir[1] == -1 ? longStop : na, title="Buy", message="Buy!")
alertcondition(dir == -1 and dir[1] == 1 ? shortStop : na, title="Sell", message="Sell!")
 

MerryDay

Well-known member
VIP
@Lukhy11 What you call shortstop and longstop in this indicator is what Mobius calls UP and DOWN in his Supertrend. They are mathematically the EXACT same. You can add plot statements to the linked indicator or to one of the other Supertrends on the forum to see them actually plot on your chart. If you have difficulty writing your own plot statements, you can ask for the def statements to be turned into plots by posting in the Supertrend thread of your choice.

To generate excitement and induce a poster to assist you, you probably should post a screenshot of a chart w/ those plots
https://usethinkscript.com/threads/how-to-insert-image-in-a-post-thread.277/ And explain how this will assisting our trading.
HTH
 

Bentley

New member
Hi Guys,
I recently saw in the following video about adding few candlestick together and it seem to be show some new way to candlestick. Candlestick Math Secrets
After some research, found that there exist in tradingview codes to do that - Candlestick Math
Code:
study("Candlestick Math","CndlMth",overlay=true)
inStart = input(2610,"Start",integer,minval=0)
inLen = input(3,"Length",integer,minval=2)

len = inLen-1
start = inStart
end = inStart + len
isIn = (n >= start) and (n <= end)

o = isIn ? (na(o[1]) ? fixnan(open[0]) : o[1]) : na
c = isIn ? (na(c[1]) ? fixnan(close[round(-len)]) : c[1]) : na
h = isIn ? (na(h[1]) ? highest(fixnan(high[round(-len)]),len+1) : h[1]) : na
l = isIn ? (na(l[1]) ? lowest(fixnan(low[round(-len)]),len+1) : l[1]) : na

fill(plot(h,title="High"),plot(l,title="Low"),color=gray,transp=50)
plot(o,title="Open",color=iff(o > c,red,green),linewidth=4)
//plot(h,title="High")
//plot(l,title="Low")
plot(c,title="Close",color=iff(o > c,red,green),linewidth=4)

And the author have added another set of code to make it easier to search for the particular candle
Code:
study("Plot N")
plot(n)

Although TOS does provide few day candlestick timeframe selection, this provide more flexibility to choose particular section. Although it's small difference, but big in result as market always seem to be able to hide this signal using normal method.

I was just wondering, anyone familiar with the tradingview codes? What's this code saying? :unsure:

Thanks :cool:
 

rad14733

Well-known member
VIP
@sannkalpkapoor Do you have a link back to the original code, and can you post an image of what this looks like on a chart...??? Nobody is going to convert something they haven't seen simply based on your wanting it converted... You could try to convert it yourself if you are that intrigued by it... I find it odd that so many members come here with conversion requests from other platforms... Why do you think that is...??? If these other platforms are so great, why not stick with them...???

Tell me, what do you know about this indicator that makes you want it converted...??? Have you used it...??? Have you tried converting it...??? Why should we do your work for you...??? What's in it for us, or is it just for you...??? You see, you prompt more questions than answers with your request...

I could spend my days and nights finding indicators for others to convert too... I understand that you are a new member and this is your very first post here but what should we think when your first post is expecting others to do your work for you when you have contributed nothing...??? Think about it...!!!

Trust me, I mean no disrespect to you, it's just that we have far too many new members wanting and wanting and wanting - without putting forth their own effort... Nuff Said...

ps: I have NEVER asked anyone else to do my work for me...
 

rad14733

Well-known member
VIP
Probably not... Beyond that, you never posted the code, a link to the code, or an image of what the code paints on a chart... But that's okay because we don't just convert code on request... We'll help you if you want to try tackling the endeavor and get stuck, however...
 

lee-I-O=coke-A

New member
sorry rad, 2 things please. Again I have mental disability, I am just trying to keep my mind active, I forgot to add the code to convert.
2nd Ben listed over 70 conversions from tradingview to tos. Right here it is showing 18 pages of conversions.

Please can someone help?

Code:
// @author LazyBear
// If you use this code in its orignal/modified form, do drop me a note.
//
// Modified by Bromley

study("TDI - Traders Dynamic Index [Goldminds]", shorttitle="TDIGM")

rsiPeriod = input(11, minval = 1, title = "RSI Period")
bandLength = input(31, minval = 1, title = "Band Length")
lengthrsipl = input(1, minval = 0, title = "Fast MA on RSI")
lengthtradesl = input(9, minval = 1, title = "Slow MA on RSI")

src = close                                                             // Source of Calculations (Close of Bar)
r = rsi(src, rsiPeriod)                                                 // RSI of Close
ma = sma(r, bandLength)                                                 // Moving Average of RSI [current]
offs = (1.6185 * stdev(r, bandLength))                                  // Offset
up = ma + offs                                                          // Upper Bands
dn = ma - offs                                                          // Lower Bands
mid = (up + dn) / 2                                                     // Average of Upper and Lower Bands
fastMA = sma(r, lengthrsipl)                                            // Moving Average of RSI 2 bars back
slowMA = sma(r, lengthtradesl)                                          // Moving Average of RSI 7 bars back

hline(30)                                                               // Oversold
hline(50)                                                               // Midline
hline(70)                                                               // Overbought

upl = plot(up, "Upper Band", color = blue)                              // Upper Band
dnl = plot(dn, "Lower Band", color = blue)                              // Lower Band
midl = plot(mid, "Middle of Bands", color = orange, linewidth = 2)      // Middle of Bands

plot(slowMA, "Slow MA", color=green, linewidth=2)                       // Plot Slow MA
plot(fastMA, "Fast MA", color=red, linewidth=2)                         // Plot Fast MA

fill(upl, midl, red, transp=90)                                         // Fill Upper Half Red
fill(midl, dnl, green, transp=90)                                       // Fill Lower Half Green
Probably not... Beyond that, you never posted the code, a link to the code, or an image of what the code paints on a chart... But that's okay because we don't just convert code on request... We'll help you if you want to try tackling the endeavor and get stuck, however...
 

rad14733

Well-known member
VIP
@lee-I-O=coke-A Yes, there are 18 pages of requests, but not many actual conversions... It should be noted that I believe this topic was originally created by a member wanting code converted, not an invitation topic to simply flood the forums with requests... If you haven't taken the time to attempt a conversion then perhaps you should, as should every member requesting code conversions... It doesn't just happen automatically and there is no conversion tool... It takes someone's manual labor to sort out what the original code does and then figure out the best way to go about the actual conversion... It takes time and effort and members, complete strangers for the most part, expect others to do their work for them... Trust me, conversions aren't enjoyable work even if they are for the converters personal use... That's time and effort that they can never get back and aren't compensated for...

I find it somewhat troublesome for people to expect others to do their work for them, but perhaps I was raised differently and hold higher moral standards than some... There's some food for thought for all to take into consideration...
 

MerryDay

Well-known member
VIP
@lee-I-O=coke-A
I am not sure you are going to generate a great deal of enthusiasm for another TDI given that this one is just so awesome:
https://usethinkscript.com/threads/traders-dynamic-index-tdi-indicator-for-thinkorswim.651/

Have you been using the study, you posted? If you really want to garner some interest in your indicator, your best bet would be to explain in detail why you think yours is superior and to illustrate with screenshots: the comparisons, and differences between them. When you put effort into providing the images, the differences, and in explaining how this will improve our trading. It makes it feel more like a team effort. Then armed with all those details, some enterprising poster might become interested in making enhancements to our current indicator.
https://usethinkscript.com/threads/how-to-insert-image-in-a-post-thread.277/
 

hawkfan

New member
VIP
The indicator is Wave-pm and I honestly think its the best volatility indicator there is. If someone could help me translate this into think script It would be awesome :D.


Code:
study("Wave-PM")

fastPeriod = input(14, "Fast Period", input.integer, minval=5, maxval=1000)
slowPeriod = input(55, "Slow Period", input.integer, minval=5, maxval=1000)
slowerPeriod = input(100, "Slow Period", input.integer, minval=5, maxval=1000)
multiplier = input(2.2, "Stddev Multiplier", input.float, minval=1, maxval=5)

wpm(length) =>
    dev = multiplier * stdev(close, round(length))
    dev1 = pow(dev / syminfo.pointvalue, 2)
    temp = sqrt(sma(dev1, 100)) * syminfo.pointvalue
    temp := temp != 0  ? dev/temp : temp
    return = if temp > 0
        iexp = exp(-2*temp)
        (1-iexp)/(1+iexp)
    else
        iexp = exp(2*temp)
        (iexp-1)/(1+iexp)

val1 = wpm(fastPeriod)
val2 = wpm(slowPeriod)
val3 = wpm(slowerPeriod)


plot(val1, title="Fast", color=color.red, style=plot.style_line, linewidth=2)
plot(val2, title="Slow", color=color.blue, style=plot.style_line, linewidth=2)
plot(val3, title="Slower", color=color.yellow, style=plot.style_line, linewidth=2)


hline(0.9, title="Danger", color=color.red, linestyle=hline.style_dotted)
hline(0.7, title="Breakout", color=color.red, linestyle=hline.style_dotted)
hline(0.5, title="Consolidation", color=color.red, linestyle=hline.style_dotted)
hline(0.35, title="Gear Change", color=color.red, linestyle=hline.style_dotted)

I came across wave-pm from crypto traders but never seen it used on stocks. Originally made for forex by mark whistler. The indicator aims to detect the weight of the pairs trading. Its like a rsi with no directional signal rather a prediction of volatility . I plan to use this on tos so I can scan penny stocks since I think this indicator does exceptionally well. The only problem being the window of entry being very short.

Did you have any luck getting this converted? Looks interesting - similar to the Damiani Volameter study I have seen for Metatrader. I'd like to get something like this for TOS. Hoping one of the talented programmers here have the skills to convert these. Looking at the code I don't think I can be much help - it looks like it would be over my head.
 

MerryDay

Well-known member
VIP
@thanatos There are already so many momentum oscillators in TOS. I think we are probably saturated.
One of the Gold Standards of Momentum is Mobius's True Momentum Oscillator (TMO).

Have you been using this oscillator? If you really want to garner some interest in this indicator, your best bet would be to explain in detail why you think this one is superior to the TMO and others on this forum and to illustrate with screenshots: the comparisons, and differences between them. When you put effort into providing the images, the differences, and explaining how this will improve our trading. It makes it feel more like a team effort. Then armed with all those details, some enterprising poster might become interested in looking into this study in more depth.
https://usethinkscript.com/threads/how-to-insert-image-in-a-post-thread.277/
 

Lauren

New member
VIP
Do you think the attached could be made into a script for TD or Ninjatrader?

I like the idea of swinging NQ/CL/GC but being notified when the attached happens.

After several red HA candles, a daily candle closes green and you go LONG until there is a red daily candle close.. or the opposite.

Thanks!!
Lauren

Xklv5Xc.png
 

rad14733

Well-known member
VIP
@Lauren Do you have a link to where the image came from...??? Just an image doesn't give anyone much to go on... This something I might be interested in looking into but no guarantee I'll convert code... But, hey, you never know...
 

Lauren

New member
VIP
Hey @rad14733 So yeah its from Tradingview "ideas" I included the whole pic so you can see the original poster. There is no script currently made, my developer said it should be pretty easy to code.. I was even thinking how I learned in TOS one time how to create a scan/alert with the lookback feature on candles. This simply just looks back 1-2 candles.. say there were at least 2 red candles and the current candle closes GREEN.. then that would be an indication to go "long" until the green HA candles stop and 1 red one forms. Obviously you can just pick the overall trending direction or you can do both longs and shorts. I like it on a 30 min or a daily for /ES and /NQ
 

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