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:

hoojsn

New member
Anyone could help to translate this script to TOS, this in found this in https://www.tradingview.com/script/lhda3xOg-Ord-Volume-LucF/
Code:
//@version=3
//@author=LucF
is
// Ord Volume [LucF]
// v1.1, 2019.03.24

// Shows average volume for each price wave (a Tim Ord concept).
// It's basically Weis Wave with average volume instead of cumulative volume.
// Credits to LazyBear for original Weis Wave code (a David Weis concept).

study("Ord Volume [LucF]", shorttitle="Ord Volume", precision=0)

MyGreenRaw = color(#00FF00,0),      MyGreenMedium = color(#00FF00,40),      MyGreenSemiDark = color(#00FF00,62),    MyGreenDark = color(#00FF00,75),    MyGreenDarkDark = color(#00FF00,82),    MyGreenDarkDarkDark = color(#00FF00,93)
MyRedRaw = color(#FF0000,0),        MyRedMedium = color(#FF0000,30),        MyRedSemiDark = color(#FF0000,50),      MyRedDark = color(#FF0000,75),      MyRedDarkDark = color(#FF0000,85),      MyRedDarkDarkDark = color(#FF0000,92)
MyOrangeRaw = color(#FF9800,0),     MyOrangeMedium = color(#FF9800,30),     MyOrangeSemiDark = color(#FF9800,50),   MyOrangeDark = color(#FF9800,60)
Invisible = color(white,100)

// ---------- Inputs
ColorAvg = input(true, "Distinguish rising/falling states")
ShowAvgEma = input(false, "EMA of averages")
ShowLastAvg = input(false, "Last Wave's Ending Average")
ShowLastHighestAvg = input(false, "Last Wave's Highest Average")
TrendReversalLength = input(5, "Trend reversal length")
PriceSource = input(close, "Price Source for trend detection")
LongsOnly = input(false,"Only Long Markers")
ShortsOnly = input(false,"... Or Only Short Markers")
ShowMarker1 = input(false, "Marker 1: Breach of previous wave's highest Average")

// ---------- Detect Wave
Trend = 0
Wave = 0
WaveBars = 0
CumVolume = volume

UpOrDn = PriceSource>PriceSource[1] ? 1 : PriceSource<PriceSource[1] ? -1 : 0                           // Price movement Up->1, Dn->-1, No change->0
Trend := (UpOrDn != 0) and (UpOrDn != UpOrDn[1]) ? UpOrDn : nz(Trend[1])                                // Trend changes when price reverses direction.
ReversalTrend = rising(PriceSource, TrendReversalLength) or falling(PriceSource, TrendReversalLength)   // Detect reversal condition.
Wave := (Trend != nz(Wave[1])) and ReversalTrend ? Trend : nz(Wave[1])                                  // Stay in wave until a counter trend of trendDetectionLength occurs.

// ---------- States
BullWave = Wave==1
BearWave = Wave==-1
SameWave = Wave==Wave[1]

// ---------- Build average volume for current wave.
CumVolume := SameWave ? (nz(CumVolume[1])+volume) : volume
WaveBars := SameWave ? nz(WaveBars[1])+1 : 1
AverageWaveVolume = CumVolume/WaveBars

// ---------- Keep track of last wave's ending average.
LastAvg = 0.0
LastAvg := not SameWave ? AverageWaveVolume[1] : LastAvg[1]

// ---------- Keep track of last wave's maximum average.
CurrentMaxAvg = 0.0
CurrentMaxAvg := SameWave ? max(AverageWaveVolume, nz(CurrentMaxAvg[1])) : AverageWaveVolume
// plot(CurrentMaxAvg)
LastMaxAvg = CurrentMaxAvg
LastMaxAvg := SameWave ? LastMaxAvg[1] : CurrentMaxAvg[2]

// ---------- Plots
plot( AverageWaveVolume, "Average Volume", color=BullWave? rising(AverageWaveVolume,1) and ColorAvg? MyGreenSemiDark:MyGreenDark: rising(AverageWaveVolume,1) and ColorAvg? MyRedSemiDark:MyRedDark, linewidth=1, style=area)
plot( ShowAvgEma? ema( AverageWaveVolume,20):na, "EMA of Average Volume", color=MyOrangeMedium, linewidth=1)
plot( ShowLastAvg ? LastAvg:na, "Last Wave Average", color=BullWave? red:green, linewidth=2, style=circles)
plot( ShowLastHighestAvg ? LastMaxAvg:na, "Last wave Maximum Average", color=not SameWave? Invisible: BullWave? red:green, linewidth=2, style=line)

// ---------- Markers
// Marker 1: Last wave's maximum average surpassed
M1U = ShowMarker1 and not ShortsOnly and BullWave and close>open and (crossover(AverageWaveVolume, LastMaxAvg) or (not SameWave and AverageWaveVolume>CurrentMaxAvg[1]))
M1D = ShowMarker1 and not LongsOnly and BearWave and close<open and (crossover(AverageWaveVolume, LastMaxAvg) or (not SameWave and AverageWaveVolume>CurrentMaxAvg[1]))
plotshape( M1U, "Marker 1 Up", color=MyGreenMedium, style=shape.triangleup, location=location.top, size=size.tiny, text="1")
plotshape( M1D, "Marker 1 Dn", color=MyRedMedium, style=shape.triangledown, location=location.top, size=size.tiny, text="1")

// ---------- Alert
alertcondition(M1U or M1D, title="Ord V: Configured Markers", message="OrdV Marker")
 
Last edited by a moderator:

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

Billions

Active member
2019 Donor
VIP
Can anyone help with coding this into TOS Script. Thanks
Code:
//@version=3
study(title="Market Cipher A", overlay=true)
//EMA Ribbon
ema1 = input(5)
ema2 = input(11)
ema3 = input(15)
ema4 = input(18)
ema5 = input(21)
ema6 = input(24)
ema7 = input(28)
ema8 = input(34)
ema1_ = ema(close, ema1)
ema2_ = ema(close, ema2)
ema3_ = ema(close, ema3)
ema4_ = ema(close, ema4)
ema5_ = ema(close, ema5)
ema6_ = ema(close, ema6)
ema7_ = ema(close, ema7)
ema8_ = ema(close, ema8)
plot(ema1_, color=#265aa6, linewidth=2, transp=50, title="EMA 1")
plot(ema2_, color=#265aa6, linewidth=2, transp=50, title="EMA 2")
plot(ema3_, color=#1976d2, linewidth=2, transp=50, title="EMA 3")
plot(ema4_, color=#1976d2, linewidth=2, transp=50, title="EMA 4")
plot(ema5_, color=#7fb3ff, linewidth=2, transp=50, title="EMA 5")
plot(ema6_, color=#7fb3ff, linewidth=2, transp=50, title="EMA 6")
plot(ema7_, color=#bbdefb, linewidth=2, transp=50, title="EMA 7")
plot(ema8_, color=#bbdefb, linewidth=2, transp=50, title="EMA 8")

Longema = crossover(ema2_,ema8_)
plotshape(Longema, style=shape.circle, color=green, transp=0, location=location.abovebar, size=size.tiny, title="Long EMA Signal")
Redcross = crossunder(ema1_,ema2_)
plotshape(Redcross, style=shape.xcross, color=red, transp=0, location=location.abovebar, size=size.tiny, title="Red cross")
Bluetriangle = crossover(ema2_,ema3_)
plotshape(Bluetriangle, style=shape.triangleup, color=blue, transp=0, location=location.belowbar, size=size.small, title="Blue Triangle")

//Alerts
alertcondition(Redcross != 0, "RedX", " RedX")
alertcondition(Longema != 0, "Longema", "Longema")
alertcondition(Bluetriangle!= 0, "Bluetriangle", " Bluetriangle")

//-------------------END-------------------
 
Last edited by a moderator:

tradebyday

Active member
@Nomak not sure if you felt up to it, but I had this in my archives from tradingview. I think its similar to what @thebewb has on his chart if you wish to code it over (or anyone else that feels like they may want it. Linking both the indicator and the code here for you. https://www.tradingview.com/script/l3fFpSkr-Hilbert-Sine-Wave-Support-and-Resistance/

Code:
//@version=2
study("Hilbert Sine Wave Support and Resistance", "Sine Wave SR", overlay=true)
Price = close
alpha = 0.07
Smooth = (Price+2*Price[1]+2*Price[2]+Price[3])/6
Cycle = (1-.5*alpha)*(1-.5*alpha)*(Smooth-2*Smooth[1]+Smooth[2])+2*(1-alpha)*nz(Cycle[1])-(1-alpha)*(1-alpha)*nz(Cycle[2])
Q1=(.0962*Cycle+.5769*Cycle[2]-.5769*Cycle[4]-.0962*Cycle[6])*(.5+.08*nz(InstPeriod[1]))
I1 = Cycle[3]
DeltaPhase = iff(Q1 != 0 and Q1[1]!= 0, (I1/Q1-I1[1]/Q1[1])/(1+I1*I1[1]/(Q1*Q1[1])), na)
DeltaPhase := iff(DeltaPhase < 0.1, 0.1, DeltaPhase)
DeltaPhase := iff(DeltaPhase > 1.1, 1.1, DeltaPhase)
MedianDelta = percentile_nearest_rank(DeltaPhase,5, 50)
DC = iff(MedianDelta == 0, 15, 6.28318/MedianDelta + 0.5)
InstPeriod=.33*DC+.67*nz(InstPeriod[1])
Value1 = .15*InstPeriod+.85*nz(Value1[1])
DCPeriod = floor(Value1)
RealPart = 0
ImagPart = 0
for count = 0 to DCPeriod - 1
    RealPart := RealPart + sin(6.28318 * count / DCPeriod) * (Cycle[count])
    ImagPart := ImagPart + cos(6.28318 * count / DCPeriod) * (Cycle[count])
DCPhase = iff(abs(ImagPart) > 0.001, atan(RealPart / ImagPart), na)
DCPhase := iff(abs(ImagPart) <= 0.001, 1.572963*sign(RealPart), DCPhase)
DCPhase := DCPhase + 1.572963
DCPhase := iff(ImagPart < 0, DCPhase + 3.1415926, DCPhase)
DCPhase := iff(DCPhase > 5.49778705, DCPhase - 6.28318, DCPhase)
Sine = sin(DCPhase)
LeadSine = sin(DCPhase + 0.78539815)

// Drawing Lines:
drawingsupport = nz(drawingsupport[1])
currdotvalue = nz(currdotvalue[1])
if (LeadSine[floor(DCPeriod/8)] <= Sine[floor(DCPeriod/8)] and drawingsupport == 1)
    currdotvalue := high*1.01
    drawingsupport := 0
if (LeadSine[floor(DCPeriod/8)] > Sine[floor(DCPeriod/8)] and drawingsupport == 0)
    currdotvalue := low*0.99
    drawingsupport := 1
currdotcolor = iff(drawingsupport == 0, green, red)
plot(currdotvalue, style=circles, linewidth=2, color=currdotcolor)
 

superfatkorean

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


Code:
study("Wave-PM")

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

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

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


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


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

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

Furthur

New member
Hi, I have an indicator from tradingview, I was wondering if it's possible to convert it to think script? Thanks in advance!

Code:
//@version=4
study(title="(JS) Squeeze Pro 2", shorttitle="(JS)SqzPro2", overlay=false)

//----------------------------{ Inputs }----------------------------------------

src                 = input(defval=close, title="Squeeze Input", type=input.source)
int     length      = input(20, title="Length", minval=1)
string  bbmatype    = input(defval='SMA', title='Bollinger Bands Calculation Type', options=['SMA', 'EMA', 'WMA', 'VWMA', 'RMA'])
string  kcmatype    = input(defval='SMA', title='Keltner Channel Calculation Type', options=['SMA', 'EMA', 'WMA', 'VWMA', 'RMA'])
int     color_1     = input(title="Color Format", defval=2, minval=1, maxval=6)
bool    drdiv       = input(defval=false, title="Draw Divergence")
bool    bgoff       = input(defval=false, title="Background Off")
bool    darkm       = input(defval=true, title="Gray Background for Dark Mode")
bool    zerold      = input(defval=false, title="Zero Line Dots")
bool    lowsqzwht   = input(defval=true, title="Low Squeeze White")

//Bollinger Bands Basis Line
smabb       = sma(src, length)
emabb       = ema(src, length)
wmabb       = wma(src, length)
vwmabb      = vwma(src, length)
rmabb       = rma(src, length)
basis       = bbmatype == 'SMA' ? smabb : bbmatype == 'EMA' ? emabb :
   bbmatype == 'WMA' ? wmabb : bbmatype == 'VWMA' ? vwmabb : rmabb

//Keltner Channel Basis Line
smakc       = sma(src, length)
emakc       = ema(src, length)
wmakc       = wma(src, length)
vwmakc      = vwma(src, length)
rmakc       = rma(src, length)
basiskc     = bbmatype == 'SMA' ? smakc : kcmatype == 'EMA' ? emakc :
   kcmatype == 'WMA' ? wmakc : kcmatype == 'VWMA' ? vwmakc : rmakc

// Keltner Channel Low
smakcl      = sma(tr, length)
emakcl      = ema(tr, length)
wmakcl      = wma(tr, length)
vwmakcl     = vwma(tr, length)
rmakcl      = rma(tr, length)
rangemal    = kcmatype == 'SMA' ? smakcl : kcmatype == 'EMA' ? emakcl :
   kcmatype == 'WMA' ? wmakcl : kcmatype == 'VWMA' ? vwmakcl : rmakcl
// Keltner Channel Mid
smakcm      = sma(tr, length)
emakcm      = ema(tr, length)
wmakcm      = wma(tr, length)
vwmakcm     = vwma(tr, length)
rmakcm      = rma(tr, length)
rangemam    = kcmatype == 'SMA' ? smakcm : kcmatype == 'EMA' ? emakcm :
   kcmatype == 'WMA' ? wmakcm : kcmatype == 'VWMA' ? vwmakcm : rmakcm
//Keltner Channel High
smakch      = sma(tr, length)
emakch      = ema(tr, length)
wmakch      = wma(tr, length)
vwmakch     = vwma(tr, length)
rmakch      = rma(tr, length)
rangemah    = kcmatype == 'SMA' ? smakch : kcmatype == 'EMA' ? emakch :
   kcmatype == 'WMA' ? wmakch : kcmatype == 'VWMA' ? vwmakch : rmakch

//{Instead of putting the numbers in the formula, I chose to do it this way so you could set it in actual BB or KC too}

//Bollinger Bands Multiplier
mult        = 2.0
//Keltner Channel Low Multiplier
multlowKC   = 2.0
//Keltner Channel Mid Multiplier
multmidKC   = 1.5
//Keltner Channel High Multiplier
multhighKC  = 1.0

//Bollinger Bands
dev         = mult * stdev(src, length)
upperBB     = basis + dev
lowerBB     = basis - dev
//Keltner Channel Bands Low
upperKCl    = basiskc + rangemal * multlowKC
lowerKCl    = basiskc - rangemal * multlowKC
//Keltner Channel Bands Mid
upperKCm    = basiskc + rangemam * multmidKC
lowerKCm    = basiskc - rangemam * multmidKC
//Keltner Channel Bands High
upperKCh    = basiskc + rangemah * multhighKC
lowerKCh    = basiskc - rangemah * multhighKC

//------------------------{ Squeeze Basics }------------------------------------

//Squeeze Momentum
sz          = linreg(src - avg(avg(highest(high, length), lowest(low, length)), ema(close, length)), length, 0)
//Squeeze Conditions
sc1         = sz >= 0
sc2         = sz < 0
sc3         = sz >= sz[1]
sc4         = sz < sz[1]
sc5         = sz < 1
sc6         = sz > -1
//Squeeze On
lowsqz      = lowerBB > lowerKCl and upperBB < upperKCl
lsf         = lowsqz == false
midsqz      = lowerBB > lowerKCm and upperBB < upperKCm
msf         = midsqz == false
highsqz     = lowerBB > lowerKCh and upperBB < upperKCh
hsf         = highsqz == false

//-----------------------{ Color Components }-----------------------------------

//Color Conditions
clr1        = sc1 and sc3 ? #00eeff :
   sc1 and sc4 ? #000eff : sc2 and sc4 ? #ff0000 : sc2 and sc3 ? #ffe500 : color.gray
clr2        = sc1 and sc3 ? #00bcd4 :
   sc1 and sc4 ? #0d47a1 : sc2 and sc4 ? #ba68c8 : sc2 and sc3 ? #9c27b0 : #673ab7
clr3        = sc1 and sc3 ? #15ff00 : sc1 and sc4 ? #388e3c :
   sc2 and sc4 ? #f44336 : sc2 and sc3 ? #b71c1c : color.gray
clr4        = sc1 and sc3 ? #fff59d :
   sc1 and sc4 ? #ffd600 : sc2 and sc4 ? #ffcc80 : sc2 and sc3 ? #ff9800 : #702700
clr5        = sc1 and sc3 ? #2196f3 :
   sc1 and sc4 ? #0d47a1 : sc2 and sc4 ? #ef9a9a : sc2 and sc3 ? #d32f2f : #ce93d8
clr6        = sc5 and sc1 ? #ef6c00 : sc6 and sc2 ? #ef6c00 : sc1 and sc3 ? #fff176 :
   sc1 and sc4 ? #ffd600 : sc2 and sc4 ? #ef9a9a : sc2 and sc3 ? #d32f2f : #ffb74d
choice      = color_1 == 1 ? clr1 : color_1 == 2 ? clr2 :
   color_1 == 3 ? clr3 : color_1 == 4 ? clr4 : color_1 == 5 ? clr5 : color_1 == 6 ? clr6 : na
//Background Conditions
bg1         = color.gray
bg2         = #673ab7
bg3         = color.gray
bg4         = #ffd600
bg5         = #ce93d8
bg6         = #ffb74d
bgc         = bgoff ? na : color_1 == 1 ? bg1 : color_1 == 2 ? bg2 :
   color_1 == 3 ? bg3 : color_1 == 4 ? bg4 : color_1 == 5 ? bg5 : color_1 == 6 ? bg6 : na
//Background Colors
bgcolor(color=darkm ? bgc : na, editable=false, transp=95, editable=false)
bgcolor(bgoff ? na : choice)
//Squeeze Dot Colors
sqzproc     = highsqz ? #ffe500 : midsqz ? #ff0000 : lowsqz and lowsqzwht ? color.white : lowsqz ? #000000 : na

//-----------------{ Indicator Components and Plots }---------------------------

//Squeeze Dot Plot Above and Below
sqzpro      = zerold ? na : highsqz ? highsqz : midsqz ? midsqz : lowsqz ? lowsqz : na
plotshape(sqzpro, title="Squeeze Dots Top", style=shape.circle, location=location.top, color=sqzproc)
plotshape(sqzpro, title="Squeeze Dots Bottom", style=shape.circle, location=location.bottom, color=sqzproc)

//Squeeze Dot Plot Zero Line
nozero      = lowsqzwht == false
sqzproz     = highsqz ? 0 : midsqz ? 0 : lowsqz ? 0 : na
plot(zerold ? sqzproz : na, title="Zero Line Squeeze", color=sqzproc, linewidth=5,style=plot.style_circles,transp=0)
plot(nozero ? 0 : na, title="Zero Line Squeeze", color=color.white, linewidth=1,style=plot.style_line,transp=0)

//Squeeze Plot
plot(sz, title="Squeeze Momentum", color=choice, style=plot.style_columns, linewidth=1)

//Divergence Formula {Compliments of Ricardo Santos}
ftf(_src) =>
    _src[4] < _src[2] and _src[3] < _src[2] and _src[2] > _src[1] and
       _src[2] > _src[0]
fbf(_src) =>
    _src[4] > _src[2] and _src[3] > _src[2] and _src[2] < _src[1] and
       _src[2] < _src[0]
ffract(_src) =>
    fbf__1 = fbf(_src)
    ftf(_src) ? 1 : fbf__1 ? -1 : 0
fractaltop  = ffract(sz) > 0 ? sz[2] : na
fractalbot  = ffract(sz) < 0 ? sz[2] : na
high_prev   = valuewhen(fractaltop, sz[2], 1)
high_price  = valuewhen(fractaltop, high[2], 1)
low_prev    = valuewhen(fractalbot, sz[2], 1)
low_price   = valuewhen(fractalbot, low[2], 1)
regbeardiv  = fractaltop and high[2] > high_price and sz[2] < high_prev
hidbeardiv  = fractaltop and high[2] < high_price and sz[2] > high_prev
regbulldiv  = fractalbot and low[2] < low_price and sz[2] > low_prev
hidbulldiv  = fractalbot and low[2] > low_price and sz[2] < low_prev

//Divergence Plot
plot(title='Bearish Fractal', series=drdiv ? fractaltop ? sz[2] : na : na, color=regbeardiv ? choice : na, linewidth=2, offset=-2, editable=false)
plot(title='Bullish Fractal', series=drdiv ? fractalbot ? sz[2] : na : na, color=regbulldiv ? choice : na, linewidth=2, offset=-2, editable=false)
plot(title='Bearish Divergence', series=drdiv ? fractaltop ? sz[2] : na : na, style=plot.style_circles, color=regbeardiv ? choice : na, linewidth=3, offset=-2, editable=false)
plot(title='Bullish Divergence', series=drdiv ? fractalbot ? sz[2] : na : na, style=plot.style_circles, color=regbulldiv ? choice : na, linewidth=3, offset=-2, editable=false)

//------------------------{ Alert Conditions }----------------------------------

//Dot Count Regular
ll6         = barssince(lsf) == 6
ml6         = barssince(msf) == 6
hl6         = barssince(hsf) == 6
//Dot Count Prolonged
ll12        = barssince(lsf) == 12
ml12        = barssince(msf) == 12
hl12        = barssince(hsf) == 12
//End Of Squeeze
eol         = barssince(lowsqz) == 1
eom         = barssince(midsqz) == 1
eoh         = barssince(highsqz) == 1
//Start Of Squeeze
sol         = barssince(lsf) == 1
som         = barssince(msf) == 1
soh         = barssince(hsf) == 1

//-----------------------------{ Alerts }---------------------------------------

//6th Dot Alerts
alertcondition(ll6, title="6th White Dot", message="Early Squeeze - 6th White Dot")
alertcondition(ml6, title="6th Red Dot", message="Squeeze - 6th Red Dot")
alertcondition(hl6, title="6th Yellow Dot", message="Power Squeeze - 6th Yellow Dot")
//12th Dot Alerts
alertcondition(ll12, title="12th White Dot", message="Early Squeeze - 12th White Dot")
alertcondition(ml12, title="12th Red Dot", message="Squeeze - 12th Red Dot")
alertcondition(hl12, title="12th Yellow Dot", message="Power Squeeze - 12th Yellow Dot")
//End of Squeeze Alerts
alertcondition(eol, title="White Dot - End of Squeeze", message="White Dot - End of Early Squeeze")
alertcondition(eom, title="Red Dot - End of Squeeze", message="Yellow Dot - End of Squeeze")
alertcondition(eoh, title="Yellow Dot - End of Squeeze", message="Red Dot - End of Power Squeeze")
//Start of Squeeze Alerts
alertcondition(sol, title="Early Squeeze Started", message="White Dot - Early Squeeze Started")
alertcondition(som, title="Squeeze Started", message="Red Dot - Squeeze Started")
alertcondition(soh, title="Power Squeeze Started", message="Yellow Dot - Power Squeeze Started")
//Zero Line Alerts
alertcondition(sz[1] < 0 and sz > 0, title="Zero Line Cross Bullish", message="Zero Line Cross Bullish")
alertcondition(sz[1] > 0 and sz < 0, title="Zero Line Cross Bearish", message="Zero Line Cross Bearish")
 

jack

New member
VIP
I mainly use the indicators recommended on the Swing Arm site, but I have been watching this VWAP one as well and it has been spot on. It is from Trade View. I am not a coder, but if someone would like to code it for TOS, I think you would find it very beneficial.

Thanks for considering

Code:
//@version=4
study("My VWAP Reversal + Pivot Points Standard", overlay=true)
higherTF = input("D", type=input.resolution)
prevCloseHTF = security(syminfo.tickerid, higherTF, close[1], lookahead=true)
prevOpenHTF = security(syminfo.tickerid, higherTF, open[1], lookahead=true)
prevHighHTF = security(syminfo.tickerid, higherTF, high[1], lookahead=true)
prevLowHTF = security(syminfo.tickerid, higherTF, low[1], lookahead=true)

pLevel = (prevHighHTF + prevLowHTF + prevCloseHTF) / 3
//r1Level = pLevel * 2 - prevLowHTF
//s1Level = pLevel * 2 - prevHighHTF

//var line r1Line = na
var line pLine = na
var label pLabel = na
//var line s1Line = na

var float open_price = na
var float high_price = na
var float low_price = na
var float gap_up = na

var label lHigh = na
var label lLow = na
var line PriceLine = na

if pLevel[1] != pLevel
//    line.set_x2(r1Line, bar_index)
    line.set_x2(pLine, bar_index)
//    line.set_x2(s1Line, bar_index)
//    line.set_extend(r1Line, extend.none)
    line.set_extend(pLine, extend.none)
//    line.set_extend(s1Line, extend.none)
//    r1Line := line.new(bar_index, r1Level, bar_index, r1Level, extend=extend.right)
    pLine := line.new(bar_index, pLevel, bar_index, pLevel, color=color.orange, width=3, extend=extend.right)
//    s1Line := line.new(bar_index, s1Level, bar_index, s1Level, extend=extend.right)
//    label.new(bar_index, r1Level, "R1", style=label.style_none)
    pLabel := label.new(bar_index, pLevel, "P", style=label.style_none)
//    label.new(bar_index, s1Level, "S1", style=label.style_none)
    label.delete(pLabel[1])
    line.delete(pLine[1])
    open_price := open
    high_price := high
    low_price := low
    gap_up := open > close [1] ? 1 : 0
    lLow := label.new(bar_index, low, tostring(low), style=label.style_label_up, yloc=yloc.belowbar, color=color.red)
    label.delete(lLow[1])
    lHigh := label.new(bar_index, high, tostring(high), style=label.style_label_down, yloc=yloc.abovebar, color=color.lime)
    label.delete(lHigh[1])
    label.delete(gap_up ? lHigh : lLow)
    PriceLine := line.new(bar_index, gap_up ? low_price : high_price, bar_index, gap_up ? low_price : high_price, color=gap_up ? color.red : color.black, style=line.style_dashed, width=2, extend=extend.right)
    line.delete(PriceLine[1])

if not na(pLine) and line.get_x2(pLine) != bar_index
//    line.set_x2(r1Line, bar_index)
    line.set_x2(pLine, bar_index)
    line.set_x2(PriceLine, bar_index)
//    line.set_x2(s1Line, bar_index)
// END
 

Marcel77

New member
VIP
Hello Traders,

I'm looking for some advise. I'm trying to convert two (great) indicators I have on Tradingview so I can use those on my TOS platform. I'm just not a big tradingview fan and it's kind of annoying having two applications open all the time.

Does anyone know if such a conversion is even possible?

Thank you in advance.
 

Marcel77

New member
VIP
Thank you very much for your reply. Hope someone can help me out (I really need to get my head around the coding in TOS).

Here is the indicator:

Code:
study(title="On Balance Volume X", shorttitle="OBVX")

fastLen = input(7)
slowLen = input(20)

src = close
obv = cum(change(src) > 0 ? volume : change(src) < 0 ? -volume : 0*volume)
plot(obv, color=lime, title="OBV")

fast = sma(obv, fastLen)
slow = sma(obv, slowLen)
plot(fast, color=white)
plot(slow, color=red)

backgroundColour = iff((obv > fast), iff((fast > slow), lime, green), iff((fast > slow), orange, red))

bgcolor(color=backgroundColour, transp=85)
 

Marcel77

New member
VIP
They are very similar but I was hoping to somehow convert my two favorite indicators to have them available on TOS. Here is my setup on on Tradingview:

403DUgW.png


On top I have the super trend. The lower ares are the OBVX and OBV delta.

Maybe I just need to live with it.
 

TETRIZ

New member
I am working on my first script to convert a tradingview indicator. As a beginner, I have trouble understanding thinkscript. Appreciate your help.

Trading view script: https://www.tradingview.com/script/fE4pYynE-Market-Mode/

This as close as I can get as a beginner after burning multiple days. The plotting is good enough. I have tested multiple tickers manually. However, the values are skewed by .1

Appreciate if one of the experts can extend the hand with big heart in fixing the skewed numbers. I am expecting the correction is needed in fold statement or compound value usage.

The script in Conversion:

Code:
#version = 0.1
#credits: https://www.tradingview.com/script/fE4pYynE-Market-Mode/
#Ehler’s description of the method and indicator:
#There just has to be a better way to determine whether the market is in a cycle mode or trend mode other than #gazing at squiggly lines on your computer screen.
#One approach is to compare the peak swings of the cycle mode to the amplitude of the trend mode.
#We do this by capturing the peaks and averaging these peaks in a relatively long moving average. #Correspondingly, one can capture the valleys and also average the valleys in a relatively long moving average. #We then take a fraction of these averages as the thresholds between a trend mode and a cycle mode. If the trend #is above the upper threshold the
#market is in an uptrend. If the trend is below the lower threshold the market is in a downtrend. When the trend #falls between the two threshold levels the market is in a cycle mode.
#The setting of the fraction of the averaged peaks and valleys to be used to establish the thresholds is somewhat #subjective and can be adjusted to fit your trading style. Personally, we prefer to trade in the cycle mode and #therefore tend to set the thresholds relatively far apart.
#In this way one can stop swing trading when the market is clearly in a trend.
declare lower;
input MMPeriod = 20;# "Market mode period"
input Delta = 0.5; # "Delta"
input Fraction = 0.8; # "Fraction"
input LevelUpAveragePeriod = 10; # "Level up average period"
input LevelDownAveragePeriod = 10; # "Level down average period"

def Price = (high + low) / 2;
def MPI = Double.Pi;#3.1415926535897;
def bar_index = BarNumber();
def calc = 2.0 * MPI / MMPeriod;
def beta = Cos(calc / (2 * MPI) * 360);
def calc2 = 4.0 * MPI * Delta / MMPeriod;
def gamma   = 1.0 / Cos(calc2 / (4.0 * MPI * Delta) * 360);
def alpha   = gamma - Sqrt(gamma * gamma - 1.0);
def alphaUp = 2.0 / (1.0 + LevelUpAveragePeriod);
def alphaDn = 2.0 / (1.0 + LevelDownAveragePeriod);
def dPeriod = 2 * MMPeriod;


#coulld be something worng in using Compondvalue or fold statement
# original script
#if bar_index>MMPeriod
 #   workbp := 0.5*(1.0-alpha)*(Price-Price[2])+beta*(1.0+alpha)*workbp[1]-alpha*workbp[2]
  #    mean = mean+workbp[k]
   #     inc:=k
   # mean := mean/inc
   # workapeak := workapeak[1]
   # if mean>0
    #    workapeak:=workapeak[1]+alphaUp*(mean-workapeak[1])
    #workavaley:=workavaley[1]
    #if mean<0
     #   workavaley:=workavaley[1]+alphaDn*(mean-workavaley[1])
    #fractionUp := Fraction*workapeak
    #fractionDn := Fraction*workavaley

def workbp  = 0.5 * (1.0 - alpha) * (Price - Price[2]) + beta * (1.0 + alpha) * workbp[1] - alpha * workbp[2];

def mean = (fold i = 0 to dPeriod-1 with p = workbp
        do CompoundValue(40, workbp[i], workbp)) / dPeriod ;

def workapeak = if mean > 0 then workapeak[1] + alphaUp * (mean - workapeak[1]) else workapeak[1];

def workavaley = if mean < 0 then workavaley[1] + alphaDn * (mean - workavaley[1]) else workavaley[1];

def fractionUp = Fraction * workapeak;
def fractionDn = Fraction * workavaley;

plot meanp = mean;
meanp.SetPaintingStrategy(PaintingStrategy.LINE);
meanp.AssignValueColor(if (mean > fractionUp) then Color.DARK_GREEN else if (mean < fractionDn ) then Color.DARK_RED else Color.WHITE);
meanp.SetLineWeight(2);

plot fupP = fractionUp ;
fupP.AssignValueColor(CreateColor(157,9,173));
plot fdnP = fractionDn ;
fdnP.AssignValueColor(CreateColor(157,9,173));
def buy = crosses(mean,  fractionUp, CrossingDirection.ABOVE);
def sell = crosses(mean, fractionDn, CrossingDirection.BELOW);

plot buyP = if buy then fractionup else Double.NaN;
buyp.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
buyp.AssignValueColor(COlor.LIME);

plot sellP = if sell then fractionDn else Double.NaN;
sellP.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
sellP.AssignValueColor(COlor.LIGHT_ORANGE);
 
Last edited:

FOTM_8888

Member
VIP
Here is the Trading View Script!

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

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

study("Optimized Trend Tracker","OTT", overlay=true)
src = input(close, title="Source")
pds=input(2, "OTT Period", minval=1)
percent=input(1.4, "OTT Percent", type=input.float, step=0.1, minval=0)
showsupport = input(title="Show Support Line?", type=input.bool, defval=false)
showsignalsk = input(title="Show Support Line Crossing Signals?", type=input.bool, defval=false)
showsignalsc = input(title="Show Price/OTT Crossing Signals?", type=input.bool, defval=false)
highlight = input(title="Show OTT Color Changes?", type=input.bool, defval=false)
showsignalsr = input(title="Show OTT Color Change Signals?", type=input.bool, defval=false)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=false)
alpha=2/(pds+1)
ud1=src>src[1] ? src-src[1] : 0
dd1=src<src[1] ? src[1]-src : 0
UD=sum(ud1,9)
DD=sum(dd1,9)
CMO=nz((UD-DD)/(UD+DD))
k= abs(CMO)
Var=0.0
Var:=nz(alpha*k*src)+(1-alpha*k)*nz(Var[1])
fark=Var*percent*0.01
longStop = Var - fark
longStopPrev = nz(longStop[1], longStop)
longStop := Var > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop =  Var + fark
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := Var < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and Var > shortStopPrev ? 1 : dir == 1 and Var < longStopPrev ? -1 : dir
MT = dir==1 ? longStop: shortStop
OTT=Var>MT ? MT*(200+percent)/200 : MT*(200-percent)/200
plot(showsupport ? Var : na, color=#0585E1, linewidth=2, title="Support Line")
OTTC = highlight ? OTT[2] > OTT[3] ? color.green : color.red : #B800D9
pALL=plot(nz(OTT[2]), color=OTTC, linewidth=2, title="OTT", transp=0)
alertcondition(cross(OTT[2], OTT[3]), title="Color ALARM", message="OTT Has Changed Color!")
alertcondition(crossover(OTT[2], OTT[3]), title="GREEN ALERT", message="OTT GREEN BUY SIGNAL!")
alertcondition(crossunder(OTT[2], OTT[3]), title="RED ALERT", message="OTT RED SELL SIGNAL!")
alertcondition(cross(Var, OTT[2]), title="Cross Alert", message="OTT - Support Line Crossing!")
alertcondition(crossover(Var, OTT[2]), title="Crossover Alarm", message="Support Line BUY SIGNAL!")
alertcondition(crossunder(Var, OTT[2]), title="Crossunder Alarm", message="Support Line SELL SIGNAL!")
alertcondition(cross(src, OTT[2]), title="Price Cross Alert", message="OTT - Price Crossing!")
alertcondition(crossover(src, OTT[2]), title="Price Crossover Alarm", message="PRICE OVER OTT - BUY SIGNAL!")
alertcondition(crossunder(src, OTT[2]), title="Price Crossunder Alarm", message="PRICE UNDER OTT - SELL SIGNAL!")
buySignalk = crossover(Var, OTT[2])
plotshape(buySignalk and showsignalsk ? OTT*0.995 : na, title="BUY", text="BUY", location=location.absolute, style=shape.labelup, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
sellSignallk = crossunder(Var, OTT[2])
plotshape(sellSignallk and showsignalsk ? OTT*1.005 : na, title="SELL", text="SELL", location=location.absolute, style=shape.labeldown, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
buySignalc = crossover(src, OTT[2])
plotshape(buySignalc and showsignalsc ? OTT*0.995 : na, title="BUY", text="BUY", location=location.absolute, style=shape.labelup, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
sellSignallc = crossunder(src, OTT[2])
plotshape(sellSignallc and showsignalsc ? OTT*1.005 : na, title="SELL", text="SELL", location=location.absolute, style=shape.labeldown, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0,display=display.none)
longFillColor = highlighting ? (Var>OTT ? color.green : na) : na
shortFillColor = highlighting ? (Var<OTT ? color.red : na) : na
fill(mPlot, pALL, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, pALL, title="DownTrend Highligter", color=shortFillColor)
buySignalr = crossover(OTT[2], OTT[3])
plotshape(buySignalr and showsignalsr ? OTT*0.995 : na, title="BUY", text="BUY", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
sellSignallr = crossunder(OTT[2], OTT[3])
plotshape(sellSignallr and showsignalsr ? OTT*1.005 : na, title="SELL", text="SELL", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
 
Last edited by a moderator:

FOTM_8888

Member
VIP
post a link to it
here is.. is call break out trend follower.

Code:
//@version=4

// Revision:        1
// Author:          @millerrh
// Strategy:  Enter long when recent swing high breaks out, using recent swing low as stop level.  Move stops up as higher lows print to act
// as trailing stops.  Ride trend as long as it is there and the higher lows aren't breached. 
// Conditions/Variables
//    1. Can place a user-defined percentage below swing low and swing high to use as a buffer for your stop to help avoid stop hunts
//    2. Can add a filter to only take setups that are above a user-defined moving average (helps avoid trading counter trend)
//    3. Manually configure which dates to back test
//    4. Color background of backtested dates - allows for easier measuring buy & hold return of time periods that don't go up to current date   


// === CALL STRATEGY/STUDY, PROGRAMATICALLY ENTER STRATEGY PARAMETERS HERE SO YOU DON'T HAVE TO CHANGE THEM EVERY TIME YOU RUN A TEST ===
// (STRATEGY ONLY) - Comment out srategy() when in a study()
//strategy("Breakout Trend Follower", overlay=true, initial_capital=10000, currency='USD',
//   default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
// (STUDY ONLY) - Comment out study() when in a strategy()
study("Breakout Trend Follower", overlay=true)

// === BACKTEST RANGE ===
From_Year  = input(defval = 2019, title = "From Year")
From_Month = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
From_Day   = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
To_Year    = input(defval = 9999, title = "To Year")
To_Month   = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
To_Day     = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
Start  = timestamp(From_Year, From_Month, From_Day, 00, 00)  // backtest start window
Finish = timestamp(To_Year, To_Month, To_Day, 23, 59)        // backtest finish window

// A switch to control background coloring of the test period - Use for easy visualization of backtest range and manual calculation of
// buy and hold (via measurement) if doing prior periods since value in Strategy Tester extends to current date by default
testPeriodBackground = input(title="Color Background - Test Period?", type=input.bool, defval=false)
testPeriodBackgroundColor = testPeriodBackground and (time >= Start) and (time <= Finish) ? #00FF00 : na
bgcolor(testPeriodBackgroundColor, transp=95)

// == FILTERING ==
// Inputs
useMaFilter = input(title = "Use MA for Filtering?", type = input.bool, defval = false)
maType = input(defval="SMA", options=["EMA", "SMA"], title = "MA Type For Filtering")
maLength   = input(defval = 200, title = "MA Period for Filtering", minval = 1)

// Declare function to be able to swap out EMA/SMA
ma(maType, src, length) =>
    maType == "EMA" ? ema(src, length) : sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc)
maFilter = ma(maType, close, maLength)
plot(maFilter, title = "Trend Filter MA", color = color.green, linewidth = 3, style = plot.style_line, transp = 50)

// Check to see if the useMaFilter check box is checked, this then inputs this conditional "maFilterCheck" variable into the strategy entry
maFilterCheck = if useMaFilter == true
    maFilter
else
    0

// === PLOT SWING HIGH/LOW AND MOST RECENT LOW TO USE AS STOP LOSS EXIT POINT ===
// Inputs
//pvtLenL       = input(3, minval=1, title="Pivot Length Left Hand Side") //use if you want to change this to an input
//pvtLenR       = input(3, minval=1, title="Pivot Length Right Hand Side") //use if you want to change this to an input
pvtLenL       = 3
pvtLenR       = 3

// Get High and Low Pivot Points
pvthi_ = pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = pivotlow(low, pvtLenL, pvtLenR)

// Force Pivot completion before plotting.
Shunt = 1 //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLen = 0 //Maximum Extension Length
pvthi = pvthi_[Shunt]
pvtlo = pvtlo_[Shunt]

// Count How many candles for current Pivot Level, If new reset.
counthi = barssince(not na(pvthi))
countlo = barssince(not na(pvtlo))

pvthis = fixnan(pvthi)
pvtlos = fixnan(pvtlo)
hipc = change(pvthis) != 0 ? na : color.maroon
lopc = change(pvtlos) != 0 ? na : color.green

// Display Pivot lines
plot((maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, transp=0, linewidth=1, offset=-pvtLenR-Shunt, title="Top Levels")
plot((maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, transp=0, linewidth=1, offset=-pvtLenR-Shunt, title="Bottom Levels")
plot((maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, transp=0, linewidth=1, offset=0, title="Top Levels 2")
plot((maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, transp=0, linewidth=1, offset=0, title="Bottom Levels 2")

// Stop Levels
stopBuff = input(0.0, minval=-2, title="Stop Loss Buffer off Swing Low (%)")
stopPerc = stopBuff*.01 // Turn stop buffer input into a percentage
stopLevel = valuewhen(pvtlo_, low[pvtLenR], 0) //Stop Level at Swing Low
stopLevel2 = stopLevel - stopLevel*stopPerc  // Stop Level with user-defined buffer to avoid stop hunts and give breathing room
plot(stopLevel2, style=plot.style_line, color=color.orange, show_last=1, linewidth=1, transp=50, trackprice=true)
buyLevel = valuewhen(pvthi_, high[pvtLenR], 0) //Buy level at Swing High
buyLevel2 = buyLevel + buyLevel*stopPerc // Buy-stop level with user-defined buffer to avoid stop hunts and give breathing room
plot(buyLevel2, style=plot.style_line, color=color.aqua, show_last=1, linewidth=1, transp=50, trackprice=true)

// Conditions for entry and exit
buySignal = high > buyLevel2
buy = buySignal and time > Start and time < Finish and buyLevel2 > maFilterCheck // All these conditions need to be met to buy
sellSignal = low < stopLevel2 // Code to act like a stop-loss for the Study

// (STRATEGY ONLY) Comment out for Study
// strategy.entry("Long", strategy.long, stop = buyLevel2, when = time > Start and time < Finish and buyLevel2 > maFilterCheck)
// strategy.exit("Exit Long", from_entry = "Long", stop=stopLevel2)

// == (STUDY ONLY) Comment out for Strategy ==
// Check if in position or not
inPosition = bool(na)
inPosition := buy[1] ? true : sellSignal[1] ? false : inPosition[1]
flat = bool(na)
flat := not inPosition
buyStudy = buy and flat
sellStudy = sellSignal and inPosition
//Plot indicators on chart and set up alerts for Study
plotshape(buyStudy, style = shape.triangleup, location = location.belowbar, color = #1E90FF, text = "Buy")
plotshape(sellStudy, style = shape.triangledown, location = location.abovebar, color = #EE82EE, text = "Sell")
alertcondition(buyStudy, title='Breakout Trend Follower Buy', message='Breakout Trend Follower Buy')
alertcondition(sellStudy, title='Breakout Trend Follower Sell', message='Breakout Trend Follower Sell')

// Color background when trade active (for easier visual on what charts are OK to enter on)
tradeBackground = input(title="Color Background for Trades?", type=input.bool, defval=true)
tradeBackgroundColor = tradeBackground and inPosition ? #00FF00 : na
bgcolor(tradeBackgroundColor, transp=95)
noTradeBackgroundColor = tradeBackground and flat ? #FF0000 : na
bgcolor(noTradeBackgroundColor, transp=90)
 

New Indicator: Buy the Dip

Check out our Buy the Dip indicator and see how it can help you find profitable swing trading ideas. Scanner, watchlist columns, and add-ons are included.

Download the indicator

Similar threads

Top