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:

JaredH409

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

// WHAT IT DOES AND HOW TO USE:
// In the Input page you configure the RSI
//
// The indicator draws swings on the chart based on RSI extremes
// Example: Lines are draws from OVERSOLD to OVERBOUGHT and vice-versa
// If we keep geing in deeper OVERBOUGHT or OVERSOLD, the swinglines follow the price, till another cycle is complete
// In the labels you see the swing's relation to the structure: If the swing high is higher then the previous, it becomes Higher High aka HH


//@version=4
study("RSI Swing Indicator", overlay=true, max_bars_back=1000)

// RSI Settings for user
rsiSource = input(title="RSI Source", type=input.source, defval=close)
rsiLength = input(title="RSI Length", type=input.integer, defval=7)
rsiOverbought = input(title="RSI Overbought", type=input.integer, defval=70, minval=51, maxval=100)
rsiOvesold = input(title="RSI Oversold", type=input.integer, defval=30, minval=1, maxval=49)

// RSI value based on inbuilt RSI
rsiValue = rsi(rsiSource, rsiLength)

// Get the current state
isOverbought = rsiValue >= rsiOverbought
isOversold = rsiValue <= rsiOvesold

// State of the last extreme 0 for initialization, 1 = overbought, 2 = oversold
var laststate = 0

// Highest and Lowest prices since the last state change
var hh = low
var ll = high

// Labels
var label labelll = na
var label labelhh = na

// Swing lines
var line line_up = na
var line line_down = na

var last_actual_label_hh_price = 0.0
var last_actual_label_ll_price = 0.0


// FUNCTIONS
obLabelText() =>
    if(last_actual_label_hh_price < high)
        "HH"
    else
        "LH"
//plot(last_actual_label_hh_price)
osLabelText() =>
    if(last_actual_label_ll_price < low)
        "HL"
    else
        "LL"

// Create oversold or overbought label
createOverBoughtLabel(isIt) =>
    if(isIt)
        label.new(x=bar_index, y=na ,yloc=yloc.abovebar, style=label.style_label_down, color=color.red, size=size.tiny, text=obLabelText())
    else
        label.new(x=bar_index, y=na ,yloc=yloc.belowbar, style=label.style_label_up, color=color.green, size=size.tiny, text=osLabelText())
      
        
// Move the oversold swing and label
moveOversoldLabel() =>
    label.set_x(labelll, bar_index)
    label.set_y(labelll, low)
    label.set_text(labelll, osLabelText())
    line.set_x1(line_down, bar_index)
    line.set_y1(line_down, low)

moveOverBoughtLabel() =>
    label.set_x(labelhh, bar_index)
    label.set_y(labelhh, high)
    label.set_text(labelhh, obLabelText())
    line.set_x1(line_up, bar_index)
    line.set_y1(line_up, high)

// We go from oversold straight to overbought NEW DRAWINGS CREATED HERE
if(laststate == 2 and isOverbought)
    hh := high
    labelhh := createOverBoughtLabel(true)
    last_actual_label_ll_price := label.get_y(labelll)
    labelll_ts = label.get_x(labelll)
    labelll_price = label.get_y(labelll)
    line_up := line.new(x1=bar_index, y1=high, x2=labelll_ts, y2=labelll_price, width=1)

// We go from overbought straight to oversold  NEW DRAWINGS CREATED HERE
if(laststate == 1 and isOversold)
    ll := low
    labelll := createOverBoughtLabel(false)
    last_actual_label_hh_price := label.get_y(labelhh)
    labelhh_ts = label.get_x(labelhh)
    labelhh_price = label.get_y(labelhh)
    line_down := line.new(x1=bar_index, y1=high, x2=labelhh_ts, y2=labelhh_price, width=1)


// If we are overbought
if(isOverbought)
    if(high >= hh)
        hh := high
        moveOverBoughtLabel()
    laststate := 1
    
// If we are oversold
if(isOversold)
    if(low <= ll)
        ll := low
        moveOversoldLabel()
    laststate := 2
    
    
// If last state was overbought and we are overbought
if(laststate == 1 and isOverbought)
    if(hh <= high)
        hh := high
        moveOverBoughtLabel()
    
//If we are oversold and the last state was oversold, move the drawings to the lowest price
if(laststate == 2 and isOversold)
    if(low <= ll)
        ll := low
        moveOversoldLabel()


// If last state was overbought
if(laststate == 1)
    if(hh <= high)
        hh := high
        moveOverBoughtLabel()
        
// If last stare was oversold
if(laststate == 2)
    if(ll >= low)
        ll := low
        moveOversoldLabel()
 

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

Bladeof300

New member
Can anyone help me? I got stuck on the Damiani_volatmeter - I dont seem to understand "?" ":" functions in pinscript. I will include what I have done and the original pinescript.

My attempt
Code:
#//@version=2 #study(title='[RS]Damiani Volatmeter V0', shorttitle='DV', #overlay=false)
#//  ||  Adapted from:
#//|                        Damiani_volatmeter.mq4  v3.2              #|

Input vis_atr = 13;
Input vis_std = 20;
Input sed_atr = 40;
Input threshold_levels = 100;
Input lag_supressor = 1.4;
Input Lag_s_k = 0.5;

Def vol = lag_supressor ? atr(vis_atr) / atr(sed_atr) + lag_s_K*(s1-s3) : atr(vis_atr) / atr(sed_atr);
Def anti_thres = stdev(close, vis_std) / stdev(close, sed_std);
Def t = threshold_level - anti_thres;
Def vol_m = if (vol > t) if -1 else 0.03);
Def s1 = nz(vol[1],0);
Def s3 = nz(vol[3], 0);

Plot V = Vol;
Plot A = T;
Plot T = Vol_m;

Original work

Code:
//@version=2
study(title='[RS]Damiani Volatmeter V0', shorttitle='DV', overlay=false)
//  ||  Adapted from:
//+------------------------------------------------------------------+
//|                        Damiani_volatmeter.mq4  v3.2              |
//|                     Copyright © 2006,2007 Luis Guilherme Damiani |
//|                                      http://www.damianifx.com.br |
//+------------------------------------------------------------------+

//  ||-----------------------------------------------------------------------------------------||
//  ||  Inputs:
vis_atr = input(13)
vis_std = input(20)
sed_atr = input(40)
sed_std = input(100)
threshold_level = input(1.4)

lag_supressor = input(true)
lag_s_K = 0.5

//  ||-----------------------------------------------------------------------------------------||
//  ||
s1=nz(vol[1], 0)
s3=nz(vol[3], 0)

vol = lag_supressor ? atr(vis_atr) / atr(sed_atr) + lag_s_K*(s1-s3) : atr(vis_atr) / atr(sed_atr)
anti_thres = stdev(close, vis_std) / stdev(close, sed_std)
t = threshold_level - anti_thres
vol_m = vol > t ? -1 : 0.03
//  ||-----------------------------------------------------------------------------------------||
//  ||  Outputs:
plot(title='V', series=vol, color=lime)
plot(title='A', series=t, color=silver)
plot(title='T', series=vol_m, color=maroon)
 

Slippage

Active member
Can anyone help me? I got stuck on the Damiani_volatmeter - I dont seem to understand "?" ":" functions in pinscript. I will include what I have done and the original pinescript.

My attempt
Code:
Def vol = lag_supressor ? atr(vis_atr) / atr(sed_atr) + lag_s_K*(s1-s3) : atr(vis_atr) / atr(sed_atr);
It's just a shorthand for if then else.
Ruby:
Def vol = if lag_supressor then atr(vis_atr) / atr(sed_atr) + lag_s_K*(s1-s3) else atr(vis_atr) / atr(sed_atr);
 

Mzxir

New member
VIP
Can anyone lend me some help with converting this pinescript to thinkscript? Would be greatly appreciated

Code:
study(title="Range Filter Buy and Sell 5min", overlay=true)

// Source

src = input(defval=close, title="Source")

// Sampling Period
// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters

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

// Range Multiplier

mult = input(defval=3.0, minval=0.1, title="Range Multiplier")

// Smooth Average Range

smoothrng(x, t, m)=>
    wper      = (t*2) - 1
    avrng     = ema(abs(x - x[1]), t)
    smoothrng = ema(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

filtplot = plot(filt, color=filtcolor, linewidth=3, title="Range Filter")

// Target

hbandplot = plot(hband, color=aqua, transp=100, title="High Target")
lbandplot = plot(lband, color=fuchsia, transp=100, title="Low Target")

// Fills

fill(hbandplot, filtplot, color=aqua, title="High Target Range")
fill(lbandplot, filtplot, color=fuchsia, title="Low Target Range")

// Bar Color

barcolor(barcolor)

// Break Outs

longCond = na
shortCond = na
longCond := ((src > filt) and (src > src[1]) and (upward > 0)) or ((src > filt) and (src < src[1]) and (upward > 0)) 
shortCond := ((src < filt) and (src < src[1]) and (downward > 0)) or ((src < filt) and (src > src[1]) and (downward > 0))

CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1

//Alerts

plotshape(longCondition, title = "Buy Signal", text ="BUY", textcolor = white, style=shape.labelup, size = size.normal, location=location.belowbar, color = green, transp = 0)
plotshape(shortCondition, title = "Sell Signal", text ="SELL", textcolor = white, style=shape.labeldown, size = size.normal, location=location.abovebar, color = red, transp = 0)

alertcondition(longCondition, title="Buy Alert", message = "BUY")
alertcondition(longCondition, title="Buy Alert", message = "BUY")
alertcondition(longCondition, title="Buy Alert", message = "BUY")
alertcondition(shortCondition, title="Sell Alert", message = "SELL")
 

Sparrow

New member
VIP
I am new to TOS and have been using Trading View. I like this Golden / Death Cross indicator in pine script and could sure use help converting it to TOS. I am stumped on the part of how to color one bar background. Well, and a lot more things in life...

Code:
//Golden Cross MA 50 & 200
ma50= input(50, minval=1, title="Moving Average 50")
ma200= input(200, minval=1, title="Moving Average 200")
exponential = input(false, title="Exponential MA")
select1 = exponential ? ema(src, ma50) : sma(src, ma50)
select2 = exponential ? ema(src, ma200) : sma(src, ma200)
golden_cross() => select1 > select2
death_cross() => select1 < select2
Golden() => golden_cross() and death_cross()[1]
Death() => death_cross() and golden_cross()[1]

// Change background of cross
bgcolor(Golden() ? color.yellow : na, transp=90)
bgcolor(Death() ? color.red : na, transp=80)

plotshape(Golden(), color=color.white, style=shape.arrowup, text="Golden Cross",  size=size.normal, location=location.top)
plotshape(Death(), color=color.red, style=shape.arrowdown, text="Death Cross",  size=size.normal, location=location.top)
 

Nick

Active member
2019 Donor
VIP
There is another indicator which Matt Caruso uses in the US Investing Championship, and that is the breadth indicator called net new high. A picture of it is below:

tvAdbSQ.png


There is already a script written for it but it is for TradingView, as shown here: https://www.tradingview.com/chart/FTCH/WywLQoxo-Nasdaq-Net-new-highs/

I am just wondering, does anyone out there has the script for the indicator but it is written for Thinkorswim?

Thank you so much :) :) 🙏🙏
@BenTen @markos
Thanks for directing me to the NASDAQ indicator. Unfortunately, it is not the same. What I didn't highlight specifically was the description for the above indicator. Basically, from the video interview, Matt shared that he uses the Net High n Low indicator and only enter the trade when there are 3 consecutive period of positive net new highs.

Unfortunately, I am unable to get the source code from tradingview but I manage to extract the the description for the indicator is as follows:

"The shows daily net new highs for the Nasdaq. The background is green if there are 3 consecutive days of positive net new highs. It is red if we have 3 consecutive net new lows."

Just wondering if anyone came across something similar or able to duplicate what is provided in trading view.
Thank you very much
 
Last edited:

Lauren

New member
VIP
Can anyone convert the SuperTrend Indicator on TradingView over to ThinkorSwim:

Code:
//@version=4
study("Supertrend", overlay = true)

Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : 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)
longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
alertcondition(buySignal, title="SuperTrend Buy", message="SuperTrend Buy!")
alertcondition(sellSignal, title="SuperTrend Sell", message="SuperTrend Sell!")
changeCond = trend != trend[1]
alertcondition(changeCond, title="SuperTrend Direction Change", message="SuperTrend has changed direction!")
 

Slippage

Active member
Can anyone convert the SuperTrend Indicator on TradingView over to ThinkorSwim:

Code:
//@version=4
study("Supertrend", overlay = true)

Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : 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)
longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
alertcondition(buySignal, title="SuperTrend Buy", message="SuperTrend Buy!")
alertcondition(sellSignal, title="SuperTrend Sell", message="SuperTrend Sell!")
changeCond = trend != trend[1]
alertcondition(changeCond, title="SuperTrend Direction Change", message="SuperTrend has changed direction!")
There's a lot of indicators already here. Try the search box and you can find this: https://usethinkscript.com/threads/supertrend-indicator-by-mobius-for-thinkorswim.7/
 

Windir

New member
Market Cipher A

Code:
//@version=4

// Thanks Dynausmaux for the code
// Based on Cipher_A from falconCoin [URL]https://www.tradingview.com/script/cAw5GEAB-Market-Cipher-A-free-version-1-1/[/URL]
// Thanks to LazyBear foor WaveTrend Oscillator [URL]https://www.tradingview.com/script/2KE8wTuF-Indicator-WaveTrend-Oscillator-WT/[/URL]
// I just added the red diamond, blood diamond and yellowX pattern, i dont know if is exact but seems to be.
// Still need a lot of visual adjustments to look like market cipher A but it's an attempt
study(title="VuManChu Cipher A", shorttitle="VMC Cipher_A", overlay=true)

// FUNCTIONS {

// WaveTrend
f_wavetrend(_src, _chlen, _avg, _malen) =>
    _esa = ema(_src, _chlen)
    _de = ema(abs(_src - _esa), _chlen)
    _ci = (_src - _esa) / (0.015 * _de)
    _tci = ema(_ci, _avg)
    _wt1 = _tci
    _wt2 = sma(_wt1, _malen)
    [_wt1, _wt2]

// 8 EMA Ribbon
f_emaRibbon(_src, _e1, _e2, _e3, _e4, _e5, _e6, _e7, _e8) =>
    _ema1 = ema(_src, _e1)
    _ema2 = ema(_src, _e2)
    _ema3 = ema(_src, _e3)
    _ema4 = ema(_src, _e4)
    _ema5 = ema(_src, _e5)
    _ema6 = ema(_src, _e6)
    _ema7 = ema(_src, _e7)
    _ema8 = ema(_src, _e8)
    [_ema1, _ema2, _ema3, _ema4, _ema5, _ema6, _ema7, _ema8]
  
f_rsimfi(_period, _multiplier, _tf) => security(syminfo.tickerid, _tf, sma(((close - open) / (high - low)) * _multiplier, _period))

// } FUNCTIONS


// PARAMETERS {

// WaveTrend
wtChannelLen = input(9, title = 'WT Channel Length')
wtAverageLen = input(13, title = 'WT Average Length')
wtMASource = input(hlc3, title = 'WT MA Source')
wtMALen = input(3, title = 'WT MA Length')

// WaveTrend Overbought & Oversold lines
obLevel = input(53, title = 'WT Overbought Level 1')
obLevel2 = input(60, title = 'WT Overbought Level 2')
obLevel3 = input(100, title = 'WT Overbought Level 3')
osLevel = input(-53, title = 'WT Oversold Level 1')
osLevel2 = input(-60, title = 'WT Oversold Level 2')
osLevel3 = input(-80, title = 'WT Oversold Level 3')

// EMA Ribbon
showRibbon = input(true, "Show Ribbon")
ema1Len = input(5, title = "EMA 1 Length")
ema2Len = input(11, title = "EMA 2 Length")
ema3Len = input(15, title = "EMA 3 Length")
ema4Len = input(18, title = "EMA 4 Length")
ema5Len = input(21, title = "EMA 5 Length")
ema6Len = input(24, title = "EMA 6 Length")
ema7Len = input(28, title = "EMA 7 Length")
ema8Len = input(34, title = "EMA 8 Length")

// RSI
rsiSRC = input(close, title = "RSI Source")
rsiLen = input(14, title = "RSI Length")
rsiOversold = input(30, title = 'RSI Oversold', minval = 50, maxval = 100)
rsiOverbought = input(60, title = 'RSI Overbought', minval = 0, maxval = 50)

// RSI+MFI
rsiMFIShow = input(true, title = "Show RSI+MFI")
rsiMFIperiod = input(60, title = 'RSI+MFI Period')
rsiMFIMultiplier = input(150, title = 'RSI+MFI Area multiplier')

// }


// CALCULATE INDICATORS {

// EMA Ribbon
[ema1, ema2, ema3, ema4, ema5, ema6, ema7, ema8] = f_emaRibbon(close, ema1Len, ema2Len, ema3Len, ema4Len, ema5Len, ema6Len, ema7Len, ema8Len)

// RSI
rsi = rsi(rsiSRC, rsiLen)

// Calculates WaveTrend
[wt1, wt2] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen)

// WaveTrend Conditions
wtOverSold = wt2 <= osLevel
wtOverBought = wt2 >= obLevel
wtCross = cross(wt1, wt2)
wtCrossUp = wt2 - wt1 <= 0
wtCrossDown = wt2 - wt1 >= 0

// RSI + MFI
rsiMFI = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, timeframe.period)

// Signals
longEma = crossover(ema2, ema8)
redCross = crossunder(ema1, ema2)
blueTriangle = crossover(ema2, ema3)
redDiamond = wtCross and wtCrossDown
yellowCross = redDiamond and wt2 < 45 and wt2 > osLevel3 and rsi < 30 and rsi > 15 and rsiMFI < -5
bloodDiamond = redDiamond and redCross
bullCandle = open > ema2 and open > ema8 and (close[1] > open[1]) and (close > open) and not redDiamond and not redCross
shortEma = crossover(ema8, ema2)

// } CALCULATE INDICATORS


// DRAW {

// EMA Ribbon
ribbonDir = ema8 < ema2
colorEma = ribbonDir ? color.green : color.red
p1 = plot(ema1, color=showRibbon ? ribbonDir ? #1573d4 : color.gray : na, linewidth=2, transp=15, title="EMA 1")
p2 = plot(ema2, color=showRibbon ? ribbonDir ? #3096ff : color.gray : na, linewidth=2, transp=15, title="EMA 2")
plot(ema3, color=showRibbon ? ribbonDir ? #57abff : color.gray : na, linewidth=2, transp=15, title="EMA 3")
plot(ema4, color=showRibbon ? ribbonDir ? #85c2ff : color.gray : na, linewidth=2, transp=15, title="EMA 4")
plot(ema5, color=showRibbon ? ribbonDir ? #9bcdff : color.gray : na, linewidth=2, transp=15, title="EMA 5")
plot(ema6, color=showRibbon ? ribbonDir ? #b3d9ff : color.gray : na, linewidth=2, transp=15, title="EMA 6")
plot(ema7, color=showRibbon ? ribbonDir ? #c9e5ff : color.gray : na, linewidth=2, transp=15, title="EMA 7")
plot(ema8, color=showRibbon ? ribbonDir ? #dfecfb : color.gray : na, linewidth=2, transp=15, title="EMA 8")
p8 = plot(ema8, color=showRibbon ? na : colorEma, linewidth=2, transp=0, title="EMA 8")
fill(p1, p2, color = #1573d4, transp = 85)
fill(p2, p8, color = #363a45, transp = 85)

// SHAPES

plotshape(longEma, style=shape.circle, color=#00ff00, location=location.abovebar, size=size.tiny, title="Long EMA Signal", transp=50)
plotshape(shortEma, style=shape.circle, color=#ff0000, location=location.abovebar, size=size.tiny, title="Short EMA Signal", transp=50)
plotshape(redCross, style=shape.xcross, color=#ff0000, location=location.abovebar, size=size.tiny, title="Red cross", transp=50)
plotshape(blueTriangle, style=shape.triangleup, color=#0064ff, location=location.abovebar, size=size.small, title="Blue Triangle", transp=50)
plotshape(redDiamond, style=shape.diamond, color=#ff0000, location=location.abovebar, size=size.tiny, title="Red Diamond", transp=25)
plotshape(bullCandle, style=shape.diamond, color=color.yellow, location=location.abovebar, size=size.tiny, title="Bull candle", transp=75)
plotshape(bloodDiamond, style=shape.diamond, color=#ff0000, location=location.abovebar, size=size.small, title="Blood Diamond", transp=15)
plotshape(yellowCross, style=shape.xcross, color=color.yellow, location=location.abovebar, size=size.small, title="Yellow Cross", transp=25)
// } DRAW


// ALERTS {
alertcondition(redDiamond != 0, "Red Diamond", "Red Diamond")
alertcondition(bloodDiamond != 0, "Blood Diamond", "Blood Diamond")
alertcondition(yellowCross != 0, "YellowX", "YellowX")
alertcondition(redCross != 0, "RedX", "RedX")
alertcondition(longEma != 0, "Longema", "Longema")
alertcondition(blueTriangle != 0, "Bluetriangle", "Bluetriangle")
// } ALERTS

VMC Cipher B

Code:
//@version=4

//  Thanks to dynausmaux for the code..
//  Thanks to falconCoin for [URL]https://www.tradingview.com/script/KVfgBvDd-Market-Cipher-B-Free-version-with-Buy-and-sell/[/URL] inspired me to start this.
//  Thanks to LazyBear for WaveTrend Oscillator [URL]https://www.tradingview.com/script/2KE8wTuF-Indicator-WaveTrend-Oscillator-WT/[/URL]
//  Thanks to RicardoSantos for [URL]https://www.tradingview.com/script/3oeDh0Yq-RS-Price-Divergence-Detector-V2/[/URL]
//  Thanks to LucemAnb for Plain Stochastic Divergence [URL]https://www.tradingview.com/script/FCUgF8ag-Plain-Stochastic-Divergence/[/URL]
//  Thanks to andreholanda73 for MFI+RSI Area [URL]https://www.tradingview.com/script/UlGZzUAr/[/URL]
//  I especially thanks to TradingView for its platform that facilitates development and learning.
//
//  CIRCLES & TRIANGLES:
//    - LITTLE CIRCLE: They appear at all WaveTrend wave crossings.
//    - GREEN CIRCLE: The wavetrend waves are at the oversold level and have crossed up (bullish).
//    - RED CIRCLE: The wavetrend waves are at the overbought level and have crossed down (bearish).
//    - GOLD/ORANGE CIRCLE: When RSI is below 20, WaveTrend waves are below or equal to -80 and have crossed up after good bullish divergence (DONT BUY WHEN GOLD CIRCLE APPEAR).
//    - None of these circles are certain signs to trade. It is only information that can help you.
//    - PURPLE TRIANGLE: Appear when a bullish or bearish divergence is formed and WaveTrend waves crosses at overbought and oversold points.
//
//  NOTES:
//    - I am not an expert trader or know how to program pine script as such, in fact it is my first indicator only to study and all the code is copied and modified from other codes that are published in TradingView.
//    - I am very grateful to the entire TV community that publishes codes so that other newbies like me can learn and present their results. This is an attempt to imitate Market Cipher B.
//    - Settings by default are for 4h timeframe, divergences are more stronger and accurate. Haven't tested in all timeframes, only 2h and 4h.
//    - If you get an interesting result in other timeframes I would be very grateful if you would comment your configuration to implement it or at least check it.
//
//  CONTRIBUTIONS:
//    - Tip/Idea: Add higher timeframe analysis for bearish/bullish patterns at the current timeframe.
//    + Bearish/Bullish FLAG:
//      - MFI+RSI Area are RED (Below 0).
//      - Wavetrend waves are above 0 and crosses down.
//      - VWAP Area are below 0 on higher timeframe.
//      - This pattern reversed becomes bullish.
//    - Tip/Idea: Check the last heikinashi candle from 2 higher timeframe
//    + Bearish/Bullish DIAMOND:
//      - HT Candle is red
//      - WT > 0 and crossed down

study(title = 'VuManChu B Divergences', shorttitle = 'VMC Cipher_B_Divergences')

// PARAMETERS {

// WaveTrend
wtShow = input(true, title = 'Show WaveTrend', type = input.bool)
wtBuyShow = input(true, title = 'Show Buy dots', type = input.bool)
wtGoldShow = input(true, title = 'Show Gold dots', type = input.bool)
wtSellShow = input(true, title = 'Show Sell dots', type = input.bool)
wtDivShow = input(true, title = 'Show Div. dots', type = input.bool)
vwapShow = input(true, title = 'Show Fast WT', type = input.bool)
wtChannelLen = input(9, title = 'WT Channel Length', type = input.integer)
wtAverageLen = input(12, title = 'WT Average Length', type = input.integer)
wtMASource = input(hlc3, title = 'WT MA Source', type = input.source)
wtMALen = input(3, title = 'WT MA Length', type = input.integer)

// WaveTrend Overbought & Oversold lines
obLevel = input(53, title = 'WT Overbought Level 1', type = input.integer)
obLevel2 = input(60, title = 'WT Overbought Level 2', type = input.integer)
obLevel3 = input(100, title = 'WT Overbought Level 3', type = input.integer)
osLevel = input(-53, title = 'WT Oversold Level 1', type = input.integer)
osLevel2 = input(-60, title = 'WT Oversold Level 2', type = input.integer)
osLevel3 = input(-100, title = 'WT Oversold Level 3', type = input.integer)

// Divergence WT
wtShowDiv = input(true, title = 'Show WT Regular Divergences', type = input.bool)
wtShowHiddenDiv = input(false, title = 'Show WT Hidden Divergences', type = input.bool)
showHiddenDiv_nl = input(true, title = 'Not apply OB/OS Limits on Hidden Divergences', type = input.bool)
wtDivOBLevel = input(45, title = 'WT Bearish Divergence min', type = input.integer)
wtDivOSLevel = input(-65, title = 'WT Bullish Divergence min', type = input.integer)

// Divergence extra range
wtDivOBLevel_addshow = input(true, title = 'Show 2nd WT Regular Divergences', type = input.bool)
wtDivOBLevel_add = input(15, title = 'WT 2nd Bearish Divergence', type = input.integer)
wtDivOSLevel_add = input(-40, title = 'WT 2nd Bullish Divergence 15 min', type = input.integer)

// RSI+MFI
rsiMFIShow = input(true, title = 'Show MFI', type = input.bool)
rsiMFIperiod = input(60,title = 'MFI Period', type = input.integer)
rsiMFIMultiplier = input(175, title = 'MFI Area multiplier', type = input.float)
rsiMFIPosY = input(2.5, title = 'MFI Area Y Pos', type = input.float)

// RSI
rsiShow = input(false, title = 'Show RSI', type = input.bool)
rsiSRC = input(close, title = 'RSI Source', type = input.source)
rsiLen = input(14, title = 'RSI Length', type = input.integer)
rsiOversold = input(30, title = 'RSI Oversold', minval = 50, maxval = 100, type = input.integer)
rsiOverbought = input(60, title = 'RSI Overbought', minval = 0, maxval = 50, type = input.integer)

// Divergence RSI
rsiShowDiv = input(false, title = 'Show RSI Regular Divergences', type = input.bool)
rsiShowHiddenDiv = input(false, title = 'Show RSI Hidden Divergences', type = input.bool)
rsiDivOBLevel = input(60, title = 'RSI Bearish Divergence min', type = input.integer)
rsiDivOSLevel = input(30, title = 'RSI Bullish Divergence min', type = input.integer)

// RSI Stochastic
stochShow = input(true, title = 'Show Stochastic RSI', type = input.bool)
stochUseLog = input(true, title=' Use Log?', type = input.bool)
stochAvg = input(false, title='Use Average of both K & D', type = input.bool)
stochSRC = input(close, title = 'Stochastic RSI Source', type = input.source)
stochLen = input(14, title = 'Stochastic RSI Length', type = input.integer)
stochRsiLen = input(14, title = 'RSI Length ', type = input.integer)
stochKSmooth = input(3, title = 'Stochastic RSI K Smooth', type = input.integer)
stochDSmooth = input(3, title = 'Stochastic RSI D Smooth', type = input.integer)

// Divergence stoch
stochShowDiv = input(false, title = 'Show Stoch Regular Divergences', type = input.bool)
stochShowHiddenDiv = input(false, title = 'Show Stoch Hidden Divergences', type = input.bool)

// Schaff Trend Cycle
tcLine = input(false, title="Show Schaff TC line", type=input.bool)
tcSRC = input(close, title = 'Schaff TC Source', type = input.source)
tclength = input(10, title="Schaff TC", type=input.integer)
tcfastLength = input(23, title="Schaff TC Fast Lenght", type=input.integer)
tcslowLength = input(50, title="Schaff TC Slow Length", type=input.integer)
tcfactor = input(0.5, title="Schaff TC Factor", type=input.float)

// Sommi Flag
sommiFlagShow = input(false, title = 'Show Sommi flag', type = input.bool)
sommiShowVwap = input(false, title = 'Show Sommi F. Wave', type = input.bool)
sommiVwapTF = input('720', title = 'Sommi F. Wave timeframe', type = input.string)
sommiVwapBearLevel = input(0, title = 'F. Wave Bear Level (less than)', type = input.integer)
sommiVwapBullLevel = input(0, title = 'F. Wave Bull Level (more than)', type = input.integer)
soomiFlagWTBearLevel = input(0, title = 'WT Bear Level (more than)', type = input.integer)
soomiFlagWTBullLevel = input(0, title = 'WT Bull Level (less than)', type = input.integer)
soomiRSIMFIBearLevel = input(0, title = 'Money flow Bear Level (less than)', type = input.integer)
soomiRSIMFIBullLevel = input(0, title = 'Money flow Bull Level (more than)', type = input.integer)

// Sommi Diamond
sommiDiamondShow = input(false, title = 'Show Sommi diamond', type = input.bool)
sommiHTCRes = input('60', title = 'HTF Candle Res. 1', type = input.string)
sommiHTCRes2 = input('240', title = 'HTF Candle Res. 2', type = input.string)
soomiDiamondWTBearLevel = input(0, title = 'WT Bear Level (More than)', type = input.integer)
soomiDiamondWTBullLevel = input(0, title = 'WT Bull Level (Less than)', type = input.integer)

// macd Colors
macdWTColorsShow = input(false, title = 'Show MACD Colors', type = input.bool)
macdWTColorsTF = input('240', title = 'MACD Colors MACD TF', type = input.string)

darkMode = input(false, title = 'Dark mode', type = input.bool)


// Colors
colorRed = #ff0000
colorPurple = #e600e6
colorGreen = #3fff00
colorOrange = #e2a400
colorYellow = #ffe500
colorWhite = #ffffff
colorPink = #ff00f0
colorBluelight = #31c0ff

colorWT1 = #90caf9
colorWT2 = #0d47a1

colorWT2_ = #131722

colormacdWT1a = #4caf58
colormacdWT1b = #af4c4c
colormacdWT1c = #7ee57e
colormacdWT1d = #ff3535

colormacdWT2a = #305630
colormacdWT2b = #310101
colormacdWT2c = #132213
colormacdWT2d = #770000

// } PARAMETERS


// FUNCTIONS {
 
// Divergences
f_top_fractal(src) => src[4] < src[2] and src[3] < src[2] and src[2] > src[1] and src[2] > src[0]
f_bot_fractal(src) => src[4] > src[2] and src[3] > src[2] and src[2] < src[1] and src[2] < src[0]
f_fractalize(src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0

f_findDivs(src, topLimit, botLimit, useLimits) =>
    fractalTop = f_fractalize(src) > 0 and (useLimits ? src[2] >= topLimit : true) ? src[2] : na
    fractalBot = f_fractalize(src) < 0 and (useLimits ? src[2] <= botLimit : true) ? src[2] : na
    highPrev = valuewhen(fractalTop, src[2], 0)[2]
    highPrice = valuewhen(fractalTop, high[2], 0)[2]
    lowPrev = valuewhen(fractalBot, src[2], 0)[2]
    lowPrice = valuewhen(fractalBot, low[2], 0)[2]
    bearSignal = fractalTop and high[2] > highPrice and src[2] < highPrev
    bullSignal = fractalBot and low[2] < lowPrice and src[2] > lowPrev
    bearDivHidden = fractalTop and high[2] < highPrice and src[2] > highPrev
    bullDivHidden = fractalBot and low[2] > lowPrice and src[2] < lowPrev
    [fractalTop, fractalBot, lowPrev, bearSignal, bullSignal, bearDivHidden, bullDivHidden]
       
// RSI+MFI
f_rsimfi(_period, _multiplier, _tf) => security(syminfo.tickerid, _tf, sma(((close - open) / (high - low)) * _multiplier, _period) - rsiMFIPosY)
  
// WaveTrend
f_wavetrend(src, chlen, avg, malen, tf) =>
    tfsrc = security(syminfo.tickerid, tf, src)
    esa = ema(tfsrc, chlen)
    de = ema(abs(tfsrc - esa), chlen)
    ci = (tfsrc - esa) / (0.015 * de)
    wt1 = security(syminfo.tickerid, tf, ema(ci, avg))
    wt2 = security(syminfo.tickerid, tf, sma(wt1, malen))
    wtVwap = wt1 - wt2
    wtOversold = wt2 <= osLevel
    wtOverbought = wt2 >= obLevel
    wtCross = cross(wt1, wt2)
    wtCrossUp = wt2 - wt1 <= 0
    wtCrossDown = wt2 - wt1 >= 0
    wtCrosslast = cross(wt1[2], wt2[2])
    wtCrossUplast = wt2[2] - wt1[2] <= 0
    wtCrossDownlast = wt2[2] - wt1[2] >= 0
    [wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCrosslast, wtCrossUplast, wtCrossDownlast, wtVwap]

// Schaff Trend Cycle
f_tc(src, length, fastLength, slowLength) =>
    ema1 = ema(src, fastLength)
    ema2 = ema(src, slowLength)
    macdVal = ema1 - ema2   
    alpha = lowest(macdVal, length)
    beta = highest(macdVal, length) - alpha
    gamma = (macdVal - alpha) / beta * 100
    gamma := beta > 0 ? gamma : nz(gamma[1])
    delta = gamma
    delta := na(delta[1]) ? delta : delta[1] + tcfactor * (gamma - delta[1])
    epsilon = lowest(delta, length)
    zeta = highest(delta, length) - epsilon
    eta = (delta - epsilon) / zeta * 100
    eta := zeta > 0 ? eta : nz(eta[1])
    stcReturn = eta
    stcReturn := na(stcReturn[1]) ? stcReturn : stcReturn[1] + tcfactor * (eta - stcReturn[1])
    stcReturn

// Stochastic RSI
f_stochrsi(_src, _stochlen, _rsilen, _smoothk, _smoothd, _log, _avg) =>
    src = _log ? log(_src) : _src
    rsi = rsi(src, _rsilen)
    kk = sma(stoch(rsi, rsi, rsi, _stochlen), _smoothk)
    d1 = sma(kk, _smoothd)
    avg_1 = avg(kk, d1)
    k = _avg ? avg_1 : kk
    [k, d1]

// MACD
f_macd(src, fastlen, slowlen, sigsmooth, tf) =>
    fast_ma = security(syminfo.tickerid, tf, ema(src, fastlen))
    slow_ma = security(syminfo.tickerid, tf, ema(src, slowlen))
    macd = fast_ma - slow_ma,
    signal = security(syminfo.tickerid, tf, sma(macd, sigsmooth))
    hist = macd - signal
    [macd, signal, hist]

// MACD Colors on WT   
f_macdWTColors(tf) =>
    hrsimfi = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, tf)
    [macd, signal, hist] = f_macd(close, 28, 42, 9, macdWTColorsTF)
    macdup = macd >= signal
    macddown = macd <= signal
    macdWT1Color = macdup ? hrsimfi > 0 ? colormacdWT1c : colormacdWT1a : macddown ? hrsimfi < 0 ? colormacdWT1d : colormacdWT1b : na
    macdWT2Color = macdup ? hrsimfi < 0 ? colormacdWT2c : colormacdWT2a : macddown ? hrsimfi < 0 ? colormacdWT2d : colormacdWT2b : na
    [macdWT1Color, macdWT2Color]
   
// Get higher timeframe candle
f_getTFCandle(_tf) =>
    _open  = security(heikinashi(syminfo.tickerid), _tf, open, barmerge.gaps_off, barmerge.lookahead_on)
    _close = security(heikinashi(syminfo.tickerid), _tf, close, barmerge.gaps_off, barmerge.lookahead_on)
    _high  = security(heikinashi(syminfo.tickerid), _tf, high, barmerge.gaps_off, barmerge.lookahead_on)
    _low   = security(heikinashi(syminfo.tickerid), _tf, low, barmerge.gaps_off, barmerge.lookahead_on)
    hl2   = (_high + _low) / 2.0
    newBar = change(_open)
    candleBodyDir = _close > _open
    [candleBodyDir, newBar]

// Sommi flag
f_findSommiFlag(tf, wt1, wt2, rsimfi, wtCross, wtCrossUp, wtCrossDown) =>   
    [hwt1, hwt2, hwtOversold, hwtOverbought, hwtCross, hwtCrossUp, hwtCrossDown, hwtCrosslast, hwtCrossUplast, hwtCrossDownlast, hwtVwap] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, tf)     
   
    bearPattern = rsimfi < soomiRSIMFIBearLevel and
                   wt2 > soomiFlagWTBearLevel and
                   wtCross and
                   wtCrossDown and
                   hwtVwap < sommiVwapBearLevel
                  
    bullPattern = rsimfi > soomiRSIMFIBullLevel and
                   wt2 < soomiFlagWTBullLevel and
                   wtCross and
                   wtCrossUp and
                   hwtVwap > sommiVwapBullLevel
   
    [bearPattern, bullPattern, hwtVwap]
   
f_findSommiDiamond(tf, tf2, wt1, wt2, wtCross, wtCrossUp, wtCrossDown) =>
    [candleBodyDir, newBar] = f_getTFCandle(tf)
    [candleBodyDir2, newBar2] = f_getTFCandle(tf2)
    bearPattern = wt2 >= soomiDiamondWTBearLevel and
                   wtCross and
                   wtCrossDown and
                   not candleBodyDir and
                   not candleBodyDir2                  
    bullPattern = wt2 <= soomiDiamondWTBullLevel and
                   wtCross and
                   wtCrossUp and
                   candleBodyDir and
                   candleBodyDir2
    [bearPattern, bullPattern]

// } FUNCTIONS 

// CALCULATE INDICATORS {

// RSI
rsi = rsi(rsiSRC, rsiLen)
rsiColor = rsi <= rsiOversold ? colorGreen : rsi >= rsiOverbought ? colorRed : colorPurple

// RSI + MFI Area
rsiMFI = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, timeframe.period)
rsiMFIColor = rsiMFI > 0 ? #3ee145 : #ff3d2e

// Calculates WaveTrend
[wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCross_last, wtCrossUp_last, wtCrossDown_last, wtVwap] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, timeframe.period)

// Stochastic RSI
[stochK, stochD] = f_stochrsi(stochSRC, stochLen, stochRsiLen, stochKSmooth, stochDSmooth, stochUseLog, stochAvg)

// Schaff Trend Cycle
tcVal = f_tc(tcSRC, tclength, tcfastLength, tcslowLength)

// Sommi flag
[sommiBearish, sommiBullish, hvwap] = f_findSommiFlag(sommiVwapTF, wt1, wt2, rsiMFI, wtCross,  wtCrossUp, wtCrossDown)

//Sommi diamond
[sommiBearishDiamond, sommiBullishDiamond] = f_findSommiDiamond(sommiHTCRes, sommiHTCRes2, wt1, wt2, wtCross, wtCrossUp, wtCrossDown)

// macd colors
[macdWT1Color, macdWT2Color] = f_macdWTColors(macdWTColorsTF)

// WT Divergences
[wtFractalTop, wtFractalBot, wtLow_prev, wtBearDiv, wtBullDiv, wtBearDivHidden, wtBullDivHidden] = f_findDivs(wt2, wtDivOBLevel, wtDivOSLevel, true)
   
[wtFractalTop_add, wtFractalBot_add, wtLow_prev_add, wtBearDiv_add, wtBullDiv_add, wtBearDivHidden_add, wtBullDivHidden_add] =  f_findDivs(wt2, wtDivOBLevel_add, wtDivOSLevel_add, true)
[wtFractalTop_nl, wtFractalBot_nl, wtLow_prev_nl, wtBearDiv_nl, wtBullDiv_nl, wtBearDivHidden_nl, wtBullDivHidden_nl] =  f_findDivs(wt2, 0, 0, false)

wtBearDivHidden_ = showHiddenDiv_nl ? wtBearDivHidden_nl : wtBearDivHidden
wtBullDivHidden_ = showHiddenDiv_nl ? wtBullDivHidden_nl : wtBullDivHidden

wtBearDivColor = (wtShowDiv and wtBearDiv) or (wtShowHiddenDiv and wtBearDivHidden_) ? colorRed : na
wtBullDivColor = (wtShowDiv and wtBullDiv) or (wtShowHiddenDiv and wtBullDivHidden_) ? colorGreen : na

wtBearDivColor_add = (wtShowDiv and (wtDivOBLevel_addshow and wtBearDiv_add)) or (wtShowHiddenDiv and (wtDivOBLevel_addshow and wtBearDivHidden_add)) ? #9a0202 : na
wtBullDivColor_add = (wtShowDiv and (wtDivOBLevel_addshow and wtBullDiv_add)) or (wtShowHiddenDiv and (wtDivOBLevel_addshow and wtBullDivHidden_add)) ? #1b5e20 : na

// RSI Divergences
[rsiFractalTop, rsiFractalBot, rsiLow_prev, rsiBearDiv, rsiBullDiv, rsiBearDivHidden, rsiBullDivHidden] = f_findDivs(rsi, rsiDivOBLevel, rsiDivOSLevel, true)
[rsiFractalTop_nl, rsiFractalBot_nl, rsiLow_prev_nl, rsiBearDiv_nl, rsiBullDiv_nl, rsiBearDivHidden_nl, rsiBullDivHidden_nl] = f_findDivs(rsi, 0, 0, false)

rsiBearDivHidden_ = showHiddenDiv_nl ? rsiBearDivHidden_nl : rsiBearDivHidden
rsiBullDivHidden_ = showHiddenDiv_nl ? rsiBullDivHidden_nl : rsiBullDivHidden

rsiBearDivColor = (rsiShowDiv and rsiBearDiv) or (rsiShowHiddenDiv and rsiBearDivHidden_) ? colorRed : na
rsiBullDivColor = (rsiShowDiv and rsiBullDiv) or (rsiShowHiddenDiv and rsiBullDivHidden_) ? colorGreen : na

// Stoch Divergences
[stochFractalTop, stochFractalBot, stochLow_prev, stochBearDiv, stochBullDiv, stochBearDivHidden, stochBullDivHidden] = f_findDivs(stochK, 0, 0, false)

stochBearDivColor = (stochShowDiv and stochBearDiv) or (stochShowHiddenDiv and stochBearDivHidden) ? colorRed : na
stochBullDivColor = (stochShowDiv and stochBullDiv) or (stochShowHiddenDiv and stochBullDivHidden) ? colorGreen : na


// Small Circles WT Cross
signalColor = wt2 - wt1 > 0 ? color.red : color.lime

// Buy signal.
buySignal = wtCross and wtCrossUp and wtOversold

buySignalDiv = (wtShowDiv and wtBullDiv) or
               (wtShowDiv and wtBullDiv_add) or
               (stochShowDiv and stochBullDiv) or
               (rsiShowDiv and rsiBullDiv)
   
buySignalDiv_color = wtBullDiv ? colorGreen :
                     wtBullDiv_add ? color.new(colorGreen, 60) :
                     rsiShowDiv ? colorGreen : na

// Sell signal
sellSignal = wtCross and wtCrossDown and wtOverbought
            
sellSignalDiv = (wtShowDiv and wtBearDiv) or
               (wtShowDiv and wtBearDiv_add) or
               (stochShowDiv and stochBearDiv) or
               (rsiShowDiv and rsiBearDiv)
                   
sellSignalDiv_color = wtBearDiv ? colorRed :
                     wtBearDiv_add ? color.new(colorRed, 60) :
                     rsiBearDiv ? colorRed : na

// Gold Buy
lastRsi = valuewhen(wtFractalBot, rsi[2], 0)[2]
wtGoldBuy = ((wtShowDiv and wtBullDiv) or (rsiShowDiv and rsiBullDiv)) and
           wtLow_prev <= osLevel3 and
           wt2 > osLevel3 and
           wtLow_prev - wt2 <= -5 and
           lastRsi < 30          
         
// } CALCULATE INDICATORS


// DRAW {
bgcolor(darkMode ? color.new(#000000, 80) : na)
zLine = plot(0, color = color.new(colorWhite, 50))

//  MFI BAR
rsiMfiBarTopLine = plot(rsiMFIShow ? -95 : na, title = 'MFI Bar TOP Line', transp = 100)
rsiMfiBarBottomLine = plot(rsiMFIShow ? -99 : na, title = 'MFI Bar BOTTOM Line', transp = 100)
fill(rsiMfiBarTopLine, rsiMfiBarBottomLine, title = 'MFI Bar Colors', color = rsiMFIColor, transp = 75)

// WT Areas
plot(wtShow ? wt1 : na, style = plot.style_area, title = 'WT Wave 1', color = macdWTColorsShow ? macdWT1Color : colorWT1, transp = 0)
plot(wtShow ? wt2 : na, style = plot.style_area, title = 'WT Wave 2', color = macdWTColorsShow ? macdWT2Color : darkMode ? colorWT2_ : colorWT2 , transp = 20)

// VWAP
plot(vwapShow ? wtVwap : na, title = 'VWAP', color = colorYellow, style = plot.style_area, linewidth = 2, transp = 45)

// MFI AREA
rsiMFIplot = plot(rsiMFIShow ? rsiMFI: na, title = 'RSI+MFI Area', color = rsiMFIColor, transp = 20)
fill(rsiMFIplot, zLine, rsiMFIColor, transp = 40)

// WT Div

plot(series = wtFractalTop ? wt2[2] : na, title = 'WT Bearish Divergence', color = wtBearDivColor, linewidth = 2, offset = -2)
plot(series = wtFractalBot ? wt2[2] : na, title = 'WT Bullish Divergence', color = wtBullDivColor, linewidth = 2, offset = -2)

// WT 2nd Div
plot(series = wtFractalTop_add ? wt2[2] : na, title = 'WT 2nd Bearish Divergence', color = wtBearDivColor_add, linewidth = 2, offset = -2)
plot(series = wtFractalBot_add ? wt2[2] : na, title = 'WT 2nd Bullish Divergence', color = wtBullDivColor_add, linewidth = 2, offset = -2)

// RSI
plot(rsiShow ? rsi : na, title = 'RSI', color = rsiColor, linewidth = 2, transp = 25)

// RSI Div
plot(series = rsiFractalTop ? rsi[2] : na, title='RSI Bearish Divergence', color = rsiBearDivColor, linewidth = 1, offset = -2)
plot(series = rsiFractalBot ? rsi[2] : na, title='RSI Bullish Divergence', color = rsiBullDivColor, linewidth = 1, offset = -2)

// Stochastic RSI
stochKplot = plot(stochShow ? stochK : na, title = 'Stoch K', color = color.new(#21baf3, 0), linewidth = 2)
stochDplot = plot(stochShow ? stochD : na, title = 'Stoch D', color = color.new(#673ab7, 60), linewidth = 1)
stochFillColor = stochK >= stochD ? color.new(#21baf3, 75) : color.new(#673ab7, 60)
fill(stochKplot, stochDplot, title='KD Fill', color=stochFillColor)

// Stoch Div
plot(series = stochFractalTop ? stochK[2] : na, title='Stoch Bearish Divergence', color = stochBearDivColor, linewidth = 1, offset = -2)
plot(series = stochFractalBot ? stochK[2] : na, title='Stoch Bullish Divergence', color = stochBullDivColor, linewidth = 1, offset = -2)

// Schaff Trend Cycle
plot(tcLine ? tcVal : na, color = color.new(#673ab7, 25), linewidth = 2, title = "Schaff Trend Cycle 1")
plot(tcLine ? tcVal : na, color = color.new(colorWhite, 50), linewidth = 1, title = "Schaff Trend Cycle 2")


// Draw Overbought & Oversold lines
plot(obLevel, title = 'Over Bought Level 1', color = colorWhite, linewidth = 1, style = plot.style_cross, transp = 35)
plot(obLevel2, title = 'Over Bought Level 2', color = colorWhite, linewidth = 1, style = plot.style_stepline, transp = 35)
plot(obLevel3, title = 'Over Bought Level 3', color = colorWhite, linewidth = 2, style = plot.style_circles, transp = 35)

plot(osLevel, title = 'Over Sold Level 1', color = colorWhite, linewidth = 1, style = plot.style_cross, transp = 35)
plot(osLevel2, title = 'Over Sold Level 2', color = colorWhite, linewidth = 1, style = plot.style_stepline, transp = 35)

// Sommi flag
plotchar(sommiFlagShow and sommiBearish ? 108 : na, title = 'Sommi bearish flag', char='⚑', color = colorPink, location = location.absolute, size = size.tiny, transp = 0)
plotchar(sommiFlagShow and sommiBullish ? -108 : na, title = 'Sommi bullish flag', char='⚑', color = colorBluelight, location = location.absolute, size = size.tiny, transp = 0)
plot(sommiShowVwap ? ema(hvwap, 3) : na, title = 'Sommi higher VWAP', color = colorYellow, linewidth = 2, style = plot.style_line, transp = 15)

// Sommi diamond
plotchar(sommiDiamondShow and sommiBearishDiamond ? 108 : na, title = 'Sommi bearish diamond', char='◆', color = colorPink, location = location.absolute, size = size.tiny, transp = 0)
plotchar(sommiDiamondShow and sommiBullishDiamond ? -108 : na, title = 'Sommi bullish diamond', char='◆', color = colorBluelight, location = location.absolute, size = size.tiny, transp = 0)

// Circles
plot(wtCross ? wt2 : na, title = 'Buy and sell circle', color = signalColor, style = plot.style_circles, linewidth = 3, transp = 15)

plotchar(wtBuyShow and buySignal ? -107 : na, title = 'Buy circle', char='·', color = colorGreen, location = location.absolute, size = size.small, transp = 50)
plotchar(wtSellShow and sellSignal ? 105 : na , title = 'Sell circle', char='·', color = colorRed, location = location.absolute, size = size.small, transp = 50)

plotchar(wtDivShow and buySignalDiv ? -106 : na, title = 'Divergence buy circle', char='•', color = buySignalDiv_color, location = location.absolute, size = size.small, offset = -2, transp = 15)
plotchar(wtDivShow and sellSignalDiv ? 106 : na, title = 'Divergence sell circle', char='•', color = sellSignalDiv_color, location = location.absolute, size = size.small, offset = -2, transp = 15)

plotchar(wtGoldBuy and wtGoldShow ? -106 : na, title = 'Gold  buy gold circle', char='•', color = colorOrange, location = location.absolute, size = size.small, offset = -2, transp = 15)

// } DRAW


// ALERTS {
 
// BUY
alertcondition(buySignal, 'Buy (Big green circle)', 'Green circle WaveTrend Oversold')
alertcondition(buySignalDiv, 'Buy (Big green circle + Div)', 'Buy & WT Bullish Divergence & WT Overbought')
alertcondition(wtGoldBuy, 'GOLD Buy (Big GOLDEN circle)', 'Green & GOLD circle WaveTrend Overbought')
alertcondition(sommiBullish or sommiBullishDiamond, 'Sommi bullish flag/diamond', 'Blue flag/diamond')
alertcondition(wtCross and wtCrossUp, 'Buy (Small green dot)', 'Buy small circle')

// SELL
alertcondition(sommiBearish or sommiBearishDiamond, 'Sommi bearish flag/diamond', 'Purple flag/diamond')
alertcondition(sellSignal, 'Sell (Big red circle)', 'Red Circle WaveTrend Overbought')
alertcondition(sellSignalDiv, 'Sell (Big red circle + Div)', 'Buy & WT Bearish Divergence & WT Overbought')
alertcondition(wtCross and wtCrossDown, 'Sell (Small red dot)', 'Sell small circle')

// } ALERTS
 

NEKSUS

New member
Hello!

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

Code:
//@version=4

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



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


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

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



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


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


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


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


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


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

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



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


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


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


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


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


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

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


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


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


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

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


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


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


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


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



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


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

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

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

alertcondition(conditionMedium, title='Any Medium Vol', message='Any Bar Medium Volume Threshold')
alertcondition(conditionMedium and open < close, title='Up Medium Vol', message='Up Bar Medium Volume Threshold')
alertcondition(conditionMedium and open > close, title='Down Medium Vol', message='Down Bar Medium Volume Threshold')
Hello! Will someone do it for $ ? (Pay Pal)
 

wesam

New member
Hi this is a tradingview indicator, i will like to use it on thinkorswim as a scanner. i will like to only scan for stocks that is "If Volume is greater then the previous 40 intervals, Volume is black." thank you

Code:
// If Volume is less then the previous 20 intervals, Volume is gray.
// If Volume is greater then the previous 40 intervals, Volume is black.
// If Volume is less then the previous 2 intervals, Volume is purple.
// If Volume is less then the previous, Volume is red.
// If Volume is greater then the previous, Volume is blue.
// Other - white.
// You can add on the indicator a 2.5 Standart Deviation of a 20 period
// Bollinger Band Shifted 3 periods forward.
////////////////////////////////////////////////////////////
study(title="Hidden Gap`s VSA Volume")
Length_HH = input(40, minval=1)
Length_LLSmall = input(2, minval=2)
Length_LLBig = input(20, minval=2)
LengthMA    = input(20, minval=1)
hline(0, color=gray, linestyle=dashed)
xSMA_vol = sma(volume, LengthMA)
xHH_vol = highest(volume, Length_HH)
xLL_volSmall = lowest(volume, Length_LLSmall)
xLL_volBig = lowest(volume, Length_LLBig)
BarColor = iff(volume > xHH_vol[1], black,
             iff(volume < xLL_volBig[1], gray,
              iff(volume < xLL_volSmall[1], purple,
               iff(volume > volume[1], blue,
                 iff(volume < volume[1], red, white)))))
plot(volume, color=BarColor, title="Vol", style=histogram, linewidth=2)
plot(xSMA_vol, color=black, title="SMA")
 

strehsum

New member
I would like to convert this to a TOS script if someone could help me? Thanks!

Code:
hma(src, len) => wma(2 * wma(src, len/2) - wma(src, len), round(sqrt(len)))

ma = input(title="MA type", defval="SMA", options=["EMA", "SMA", "Hull", "WMA"])

MA(price, length) => 
    current = if ma == 'EMA'
        ema(price, length)
    else
        if ma == 'SMA'
            sma(price, length)
        else
            if ma == 'WMA'
                wma(price, length)
            else
                hma(price, length)
    current
    
price =  input(close, title='Price')
maFast = MA(price, input(13, title='MA Fast'))
maSlow = MA(price, input(48, title='MA Slow'))
maTurtle = MA(price, input(200, title='MA Turtle'))
viewCrossFlag = input(false, title='View MA Slow/Turtle crossover')

plot(maTurtle, title="MA Turtle", style=circles, linewidth=2, color=maFast>=maSlow ? #CCCCCC : #222222)
plot(maFast, title="MA Fast", style=line, linewidth=2, color=olive, transp=0)
plot(maSlow, title="MA Slow", style=line, linewidth=2, color=maroon, transp=0)

plotchar(viewCrossFlag and crossunder(maSlow, maTurtle), char='✜', color=red, location=location.top, transp=0, size=size.tiny)
plotchar(viewCrossFlag and crossover(maSlow, maTurtle), char='✜', color=green, location=location.bottom, transp=0, size=size.tiny)

alertcondition(crossunder(maFast, maSlow), title='MA cross sell', message='We have a MA sell signal!')
alertcondition(crossover(maFast, maSlow), title='MA cross buy', message='We have a MA buy signal!')

// Remember to use SMA 50 and SMA 200 on daily frame to get valid Golden and Death cross signals.
alertcondition(crossunder(maSlow, maTurtle), title='Death cross', message='Death cross. We have a MA slow crossing under the Turtle. Generally a strong sell signal!')
alertcondition(crossover(maSlow, maTurtle), title='Golden cross', message='Golden cross. We have a MA slow crossing over the Turtle. Generally a strong buy signal!')
 

rad14733

Well-known member
VIP
@strehsum Welcome to the usethinkscript forums... That is just a 3 MA crossover Study that probably already exists here in these forums... Please use the Search feature and do ample research prior to posting... There are very few Tradingview indicators that don't already exist for TOS... Due diligence on your part will eliminate members expending valuable time reinventing the wheel, so to speak... I understand that you are a new member but you may as well realize that we don't just code on demand or request... We are also more apt to help members who are willing to help themselves... Learning Thinkscript is more or less an expectation here... Good luck...
 

rad14733

Well-known member
VIP
@oneill Can you edit your post to include what it is you expect, an image of the original indicator, and a link to where the original code is located...??? Just posting a block of code doesn't tell us much at all... In addition, I consider it somewhat rude to think that in your first post, after joining just 4 minutes ago, that you might expect us to convert an indicator from another platform to Thinkscript... Have you even searched to see whether a comparable indicator might already exist...???

Oh, and lest I appear rude, welcome to the usethinkscript forums...
 

oneill

New member
@oneill Can you edit your post to include what it is you expect, an image of the original indicator, and a link to where the original code is located...??? Just posting a block of code doesn't tell us much at all... In addition, I consider it somewhat rude to think that in your first post, after joining just 4 minutes ago, that you might expect us to convert an indicator from another platform to Thinkscript... Have you even searched to see whether a comparable indicator might already exist...???

Oh, and lest I appear rude, welcome to the usethinkscript forums...
Hey sorry to come off rude, I had an old account and i forgot the password and it was easier to just connect to my discord account. Ill edit the post now. Ive been on the forum for some time finding indicators and never seen one similar though
 

oneill

New member
Hi all, I am not very good at coding. I will insert the code here from tradeview. Its linked here: https://www.tradingview.com/script/vkyFo1sQ/ Called Range Filter buy and sell 5min. I use it on the 15min and its pretty good. It creates red sell labels and green buy labels. Thats what i was hoping to have recreated in tos. Along with alerts when they populate. Appreciate any potential help. I've tried creating my own codes, but this ones too complex for me.
Code:
//@version=3


//Original Script > @DonovanWall

// Actual Version > @guikroth


//////////////////////////////////////////////////////////////////////////
// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
//////////////////////////////////////////////////////////////////////////


study(title="Range Filter Buy and Sell 5min", overlay=true)

// Source

src = input(defval=close, title="Source")

// Sampling Period
// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters

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

// Range Multiplier

mult = input(defval=3.0, minval=0.1, title="Range Multiplier")

// Smooth Average Range

smoothrng(x, t, m)=>
    wper      = (t*2) - 1
    avrng     = ema(abs(x - x[1]), t)
    smoothrng = ema(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

filtplot = plot(filt, color=filtcolor, linewidth=3, title="Range Filter")

// Target

hbandplot = plot(hband, color=aqua, transp=100, title="High Target")
lbandplot = plot(lband, color=fuchsia, transp=100, title="Low Target")

// Fills

fill(hbandplot, filtplot, color=aqua, title="High Target Range")
fill(lbandplot, filtplot, color=fuchsia, title="Low Target Range")

// Bar Color

barcolor(barcolor)

// Break Outs

longCond = na
shortCond = na
longCond := ((src > filt) and (src > src[1]) and (upward > 0)) or ((src > filt) and (src < src[1]) and (upward > 0))
shortCond := ((src < filt) and (src < src[1]) and (downward > 0)) or ((src < filt) and (src > src[1]) and (downward > 0))

CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1

//Alerts

plotshape(longCondition, title = "Buy Signal", text ="BUY", textcolor = white, style=shape.labelup, size = size.normal, location=location.belowbar, color = green, transp = 0)
plotshape(shortCondition, title = "Sell Signal", text ="SELL", textcolor = white, style=shape.labeldown, size = size.normal, location=location.abovebar, color = red, transp = 0)

alertcondition(longCondition, title="Buy Alert", message = "BUY")
alertcondition(longCondition, title="Buy Alert", message = "BUY")
alertcondition(longCondition, title="Buy Alert", message = "BUY")
alertcondition(shortCondition, title="Sell Alert", message = "SELL")
 
Last edited:

BenTen's Watchlist + Setup + Trade Recaps

Get access to Ben's watchlist, swing trading strategy, ThinkorSwim setup, and trade examples.

Learn more

Similar threads

Top