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!
 

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

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:

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)
 

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:



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

Maybe I just need to live with it.
 

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)
 

Volatility Trading Range

VTR is a momentum indicator that shows if a stock is overbought or oversold based on its Weekly and Monthly average volatility trading range.

Download the indicator

Similar threads

Top