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:

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

generic

Active member
@Rich-Trader
Code:
input obLevel = 70;
input osLevel = 30;
input length = 14;
input src = close;
def ep = 2 * length - 1;
def auc = MovAvgExponential( max( src - src[1], 0 ), ep );
def adc = MovAvgExponential( max( src[1] - src, 0 ), ep );
def x1 = (length - 1) * ( adc * obLevel / (100-obLevel) - auc);
def ub = if( x1 >= 0, src + x1, src + x1 * (100-obLevel)/obLevel );
def x2 = (length - 1) * ( adc * osLevel / (100-osLevel) - auc);
def lb = if( x2 >= 0, src + x2, src + x2 * (100-osLevel)/osLevel );

plot upper = ub;
plot lower = lb;
plot mid = (ub + lb)/2;
 

parkerwendt

New member
Hello guys,

I'm new to this forum! I am just learning how to code and have been struggling to convert the Jurik moving average onto Thinkscript. Just wondering if any coding experts here can help convert this!

Here is the code from Tradingview:

Code:
//@version=3
// Copyright (c) 2007-present Jurik Research and Consulting. All rights reserved.
// Copyright (c) 2018-present, Alex Orekhov (everget)
// Jurik Moving Average script may be freely distributed under the MIT license.
study("Jurik Moving Average", shorttitle="JMA", overlay=true)

length = input(title="Length", type=integer, defval=7)
phase = input(title="Phase", type=integer, defval=50)
power = input(title="Power", type=integer, defval=2)
src = input(title="Source", type=source, defval=close)
highlightMovements = input(title="Highlight Movements ?", type=bool, defval=true)

phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5

beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
alpha = pow(beta, power)

jma = 0.0

e0 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])

e1 = 0.0
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])

e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * pow(1 - alpha, 2) + pow(alpha, 2) * nz(e2[1])

jma := e2 + nz(jma[1])

jmaColor = highlightMovements ? (jma > jma[1] ? green : red) : #6d1e7f
plot(jma, title="JMA", linewidth=2, color=jmaColor, transp=0)
 

parkerwendt

New member
yes exactly. hopefully you guys can benefit from this. the original settings are 20 length rsi, wilders, 80,20. 10 period exponential moving average.
For some reason the thinkscript indicator is more choppy than the one on trading view. Are you noticing the same thing? Wondering if this is due to the RMA function on pinescript.
 

FOTM_8888

Member
VIP
Here is the indicator, it is look very nice and works very well in trading view. I will pay someone to help to convert this indicator! thanks

Code:
on=2
//strategy('Complete Ichimoku Trader [I]modified[/I] - original by @kingthies / mod by @cryptomrdavis', shorttitle='Complete Ichimoku Trader [I]modified[/I] - original by @kingthies / mod by @cryptomrdavis', overlay=true)
study('Complete Ichimoku Trader [I]modified[/I] - by @cryptomrdavis -', shorttitle='Complete Ichimoku Trader [I]modified[/I] - @cryptomrdavis -', overlay=true)

sp = input(true, title="Welcome to the modified Version of the Complete Ichimoku Trader - original by @ethies. This version has some extra lines of code and gives you less signals as the original one.")
haopen = security(heikinashi(tickerid), period, open)
hahigh = security(heikinashi(tickerid), period, high)
halow = security(heikinashi(tickerid), period, low)
haclose = security(heikinashi(tickerid), period, close)
heikUpColor() => haclose > haopen
heikDownColor() => haclose <= haopen
o = haopen
c = haclose
src = haclose
price = haclose

rsilength = input(13, title="RSI")
VolSMA = input(20, title="Volume")
uptrendlength = input(2, title="Uptrend Length")
downtrendlength = input(2, title="Downtrend Length")
ShowCloud = input(false, title="Show Ichimoku Cloud?")
ShowIchiLines = input(false, title="Show Ichimoku Lines?")

v1 = volume
v2 = sma(volume,VolSMA)

//RSI//
up1 = rma(max(change(src), 0), 9)
down1 = rma(-min(change(src), 0), 9)
rsi = down1 == 0 ? 100 : up1 == 0 ? 0 : 100 - (100 / (1 + up1 / down1))
K = sma(stoch(c, hahigh, halow, 14), 3)
D = sma(K, 3)

myrsi = rsi(c,rsilength)

//KDJ//
ilong = 9
isig = 3
bcwsma(s,l,m) =>
    _s = s
    _l = l
    _m = m
    _bcwsma = (_m*_s+(_l-_m)*nz(_bcwsma[1]))/_l
    _bcwsma

h = highest(hahigh, ilong)
l = lowest(halow,ilong)
RSV = 100*((c-l)/(h-l))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK-2 * pD
KD = avg(pK,pD)

//EMAs//
EMA5 = ema(price,5)
EMA7 = ema(price,7)
EMA10 = ema(price,10)
EMA14= ema(price,14)
VOLEMA = avg(volume,20)

/// --- TREND --- ///
avghigh = sma(h, uptrendlength)
avglow = sma(l, downtrendlength)
uptrend = h > avghigh
downtrend = l < avglow

//ICHIMOKU BUY & SELL//
conversionPeriods = 9
basePeriods = 26
laggingSpan2Periods = 52
displacement = 26
donchian(len) => avg(lowest(len), highest(len))
resolve(src, default) =>
    if na(src)
        default
    else
        src
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = offset(avg(conversionLine, baseLine), displacement)
leadLine2 = offset(donchian(laggingSpan2Periods), displacement)
tk_cross_bull = crossover(conversionLine, baseLine)
tk_cross_bear = crossunder(conversionLine, baseLine)
cross_y = (conversionLine[1] * (baseLine - baseLine[1]) - baseLine[1] * (conversionLine - conversionLine[1])) / ((baseLine - baseLine[1]) - (conversionLine - conversionLine[1]))
tk_cross_below_kumo = cross_y <= leadLine2[1] and cross_y <= leadLine1[1] and cross_y <= leadLine2 and cross_y <= leadLine1
tk_cross_above_kumo = cross_y >= leadLine2[1] and cross_y >= leadLine1[1] and cross_y >= leadLine2 and cross_y >= leadLine1
tk_cross_inside_kumo = (not tk_cross_below_kumo) and (not tk_cross_above_kumo)
pk_cross_bull = crossover(haclose, baseLine)
pk_cross_bear = crossunder(haclose, baseLine)
cross_pk_y = (haclose[1] * (baseLine - baseLine[1]) - baseLine[1] * (haclose - haclose[1])) / ((baseLine - baseLine[1]) - (haclose - haclose[1]))
pk_cross_below_kumo = cross_pk_y <= leadLine2[1] and cross_pk_y <= leadLine1[1] and cross_pk_y <= leadLine2 and cross_pk_y <= leadLine1
pk_cross_above_kumo = cross_pk_y >= leadLine2[1] and cross_pk_y >= leadLine1[1] and cross_pk_y >= leadLine2 and cross_pk_y >= leadLine1
pk_cross_inside_kumo = (not pk_cross_below_kumo) and (not pk_cross_above_kumo)
kumo_bull = (crossover(haclose, leadLine1) and leadLine1 > leadLine2) or (crossover(haclose, leadLine2) and leadLine2 > leadLine1)
kumo_bear = (crossunder(haclose, leadLine2) and leadLine1 > leadLine2) or (crossunder(haclose, leadLine1) and leadLine2 > leadLine1)
price_below_kumo = (haclose < leadLine2 and haclose < leadLine1)
price_above_kumo = (haclose > leadLine2 and haclose > leadLine1)
price_inside_kumo = (not price_below_kumo) and (not price_above_kumo)
no_dp_leadLine1 = avg(conversionLine, baseLine)
no_dp_leadLine2 = donchian(laggingSpan2Periods)
lead_line_cross_bull = crossover(no_dp_leadLine1, no_dp_leadLine2)
lead_line_cross_bear = crossunder(no_dp_leadLine1, no_dp_leadLine2)
price_below_kumo := (haclose < no_dp_leadLine2 and haclose < no_dp_leadLine1)
price_above_kumo := (haclose > no_dp_leadLine2 and haclose > no_dp_leadLine1)
price_inside_kumo := (not price_below_kumo) and (not price_above_kumo)
past_price = offset(haclose, displacement)
lag_line_bull_cross = haclose > haclose[displacement]
lag_line_bear_cross = haclose < haclose[displacement]
past_price_below_kumo = (past_price < leadLine2 and past_price < leadLine1)
past_price_above_kumo = (past_price > leadLine2 and past_price > leadLine1)
past_price_inside_kumo = (leadLine2 < past_price and past_price < leadLine1) and (leadLine1 < past_price and past_price < leadLine2)

//BUY & SELL
buycond = (tk_cross_below_kumo or tk_cross_inside_kumo or tk_cross_above_kumo) and rising(pJ[1],1) and heikUpColor() and uptrend and v1 >= v2 and rising(myrsi,1) or
(pk_cross_below_kumo or pk_cross_inside_kumo or pk_cross_above_kumo) and rising(pJ[1],1) and heikUpColor() and uptrend and v1 >= v2 and rising(myrsi,1) or
(past_price_below_kumo or past_price_above_kumo or past_price_inside_kumo) and rising(pJ[1],1) and heikUpColor() and uptrend and v1 >= v2 and rising(myrsi,1)
sellcond = (tk_cross_below_kumo or tk_cross_inside_kumo or tk_cross_above_kumo) and falling(pJ[1],1) and heikDownColor()and falling(myrsi,1) and downtrend or
(pk_cross_below_kumo or pk_cross_inside_kumo or pk_cross_above_kumo) and falling(pJ[1],1) and heikDownColor() and falling(myrsi,1) and downtrend or
(past_price_below_kumo or past_price_above_kumo or past_price_inside_kumo) and falling(pJ[1],1) and heikDownColor() and falling(myrsi,1) and downtrend

signalfilter = 0
signalfilter := sellcond ? 1 : buycond ? 2 : nz(signalfilter[1])
filvar = signalfilter == 1 ? 1:0
buySignal = (signalfilter != signalfilter[1] and filvar == 0)
sellSignal = (signalfilter != signalfilter[1] and filvar == 1)

//PLOT
plotshape(buySignal, color=green, text= "Buy", location= location.belowbar,style= shape.labelup, textcolor=white, size = size.tiny, title="Buy Alert",editable=false, transp=60)
plotshape(sellSignal, color=red, text= "Sell", location= location.abovebar,style= shape.labeldown, textcolor=white, size = size.tiny, title="Sell Alert", editable=false, transp=60)

SenkouA = donchian(laggingSpan2Periods)
SenkouB = (conversionLine[basePeriods] + baseLine[basePeriods]) / 2
plot(ShowIchiLines and conversionLine ? conversionLine : na, color=red, title="Tenkan")
plot(ShowIchiLines and baseLine ? baseLine : na, color=blue, title="Kijun")
plot(ShowIchiLines and price ? price : na, color= teal , title="Chikou", offset = -displacement)
A = plot(ShowCloud and SenkouA[displacement] ? SenkouA[displacement] : na, color=purple, title="SenkouA")
B = plot(ShowCloud and SenkouB ? SenkouB : na, color=green, title="SenkouB")
fill(A, B, color=green)

//Alert Conditions
alertcondition(buySignal, title='Buy Alert', message='Buy Alert')
alertcondition(sellSignal, title='Sell Alert', message='Sell Alert')
 

XeoNoX

Well-known member
VIP
For some reason the thinkscript indicator is more choppy than the one on trading view. Are you noticing the same thing? Wondering if this is due to the RMA function on pinescript.

You can attempt to add the RMA. The Rolling Moving Average, sometimes referred to as "Smoothed Moving Average", gives the recent prices most weighting, though the historic prices are also weighted, each given less weighting further back in time. The latest Rolling Average is obtained by multiplying the previous Rolling Average by n-1 periods, adding today’s symbol price, and then dividing the total by n periods. Note that the initial RMA is based on a Simple Moving Average.

Code:
Rolling Moving Average
Formula
RMA = ((RMAorSMA(t-1) * (n-1)) + Xt) / n
n = The length of the Moving Average
X = Price

idAZV3o.png
 

Swiss_Toni

New member
Hello, I am looking for someone who can convert a TradingView script into a ThinkOrSwim study. I use both platforms.

The TradingView code was written for me by a Fiveer seller. However, he does not know ThinkOrSwim code.

It is a very simple script - only 24 lines of code.

If you can do this job, please contact me. I will only do business on Fiveer or Freelancer.

Thank you for your time!
 

BubbaVT21

New member
@generic Thanks for converting it, I will take a look. Thanks again.

This good be a helpful indicator to convert from TradingView to TOS

https://www.tradingview.com/script/I7YyeFKR-Cash-in-Cash-out-Report-CICO-Quiets-market-noise/

Code:
//@version=4
study("CICO Report")

//  Cash in/cash out report (CICO). Brought to you by Johnny Nickles via Trading View Pine script. If you find this helpful in anyway, please leave a like!
//  You may also find the Cashflow and Position calculator tools helpful as well. Both are free to use on the Trading View public indicators

//  This indicator was built with the intent to quiet the market noise. The CICO Report takes the average price of a given time period (each candle) and 
//  multiples by the current volume. Then the indicators gives a running sum of the up and down movements of a market. When the sum is positive, green; negative, red.
//  The area portion of the indicator is the sum and the column bar is the current cash in or cash out. 
//  The CICO Report will also color your chart with the running sum. I recommend matching a moving average to the market you are watching for best results.
//  Next, enter the moving average value into the CICO Report input. Once matched, the moving average and the running sum should make sense visually.
 
//  userLen is the user input value for desired length of time

userLen = input(defval=100, type=input.integer, title='User length', minval=0)

//  cashVec is the price going up or down

cashVec = close - open

//  cashMag will take the average price between high and low and multiple by the current volume, value is negative when price is going down.

cashMag = cashVec > 0? volume * ((high + low) / 2): cashVec < 0? -1 * (volume * ((high + low) / 2)): na

//  cashSum takes the sum of the cashMag values based on user input length (the moving average of the market)

cashSum = sum(cashMag, userLen)

//  This plotting makes the indicator look pretty. Can be customized here or in the front panel.

plot(cashMag, title='Cash in/Cash out', style=plot.style_columns, color=cashVec > 0? color.green : color.red)
plot(cashSum, title='Running sum', style=plot.style_area, color = cashSum > 0? color.green: color.red, transp = 75)

//  This is what colors the chart. I recommend setting your current colors to all grey frist. Basically this is coloring the bars green if the sum, current and vector are all moving in the same direction.
//  Bar coloring can be turned off in the front panel.

barcolor(title='Bar coloring', color= cashVec > 0 and cashSum > 0 and cashMag > 0? color.green: cashVec < 0 and cashSum < 0 and cashMag < 0? color.red: na)

// Proper risk management is the key to the stock market. I hope this tool makes you a lot of money!
 
Last edited by a moderator:

Gellidus

New member
VIP
Hi all,

Would it be possible to help convert this TOS script on Countback line for GMMA strategy? More details can be found on this video


Code:
//@version=4
// Copyright (c) 2019-present, Franklin Moormann (cheatcountry)
// Guppy Count Back Line [CC] script may be freely distributed under the MIT license.
study("Guppy Count Back Line [CC]", overlay=true)

f_security(_symbol, _res, _src, _repaint) =>
    security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1]
   
res = input(title="Resolution", type=input.resolution, defval="")
rep = input(title="Allow Repainting?", type=input.bool, defval=false)
bar = input(title="Allow Bar Color Change?", type=input.bool, defval=true)
lbLength = input(title="LookBackLength", type=input.integer, defval=21, minval=1)
p = f_security(syminfo.tickerid, res, close, rep)
h = f_security(syminfo.tickerid, res, high, rep)
l = f_security(syminfo.tickerid, res, low, rep)

ll = lowest(lbLength)
hh = highest(lbLength)

hCount = 0, lCount = 0
cbl = p
for i = 0 to lbLength
    if l[I] == ll
        for j = i + 1 to i + lbLength
            lCount := lCount + (h[j] > h[I] ? 1 : 0)
            if lCount == 2
                cbl := h[j]
                break
    if h[I] == hh
        for j = i + 1 to i + lbLength
            hCount := hCount + (l[j] < l[I] ? 1 : 0)
            if hCount == 2
                cbl := l[j]
                break

sig = p > cbl ? 1 : p < cbl ? -1 : 0
alertcondition(crossover(sig, 0), "Buy Signal", "Bullish Change Detected")
alertcondition(crossunder(sig, 0), "Sell Signal", "Bearish Change Detected")
cblColor = sig > 0 ? color.green : sig < 0 ? color.red : color.black
barcolor(bar ? cblColor : na)
plot(cbl, color=cblColor, linewidth=2)[/I][/I][/I][/I]
 
I've noticed Thinkorswim does not have the MDX. This indicator can be very helpful for pullbacks and breakouts and I plan to be working on getting the code translated, but I am slow so I have a challenge for anyone more savvy than me to translate this code.

Code:
// ------------------------------------------------------------------------------------
//
//     Mean Deviation Index
//     Version 1.2
//
// ------------------------------------------------------------------------------------
//
// The Mean Deviation Index (MDX) is used to see how much price is deviating from the
// mean. This indicator takes both volatility and mean deviation in consideration.
//
// It uses the standard deviation of the ATR to filter an EMA, and uses this as the
// mean. It then only plots > or < 0 if price is more than 1 x ATR away from the
// mean. If index is positive, the background turns green, meaning price is more than
// 1 x ATR above the mean. If the index is negative, the background turns red,
// meaning price is more than 1 x ATR below the mean. This setting can be changed
// by changing the setting "ATR Multiplier", but the default is 1 x ATR.
//
// There are two main ways to use this index.
//
// 1. Use it aggressively to find trends (by combining it with other indicators) by
//    entereding each time the background changes color to green for longs or red for
//    shorts.
// 2. Use it to spot breakouts, waiting for a pullback, and then entering on the next
//    move in the same direction. In this context for a short, you wait for the
//    background color to turn green, then wait for the index to pull back, and then
//    enter once it starts moving up again.
//
// ------------------------------------------------------------------------------------
//
// Changelog:
//
//  - Version 1.0 -
//     * Initial release.
//  - Version 1.1 -
//     * Added option to plot in a percentage scale instead of pure instrument value.
//     * Changed the default of the different period settings to 26.
//  - Version 1.2 -
//     * Added the option to plot levels on the indicator, alongh with alerts for when
//       the MDX crosses these lines. Also added an option to show or hide these lines.
//       These lines are hidden by default.
//     * Added the option to make the indicator volume weighted.
//       This is off by default.
//
// ------------------------------------------------------------------------------------
//
// Licensed under CC BY-NC.
// https://creativecommons.org/licenses/by-nc/4.0/
//
// Copyright © Anton Berlin, 2020.
//
// ------------------------------------------------------------------------------------

//@version=4



// ------------------------------------------------------------------------------------
//    Setup
// ------------------------------------------------------------------------------------

study(title = "Mean Deviation Index", shorttitle = "MDX", overlay = false)



// ------------------------------------------------------------------------------------
//    Input
// ------------------------------------------------------------------------------------

ema_period = input(title = "EMA Period", defval = 26, minval = 3, type = input.integer)
atr_period = input(title = "ATR Period", defval = 26, minval = 1, type = input.integer)
atr_mult = input(title = "ATR Multiplier", defval = 1.0, minval = 0.1, type = input.float)
atr_filter_type = input(title = "ATR Filter Type", defval = "Away from price", options = ["Away from price", "Closer to price"], type = input.string)
atr_stddev_length = input(title = "ATR Filter Standard Deviation Length", defval = 26, minval = 1, type = input.integer)
atr_stddev_low_lookback = input(title = "ATR Filter Standard Deviation Low Lookback Period", defval = 26, minval = 1, type = input.integer)
use_normalized = input(title = "Use normalized ATR for the ATR Filter?", defval = true, type = input.bool)
levels = input(title = "Levels", defval = 4, minval = 0, type = input.float)
show_levels = input(title = "Show levels?", defval = false, type = input.bool)
show_as_perc = input(title = "Show value as percentage away from the mean?", defval = false, type = input.bool)
use_volume = input(title = "Use a volume weighted calculation?", defval = false, type = input.bool)



// ------------------------------------------------------------------------------------
//    ATR-filtered EMA
// ------------------------------------------------------------------------------------

get_atr(period, use_volume) =>
    tr_val = use_normalized ? tr / close : tr
    atr_val =
         (
             use_volume ?
                 (rma(tr * volume, atr_period) / rma(volume, atr_period)) :
                 atr(atr_period)
         ) * atr_mult

get_afema(src, period, atr_period, stdev_period, filter_type, low_lookback, use_volume) =>
    float result = na
    float alpha = na
    float stddev_factor = na
    
    atr_val = get_atr(atr_period, use_volume)
    
    stddev_a = sma(pow(atr_val, 2), stdev_period)
    stddev_b = pow(sum(atr_val, stdev_period), 2) / pow(stdev_period, 2)
    stddev = sqrt(stddev_a - stddev_b)
    stddev_lo = lowest(stddev, low_lookback)
    
    if (filter_type == "Away from price")
        stddev_factor := min(stddev_lo / stddev, 5.0)
    else if (filter_type == "Closer to price")
        stddev_factor := min(stddev / stddev_lo, 5.0)
    
    alpha := (2.0 * stddev_factor) / (period + 1.0)
    
    if (na(src[1]))
        result := sum(src, period) / period
    else
        result := alpha * src + (1.0 - alpha) * nz(result[1])
    
    // Return the result
    result



// ------------------------------------------------------------------------------------
//    Mean Deviation Index calculations
// ------------------------------------------------------------------------------------

nom_source = use_volume ? close * volume : close
nom_val = get_afema(nom_source,
     ema_period,
     atr_period,
     atr_stddev_length,
     atr_filter_type,
     atr_stddev_low_lookback,
     use_volume)

denom_val = get_afema(volume,
     ema_period,
     atr_period,
     atr_stddev_length,
     atr_filter_type,
     atr_stddev_low_lookback,
     use_volume)

vema_val = use_volume ? nom_val / denom_val : nom_val

dev_val = close - vema_val
atr_val = get_atr(atr_period, use_volume)
mdx_val = dev_val > 0 ? max(dev_val - atr_val, 0) : min(dev_val + atr_val, 0)
mdx_out = show_as_perc ? 100 * ((mdx_val + vema_val - atr_val) / (vema_val - atr_val) - 1.0) : mdx_val



// ------------------------------------------------------------------------------------
//    Plotting
// ------------------------------------------------------------------------------------

bg_clr = mdx_out > (show_levels ? levels : 0) ? color.green : mdx_out < (show_levels ? -levels : 0) ? color.red : na

bgcolor(title = "BG color for positive or negative deviation", color = bg_clr, transp = 70)
plot(title = "MDX value", series = mdx_out, color = color.gray, linewidth = 2)

plot(show_levels ? levels : na, title = "Upper level", color = color.gray)
plot(show_levels ? -levels : na, title = "Lower level", color = color.gray)



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

alertcondition(crossover(mdx_out, levels), "Cross upper level", "MDX crossed upper level")
alertcondition(crossunder(mdx_out, -levels), "Cross lower level", "MDX crossed lower level")
 

Shasha

New member
Can someone please convert this Trading view pinescript to TOS? I would really appreciate it!

Code:
//@version=4

study(title="Beep Boop", shorttitle="Beep Boop", resolution="")

fast_length = input(title="Fast Length", type=input.integer, defval=12)

slow_length = input(title="Slow Length", type=input.integer, defval=26)

EMATrend = input(title="EMA Trend", type=input.integer, defval=50)



src = input(title="Source", type=input.source, defval=close)

signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)

sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false)

sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)

col_grow_above = #26A69A

col_grow_below = #FF0000

col_fall_above = #FFFFFF

col_fall_below = #FFFFFF

col_macd = #0094ff

col_signal = #ff6a00

fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)

slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)

macd = fast_ma - slow_ma

signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)

hist = macd - signal



if (hist > 0)

    hist := 0.1

   

if (hist < 0)

    hist := 0.09

   

fastMA = ema(close, EMATrend)

//fastMA = 0



   



plot(hist, title="Histogram", style=plot.style_columns, color=(hist == 0.1 ? ((hist == 0.1) and (close > fastMA) and (open > fastMA) and (low > fastMA) ? col_grow_above : col_fall_above) : ((hist == 0.09) and (close < fastMA) and (open < fastMA) and (high < fastMA)? col_grow_below : col_fall_below) ), transp=0 )
 

bryceln

New member
This is I believe a tradingview script which I know nothing about. I need someone to help convert it to thinkscript so that I can see if it does what Im hoping. If possible I would need to be able to change the averagetype for both plots. Thanks a bunch for any help!!

Code:
l = input(13, title="TSV Length")
l_ma = input(7, title="MA Length")

t = sum(close > close[1] ? volume * (close - close[1]) : close < close[1] ? volume * (close - close[1]) : 0, l)
m = sma(t, l_ma)

PAL = (t > m) and (t > 0)
PAL_fail = (t < m) and (t > 0)
PAS = (t < m) and (t < 0)
PAS_fail = (t > m) and (t < 0)

plot(t, color=color.red, style=plot.style_histogram, title="TSV")
plot(m, color=color.green, title="MA")

plotshape(PAL, title="Price Action Long", location=location.bottom, style=shape.square, size=size.auto, color=color.green, transp=80)
plotshape(PAS, title="Price Action Short", location=location.bottom, style=shape.square, size=size.auto, color=color.red, transp=80)
plotshape(PAL_fail, title="Price Action Long - FAILURE", location=location.bottom, style=shape.xcross, size=size.auto, color=color.black, transp=60)
plotshape(PAS_fail, title="Price Action Short - FAILURE", location=location.bottom, style=shape.xcross, size=size.auto, color=color.black, transp=60)
 

Marketingjessie

New member
Hey traders I have a TradingView script I’ve been using for sometime. Works well for finding a reversal on stocks you want to get into on a daily.

It’s a pivot reversal with volume on the last bar.

Unfortunately I can’t use well with TV because there is no scanner so I’m wanted to turn it into a study so I can scan on ThinkOrSwim and trader there

Is there anyone here who could convert this TV script into a TOS script?

——- Pivot Script—-


Code:
//@version=4

study(title="Pivot BUY Alert", shorttitle="Pivot BUY Alert", overlay=true)



////////////

// INPUTS //

////////////



consec_signals = input(title="Allow consecutive signals", type=input.bool, defval=true)

ma_short_len   = input(defval = 2, title = "Short MA Length", type = input.integer, minval = 1, maxval = 100)

ma_long_len    = input(defval = 8, title = "Lomg MA Length",  type = input.integer, minval = 1, maxval = 100)



t     = tickerid(syminfo.prefix, syminfo.ticker)

realC = security(t, timeframe.period, close)

realH = security(t, timeframe.period, high)

realL = security(t, timeframe.period, low)



// calculate pivot points without filters

IsPH = (realH[1] > realH[2]) and (realH[0] < realH[1]) and (realC[0] < realL[1]) ? true : na

IsPL = (realL[1] < realL[2]) and (realL[0] > realL[1]) and (realC[0] > realH[1]) ? true : na



// calculate MAs

ma_short = sma(realC, ma_short_len)

ma_long  = sma(realC, ma_long_len)



// apply ATR filter to pivot points

long_pivot_ma  = IsPL or crossover( ma_short, ma_long)

short_pivot_ma = IsPH or crossunder(ma_short, ma_long)



// filter out consecutove signals of the same type

last_signal  = 0

last_signal := long_pivot_ma ? 1 : short_pivot_ma ? -1 : last_signal[1]



long_final  = (last_signal[1] == -1 or consec_signals ) and long_pivot_ma  and long_pivot_ma[1]  != true

short_final = (last_signal[1] ==  1 or consec_signals ) and short_pivot_ma and short_pivot_ma[1] != true



/////////////

// PLOTING //

/////////////



plot(ma_short, color = color.red)

plot(ma_long,  color = color.green)



plotshape(short_final, title="PivotHigh", style=shape.circle, location=location.abovebar, color=color.red)

plotshape(long_final,  title="PivotLow",  style=shape.circle, location=location.belowbar, color=color.green)



length_=input(21, "length", minval=1)

avrg=sma(volume,length_)



vold1 = volume > avrg*1.5 and close<open

vold2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close<open

vold3 = volume < avrg *0.5 and close<open



volu1 = volume > avrg*1.5 and close>open

volu2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close>open

volu3 = volume< avrg*0.5 and close>open





cold1=#800000

cold2=#FF0000

cold3=color.orange





colu1=#006400

colu2=color.lime

colu3=#7FFFD4





color = vold1 ? cold1 : vold2 ? cold2 : vold3 ? cold3 : volu1 ? colu1 : volu2 ? colu2 : volu3 ? colu3 : na



barcolor(color)

alert_condition=long_final==true and volume*1.01 > volume[1] and close[1]<open[1] and close[2]<open[2] and close[3]<open[3] and close>open

if(alert_condition)

    upLabel_buy = label.new(x=bar_index, y=close*1.03,color=color.green, text="Pivot BUY Alert", size=size.small,style=label.style_labeldown)

    label.set_color(upLabel_buy, color.new(#ff0000, 25))

    label.set_textcolor(upLabel_buy, color.new(#FFFFFF,0))

bgcolor(alert_condition?color.green:na,  transp=70)

alertcondition(condition=alert_condition,title="Pivot BUY Alert",message="Pivot+volume+Keltner BUY Alert for {{ticker}} @ {{close}}")
 

mickey

New member
Hi, Is someone able to convert this tradingview version of Correlation as a Cycle by Ehlers to Thinkscript? thank you. Mickey.

Code:
// Correlation Cycle
// TASC Jun 2020
// John F. Ehlers

//Inputs
Price = input(hlc3, title = "Price")
Period = input(34, title = "Period")
InputPeriod = input(0, title = "InputPeriod")
//Uses price data if InputPeriod = 0

//Vars
Length = 20
Sx = 0.00
Sy = 0.00
Sxx = 0.00
Sxy = 0.00
Syy = 0.00
X = 0.00
Y = 0.00
Real = 0.00
Imag = 0.00
Angle = 0.00
State = 0
pi = 2 * asin(1)

//Correlate over one full cycle period
Length := Period


//Creates a theoretical sinusoid having an period equal to the input period as the data input
if InputPeriod != 0 
    Price := sin( 2 * pi * bar_index / InputPeriod)

//Correlate price with cosine wave having a fixed period
Sx := 0
Sy := 0
Sxx := 0
Sxy := 0
Syy := 0
for Count = 1 to Length
    X := nz(Price[Count - 1])
    Y := cos( 2 * pi * ( Count - 1 ) / Period )
    Sx := Sx + X
    Sy := Sy + Y
    Sxx := Sxx + X * X
    Sxy := Sxy + X * Y
    Syy := Syy + Y*Y

if ( Length * Sxx - Sx * Sx > 0 ) and ( Length * Syy - Sy * Sy > 0 ) 
    Real := ( Length * Sxy - Sx * Sy ) / sqrt( ( Length * Sxx - Sx * Sx ) * ( Length * Syy - Sy * Sy ) )

//Correlate with a negative sine wave having a fixed period
Sx := 0
Sy := 0
Sxx := 0
Sxy := 0
Syy := 0
for Count = 1 to Length
    X := nz(Price[Count - 1])
    Y := -sin( 2 * pi * ( Count - 1 ) / Period )
    Sx := Sx + X
    Sy := Sy + Y
    Sxx := Sxx + X * X
    Sxy := Sxy + X * Y
    Syy := Syy + Y * Y
if ( Length * Sxx - Sx * Sx > 0 ) and ( Length * Syy - Sy * Sy > 0 ) 
    Imag := ( Length * Sxy - Sx * Sy ) / sqrt( ( Length * Sxx - Sx * Sx ) * ( Length * Syy - Sy * Sy ) )

//Compute the angle as an arctangent function and resolve ambiguity
if Imag != 0 
    Angle := 90 + atan( Real / Imag ) / pi * 180
    //Angle in degree rather than radians

if Imag > 0 
    Angle := Angle - 180
//Do not allow the rate change of angle to go negative
if nz(Angle[1]) - Angle < 270 and Angle < nz(Angle[1]) 
    Angle := nz(Angle[1])


//Compute and plot market state
State := 0
if abs( Angle - nz(Angle[1]) ) < 9 and Angle < 0 
    State := -1    
if abs( Angle - nz(Angle[1]) ) < 9 and Angle >= 0 
    State := 1
Plot4 = plot( State, "Correlation Cycle", color=State>=0 ? color.yellow : State< 0 ? color.fuchsia : color.gray,  style=plot.style_area, transp=50,   linewidth =3)
hline(0)
hline(1)
hline(-1)
built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
 

BenTen

Administrative
Staff
VIP
@mickey

Code:
declare lower;

input length = 20;

def sx = Sum(close, length);
def sxx = Sum(Sqr(close), length);
def sy1 = fold i1 = 0 to length with s1 do (s1 + Cos(2 * Double.Pi * i1 / length));
def sxy1 = fold i2 = 0 to length with s2 do (s2 + GetValue(close, i2) * Cos(2 * Double.Pi * i2 / length));
def syy1 = fold i3 = 0 to length with s3 do (s3 + Sqr(Cos(2 * Double.Pi * i3 / length)));

def corrCosine = (length * sxy1 - sx * sy1) / Sqrt((length * sxx - Sqr(sx)) * (length * syy1 - Sqr(sy1)));

def sy2 = fold j1 = 0 to length with t1 do (t1 - Sin(2 * Double.Pi * t1 / length));
def sxy2 = fold j2 = 0 to length with t2 do (t2 - GetValue(close, j2) * Sin(2 * Double.Pi * j2 / length));
def syy2 = fold j3 = 0 to length with t3 do (t3 + Sqr(Sin(2 * Double.Pi * j3 / length)));

def corrNegSine = (length * sxy2 - sx * sy2) / Sqrt((length * sxx - Sqr(sx)) * (length * syy2 - Sqr(sy2)));

plot CorreationWithCosine = corrCosine;
plot CorrealtionWithNegativeSine = corrNegSine;

CorreationWithCosine.SetDefaultColor(GetColor(5));
CorrealtionWithNegativeSine.SetDefaultColor(GetColor(6));
 

mickey

New member
Hi Ben.

Appreciate the script. That is for the first half of the indicator. Any chance you happen to have the bottom half?

Code:
//Compute the angle as an arctangent function and resolve ambiguity
if Imag != 0
    Angle := 90 + atan( Real / Imag ) / pi * 180
    //Angle in degree rather than radians

if Imag > 0
    Angle := Angle - 180
//Do not allow the rate change of angle to go negative
if nz(Angle[1]) - Angle < 270 and Angle < nz(Angle[1])
    Angle := nz(Angle[1])


//Compute and plot market state
State := 0
if abs( Angle - nz(Angle[1]) ) < 9 and Angle < 0
    State := -1   
if abs( Angle - nz(Angle[1]) ) < 9 and Angle >= 0
    State := 1
Plot4 = plot( State, "Correlation Cycle", color=State>=0 ? color.yellow : State< 0 ? color.fuchsia : color.gray,  style=plot.style_area, transp=50,   linewidth =3)
hline(0)
hline(1)
hline(-1)
 

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

Similar threads

Top