Convert Tradingview indicator

J007RMC

J007RMC

Well-known member
2019 Donor
VIP
I am wondering if someone can bring this indicator into TOS is a zig-zag high lo my understanding is these zig-zags do not repaint and I've not seen this yet.


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

//@version=4
//@author=lucemanb

//
//       THIS CODE IS BASED FROM THE MT4 ZIGZAG INDICATOR
//       THE ZIGZAG SETTINGS FOR THE MAIN ONE ON TRADINGVIEW DO NOT WORK THE SAME AS MT4
//       I HOPE U LOVE IT
//

// Ping me for donations, Collaborations or Support


////////
// Seek Menu
study("ZigZag++", "ZigZag++ Lucem Anb", true, format.price)


////////
// Fetch Ingredients
Depth       = input(12, "Depth", input.integer, minval=1, step=1)
Deviation   = input(5, "Deviation", input.integer, minval=1, step=1)
mtf_val     = input("", "Resolution", input.resolution)
line_thick  = input(4, "Line Thickness", input.integer, minval=1, maxval=4)
p           = input("Lime", "Up Color", options=["Red", "Lime", "Orange", "Teal", "Yellow", "White", "Black"])
q           = input("Red", "Down Color", options=["Red", "Lime", "Orange", "Teal", "Yellow", "White", "Black"])
display_a   = input(true, "Display Background Direction Changes?")
labels      = input(true, "Display High/Low Labels")
repaint     = input(false, "Repaint Levels")


////////
// Declare Spices
var lastlow = 0.0
var lasthigh = 0.0
data(x) => security(syminfo.tickerid, mtf_val!="" ? mtf_val : timeframe.period, x)
cc(x) => x=="Red"?color.red:x=="Lime"?color.lime:x=="Orange"?color.orange:x=="Teal"?
color.teal:x=="Yellow"?color.yellow:x=="Black"?color.black:color.white
col(c) => c>0 ? (cc(p)) : c<0 ? (cc(q)) : na


////////
// Prepare Kitchen
getLow(x, y, z, a) =>
    ll = y
    v = data(x)
    m = v==ll or data(z) - v > a*syminfo.mintick
    if v!=ll
        ll := v
    if m
        v := 0.0
    [v,ll]
getHigh(x, y, z, a) =>
    lh = y
    v = data(x)
    m = v==lh or v - data(z) > a*syminfo.mintick
    if v!=lh
        lh := v
    if m
        v := 0.0
    [v,lh]
  

////////
// Cook
[v,e] = getLow(lowest(Depth), lastlow, low, Deviation)
lastlow := e
zBB =  v != 0.0
[v1,e1] = getHigh(highest(Depth), lasthigh, high, Deviation)
lasthigh := e1
zSS = v1 != 0.0
d = 0, zigzagHigh = 0, zigzagLow = 0, zigzagHighP = 0, zigzagLowP = 0
zigzagLowP := nz(zigzagLowP[1]) + 1
zigzagHighP := nz(zigzagHighP[1]) + 1
d := zBB ? 1 : zSS ? -1 : nz(d[1], 0)
virtualLow = zigzagLow[1] + 1
if not zBB or (zBB and d == d[1] and low > low[virtualLow])
    zigzagLow := nz(zigzagLow[1]) + 1
virtualHigh = zigzagHigh[1] + 1
if not zSS or (zSS and d == d[1] and high < high[virtualHigh])
    zigzagHigh := nz(zigzagHigh[1]) + 1
direction_changed = d!=d[1]


////////
// Prepare table
x1 = bar_index-zigzagLow
x2 = bar_index-zigzagHigh
y1 = low[zigzagLow]
y2 = high[zigzagHigh]
lows = zigzagLow < zigzagHigh


////////
// Serve Guests
if not repaint and d!=d[1]
    line zigzag = line.new(x1[1], y1[1], x2[1], y2[1], color=col(d[1]*-1), style=line.style_solid, width=line_thick)
    level = lows ? (high[zigzagHighP] > high[zigzagHigh] ? "LH" : "HH") : (low[zigzagLowP] < low[zigzagLow] ? "HL" : "LL")
    label tips = label.new( lows ? x2[1] : x1[1], lows ? y2[1] : y1[1], level, xloc.bar_index, yloc.price, col(d*-1), lows ? label.style_label_down : label.style_label_up, tooltip=tostring(lows?high[zigzagHigh]:low[zigzagLow]))
    if not labels
        label.delete(tips)
    if zigzagHigh==0 and zigzagLow==0
        if d > 0
            line.set_x2(zigzag, bar_index)
            line.set_y2(zigzag, high)
            label.set_x(tips, bar_index)
            label.set_y(tips, high)
            label.set_style(tips, label.style_label_down)
            label.set_text(tips, high[zigzagHighP] > high[zigzagHigh] ? "LH" : "HH")
            label.set_tooltip(tips, tostring(high))
        else
            line.set_x1(zigzag, bar_index)
            line.set_y1(zigzag, low)
            label.set_x(tips, bar_index)
            label.set_y(tips, low)
            label.set_text(tips, low[zigzagLowP]<low ? "HL" : "LL")
            label.set_tooltip(tips, tostring(low))
    if d>0
        zigzagHighP := zigzagHigh
    if d<0
        zigzagLowP := zigzagLow


////////
// Serve Others
if repaint
    line zigzag = line.new(x1, y1, x2, y2, color=col(d*-1), style=line.style_solid, width=line_thick)
    level = lows ? (low[zigzagLowP] < high[zigzagLow] ? "HL" : "LL") : (high[zigzagHighP] > high[zigzagHigh] ? "LH" : "HH")
    label tips = label.new(lows ? x1[1] : x2[1], lows ? y1[1] : y2[1], level, xloc.bar_index, yloc.price, col(d*-1), lows ? label.style_label_up : label.style_label_down, tooltip=tostring(lows?low[zigzagLow]:high[zigzagHigh]))
    if not labels
        label.delete(tips)
    if zigzagHigh==0 and zigzagLow==0
        if d > 0
            line.set_x2(zigzag[1], bar_index)
            line.set_y2(zigzag[1], high)
            label.set_x(tips[1], bar_index)
            label.set_y(tips[1], high)
            label.set_style(tips[1], label.style_label_down)
            label.set_text(tips[1], high[zigzagHighP] > high ? "LH" : "HH")
            label.set_tooltip(tips[1], tostring(high))
        else
            line.set_x1(zigzag[1], bar_index)
            line.set_y1(zigzag[1], low)
            label.set_x(tips[1], bar_index)
            label.set_y(tips[1], low)
            label.set_text(tips[1], low[zigzagLowP] < low ? "HL" : "LL")
            label.set_tooltip(tips[1], tostring(low))
    if d == d[1]
        line.delete(zigzag[1])
        label.delete(tips[1])
    if d != d[1]
        if d>0
            zigzagHighP := zigzagHigh
        if d<0
            zigzagLowP := zigzagLow


////////
// Declare meal was tasteful!
bgcolor(display_a ? col(-d) : na, editable=false, title="Direction Changes")
alertcondition(direction_changed, "Direction Changed", 'Zigzag on {{ticker}} direction changed at {{time}}')
alertcondition(direction_changed and d<0, "Bullish Direction", 'Zigzag on {{ticker}} bullish direction at {{time}}')
alertcondition(direction_changed and d>0, "Bearish Direction", 'Zigzag on {{ticker}} bearish direction at {{time}}')
 
Last edited:
X

xcmsx

New member
2019 Donor
VIP
Can anyone convert this script to thinkorswim scanner?

greatly appreciated

Code:
strategy("Director BB Filter Strat", overlay=true, pyramiding=1, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0)
strat_dir_input = input(title="Strategy Direction", defval="long", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
strategy.risk.allow_entry_in(strat_dir_value)
//////////////////////////////////////////////////////////////////////
// Testing Start dates
testStartYear = input(2016, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
//Stop date if you want to use a specific range of dates
testStopYear = input(2030, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(30, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)


testPeriod() =>
    time >= testPeriodStart and time <= testPeriodStop ? true : false



src         = input(close, title = "Source")
source = input(close, title="Source")
typeofMA1 = input(title="Type of Moving Average", defval="EMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "TMA", "HullMA", "DEMA", "TEMA", "VWAP"])
length = input(55, title = "Length of Moving Average 1", type=input.integer)


f_smma(src, len) =>
    smma = 0.0
    smma := na(smma[1]) ? sma(src, len) : (smma[1] * (len - 1) + src) / len
    smma

f_hullma(src, length) =>
    wma(2 * wma(src, length / 2) - wma(src, length), round(sqrt(length)))

f_tma(src, length) =>
    sma(sma(src, length), length)

f_dema(src, length) =>
    emaValue = ema(src, length)
    2 * emaValue - ema(emaValue, length)

f_tema(src, length) =>
    ema1 = ema(src, length)
    ema2 = ema(ema1, length)
    ema3 = ema(ema2, length)
    (3 * ema1) - (3 * ema2) + ema3

f_ma(smoothing, src, length) =>

    iff(smoothing == "RMA",    rma(src, length),
     iff(smoothing == "SMA",    sma(src, length),
     iff(smoothing == "EMA",    ema(src, length),
     iff(smoothing == "WMA",    wma(src, length),
     iff(smoothing == "VWMA",   vwma(src, length),
     iff(smoothing == "SMMA",   f_smma(src, length),
     iff(smoothing == "HullMA", f_hullma(src, length),
     iff(smoothing == "VWAP",   vwap(hlc3),
     iff(smoothing == "DEMA",   f_dema(src, length),
     iff(smoothing == "TEMA",   f_tema(src, length), src))))))))))

basis = f_ma(typeofMA1, source, length)


plot_ma1 = plot(basis, color=color.new(color.green, 0), linewidth=3, title = "MA1")


mult        = input(1., minval=0.236, maxval=10, title="Standard Deviation")//2 for Classic Bollinger Bands //Maxval = 2 as higher the deviation, higher the risk
dev         = mult * stdev(src,length)
CC          = input(true, "Color Bars")


upper       = basis + dev
lower       = basis - dev

//Conditions for Long and Short - Extra filter condition can be used such as RSI or CCI etc.

short       = src<lower// and rsi(close,14)<40
long        = src>upper// and rsi(close,14)>60

L1          = barssince(long)
S1          = barssince(short)

longSignal  = L1<S1  and testPeriod() and not (L1<S1)[1]
shortSignal = S1<L1  and testPeriod() and not (S1<L1)[1]

if (longSignal)
    strategy.entry("buy", strategy.long)
if shortSignal
    strategy.entry("sell", strategy.short)
 
M

MasterRay

New member
UPDATE ( This is very similar to SuperTrend but it fires signals at different times.)

I looked around the forum to see if I could find anything that resembled this indicator from TradingView. Does anyone know if there has been a conversion on this to TOS or if it's possible?
Thanks so much

study(title="SMA 9/50/180 | EMA 20 | BUY/SELL", overlay=true)

Code:
//SMA and EMA code
smaInput1 = input(9, title="SMA1")
smaInput2 = input(50, title="SMA2")
smaInput3 = input(180, title="SMA3")
emaInput1 = input(20, title="EMA1")
sma1 = sma(close, smaInput1)
sma2 = sma(close, smaInput2)
sma3 = sma(close, smaInput3)
EMA1 = ema(close, emaInput1)
plot(sma1, color= color.red , title="SMA1")
plot(sma2, color = color.blue, title="SMA2")
plot(sma3, color= color.white, title="SMA3")
plot(EMA1, color = color.yellow, title="EMA1")

//@version=4
no=input(3,title="BUY/SELL Swing")
Barcolor=input(false,title="BUY/SELL Bar Color")
Bgcolor=input(false,title="BUY/SELL Background Color")
res=highest(high,no)
sup=lowest(low,no)
avd=iff(close>res[1],1,iff(close<sup[1],-1,0))
avn=valuewhen(avd!=0,avd,0)
tsl=iff(avn==1,sup,res)
Buy=crossover(close,tsl)
Sell=crossunder(close,tsl)
plotshape(Buy,title="Buy", color=color.green, style=shape.arrowup,location=location.belowbar, text="Buy")
plotshape(Sell,title="Sell", color=color.red, style=shape.arrowdown,text="Sell")
colr = close>=tsl ? color.green : close<=tsl ? color.red : na
plot(tsl, color=colr, linewidth=3, title="BUY/SELL Chart Line")
barcolor(Barcolor ? colr : na)
bgcolor(Bgcolor ? colr :na)
alertcondition(Buy, title="Buy Signal", message="Buy")
alertcondition(Sell, title="Sell Signal", message="Sell")
 
Last edited:
H

harry29191

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.
this indicator available for TOS?
 
O

oliverwu90

New member
hi guys,
I tried to replicate the code below(using Trading View).
After my research, I haven't found anything that is close to this.
Just want to show 20, 60, 120 days closed price on these days
I thought it could be simple but I'm wrong.

can anyone gives me one direction or have a script like this.
would much be appreciated.

This is how it looks like using on Trading View. I hope to transition to Thinkorswim



Code:
study("Deduction",overlay=true)
x = input(20)
y = input(60)
z = input(120)

close1 = close[x]
close2 = close[y]
close3 = close[z]
// plot(close1,color=color.orange,trackprice=true,transp=100,title='Title')
// plot(close2,color=color.blue,trackprice=true,transp=100,title='Title')
// plot(close3,color=color.navy,trackprice=true,transp=100,title='Title')

l = label.new(bar_index-x, na, tostring(x)+'MA '+tostring(close[x]),
  color=color.orange,
  textcolor=color.white,
  style=close[x] > open[x] ? label.style_labeldown : label.style_labelup,
  yloc=close[x] > open[x] ? yloc.abovebar : yloc.belowbar
  )
label.delete(l[1])

l2 = label.new(bar_index-y, na, tostring( y)+'MA '+tostring(close[y]),
  color=color.blue,
  textcolor=color.white,
   style=close[y] > open[y] ? label.style_labeldown : label.style_labelup,
  yloc=close[y] > open[y] ? yloc.abovebar : yloc.belowbar
  )
label.delete(l2[1])

l3 = label.new(bar_index-z, na, tostring(z) +'MA '+tostring(close[z]),
  color=color.navy,
  textcolor=color.white,
  style=close[z] > open[z] ? label.style_labeldown : label.style_labelup,
  yloc=close[z] > open[z] ? yloc.abovebar : yloc.belowbar
  )
label.delete(l3[1])
 
H

Hector Alzate

New member
VIP
Hi Ben Ten, TraderZen's request to switch Consider converting this indicator from TV to TOS, https://tr.tradingview.com/script/sU9molfV/ This is called Profit Maximizer PMAX.
According to the answer you give to the TraderZen user is that the change requested by him has already been made at the bottom, I download said study to the cough platform and I get everything in red with error and I will not have said study, you can help me what a mistake I can have, thanks Ben Ten
 
tg703

tg703

New member
Hi, I'm in search of a script that builds pivots based on VWAP high/low values instead of price high/low values. Optimally it would include Classic and Fib versions out to R5/S5, across day/week/month timeframes.

Here's the only example of a Tradingview version I could find, it's proven to be very accurate in my use so far:
https://www.tradingview.com/script/6uviIKSP-VWAP-Pivots-Classic-Camarilla-Woodie/

Anyone heard of anything like this, or could code it? I'm not quite proficient or familiar enough with thinkScript to piece it together. And to clarify - I don't necessarily want the above script converted exactly as is, since there's a lot of extra stuff in there. Just a simpler version with Classic+Fib pivots using the VWAP values.
 
Last edited:
BenTen

BenTen

Administrative
Staff
VIP
@usa10

The source code of this study is protected. You can add it to your favorites and use it, but you cannot view or modify the script.
 
L

lindosskier

Member
Hi everyone. Is there any way to convert the "Balance of Market Power 14" from Trading View, into a TOS indicator? Thank you.
 
I

Investingtogive

New member
VIP
Does anyone know how to convert Trading View code to TOS ? This is the Trading View code for the SuperTrend ATR - RSI.

Code:
study(title = "SuperTrend ATR + RSI", shorttitle = "SuperTrend ATR + RSI", overlay = true)

//Mode
Factor=input(title="Super Trend", defval=3, minval=1,maxval = 100)
ATR=input(title="ATR", defval=7, minval=1,maxval = 100)
RSI = input(title="RSI", defval=7, minval=1, maxval = 100)

//Super Trend ATR
Up=hl2-(Factor*atr(ATR))
Dn=hl2+(Factor*atr(ATR))

TUp=close[1]>TUp[1]? max(Up,TUp[1]) : Up
TDown=close[1]<TDown[1]? min(Dn,TDown[1]) : Dn

Trend = close > TDown[1] ? 1: close< TUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TUp: TDown

linecolor = Trend == 1 ? green : red

//RSI
src = close,

ep = 2 * RSI - 1
auc = ema( max( src - src[1], 0 ), ep )
adc = ema( max( src[1] - src, 0 ), ep )
x1 = (RSI - 1) * ( adc * 70 / (100-70) - auc)
ub = iff( x1 >= 0, src + x1, src + x1 * (100-70)/70 )
x2 = (RSI - 1) * ( adc * 30 / (100-30) - auc)
lb = iff( x2 >= 0, src + x2, src + x2 * (100-30)/30 )

//Affichage
plot(avg(ub, lb), color=purple, style = line, linewidth=1, title="RSI")
plot(Tsl, color = linecolor , style = line , linewidth = 1,title = "SuperTrend ATR")
 
netarchitech

netarchitech

Well-known member
VIP
@Investingtogive @BenTen I tried to convert the "SuperTrend ATR + RSI" TV script, but ran into a couple of issues...



Code:
##
# TradingView SuperTrend ATR + RSI Indicator Conversion (attempt)
# 11.19.2020
##

## Mode
input Factor = 3;
input ATR = 7;
input RSI = 7;

def src = close;

## SuperTrend ATR
def Up = hl2 - (Factor * ATR(ATR));
def Dn = hl2 + (Factor * ATR(ATR));

def TUp = if src[1] > TUp[1] then Max(Up, TUp[1]) else Up;
def TDown = if src[1] < TDown[1] then Min(Dn, TDown[1]) else Dn;

def Trend = if src > TDown[1] then 1 else if src < TUp[1] then -1 else !IsNaN(Trend[1]);
def Tsl = if Trend == 1 then TUp else TDown;

plot ATRline = if Trend == 1 then Color.GREEN else Color.RED;
ATRline.DefineColor("Up", Color.GREEN);
ATRline.DefineColor("Down", Color.RED);
ATRline.AssignValueColor(if Tsl > Tsl[1] then ATRline.Color("Up") else ATRline.Color("Down"));
ATRline.SetPaintingStrategy(PaintingStrategy.LINE);
    
## RSI
def ep = 2 * RSI - 1;
def auc = ExpAverage( Max( src - src[1], 0 ), ep );
def adc = ExpAverage( Max( src[1] - src, 0 ), ep );
def x1 = (RSI - 1) * ( adc * 70 / (100 - 70) - auc);
def ub = if x1 >= 0 then src + x1 else (src + x1 * (100 - 70) / 70);
def x2 = (RSI - 1) * ( adc * 30 / (100 - 30) - auc);
def lb = if x2 >= 0 then src + x2 else (src + x2 * (100 - 30) / 30);

plot RSIline = (Average(ub, lb));
RSIline.SetDefaultColor(Color.MAGENTA);
RSIline.SetPaintingStrategy(PaintingStrategy.LINE);

Hope this helps...

Good Luck and Good Trading :)
 
I

Investingtogive

New member
VIP
@netarchitech Thanks for the quick reply. I see the two areas that gave you issues. I'll see if I can figure these out. I really appreciate you getting me this far.
 
I

Investingtogive

New member
VIP
@netarchitech Thanks again for the head start. I was able to use your converted code and figure out the other issues. Here is the resulting code. Now I have to see if it's a worth while indicator to use.

Code:
##
# TradingView SuperTrend ATR + RSI Indicator Conversion (attempt)
# 11.19.2020
##

## Mode
input Factor = 3;
input ATR = 7;
input RSI = 7;

def src = close;

## SuperTrend ATR
def Up = hl2 - (Factor * ATR(ATR));
def Dn = hl2 + (Factor * ATR(ATR));

def TUp = if src[1] > TUp[1] then Max(Up, TUp[1]) else Up;
def TDown = if src[1] < TDown[1] then Min(Dn, TDown[1]) else Dn;

def Trend = if src > TDown[1] then 1 else if src < TUp[1] then -1 else Trend[1];

   
## RSI
def ep = 2 * RSI - 1;
def auc = ExpAverage( Max( src - src[1], 0 ), ep );
def adc = ExpAverage( Max( src[1] - src, 0 ), ep );
def x1 = (RSI - 1) * ( adc * 70 / (100 - 70) - auc);
def ub = if x1 >= 0 then src + x1 else (src + x1 * (100 - 70) / 70);
def x2 = (RSI - 1) * ( adc * 30 / (100 - 30) - auc);
def lb = if x2 >= 0 then src + x2 else (src + x2 * (100 - 30) / 30);

plot ATRline = (ub + lb) / 2;
ATRline.DefineColor("Up", Color.GREEN);
ATRline.DefineColor("Down", Color.RED);
ATRline.AssignValueColor(if Trend == 1 then ATRline.Color("Up") else ATRline.Color("Down"));
ATRline.SetPaintingStrategy(PaintingStrategy.LINE);
ATRline.SetDefaultColor(GetColor(1));
 
L

lindosskier

Member
Hi everyone. Is there any way to convert the "Balance of Market Power 14" from Trading View, into a TOS indicator? Thank you.
@SuryaKiranC do you also happen to know how to do this as well, or no? Thank you.
 
J007RMC

J007RMC

Well-known member
2019 Donor
VIP
ZigZag Fibs

Wondering if it's possible to make this indicator TOS


Code:
//@version=4
//
study("ZigZag ++ fibs", overlay=true)
//
///////////////
// FUNCTIONS //
///////////////

// Function outputs 1 when it's the first bar of the D/W/M/Y
is_newbar(res) =>
    ch = 0
    if(res == 'Y')
        t  = year(time('D'))
        ch := change(t) != 0 ? 1 : 0
    else
        t = time(res)
        ch := change(t) != 0 ? 1 : 0
    ch

// Rounding levels to min tick
nround(x) =>
    n = round(x / syminfo.mintick) * syminfo.mintick

////////////
// INPUTS //
////////////

pp_type                = input(title = 'Pivot Type',               defval = "Fibonacci", options = ["Traditional", "Fibonacci", "Woodie", "Camarilla"])
pp_period              = input(title = "Period",                   defval = "Day",  type = input.string, options = ['Day', 'Week', 'Month', 'Year'])
show_historical_levels = input(title = "Show Historical Levels?",  defval = false,  type = input.bool)
show_level_value       = input(title = "Show Levels Value?",       defval = true,   type = input.bool)
show_current_levels    = input(title = "Show Current Levels",      defval = false,  type = input.bool)

pp_res = pp_period == 'Day' ? 'D' : pp_period == 'Week' ? 'W' : pp_period == 'Month' ? 'M' : 'Y'

/////////////////////
// Get HLC from HT //

// Calc Open
open_cur = 0.0
open_cur := is_newbar(pp_res) ? open : open_cur[1]

popen = 0.0
popen := is_newbar(pp_res) ? open_cur[1] : popen[1]

// Calc High
high_cur = 0.0
high_cur := is_newbar(pp_res) ? high : max(high_cur[1], high)

phigh = 0.0
phigh := is_newbar(pp_res) ? high_cur[1] : phigh[1]

// Calc Low
low_cur = 0.0
low_cur := is_newbar(pp_res) ? low : min(low_cur[1], low)

plow = 0.0
plow := is_newbar(pp_res) ? low_cur[1] : plow[1]

// Calc Close
pclose = 0.0
pclose := is_newbar(pp_res) ? close[1] : pclose[1]


////////////////////////////
// CALCULATE PIVOT POINTS //
////////////////////////////

PP = 0.0
R1 = 0.0, R2 = 0.0, R3 = 0.0
S1 = 0.0, S2 = 0.0, S3 = 0.0

if (pp_type == "Traditional")
    PP := (phigh + plow + pclose) / 3
    R1 := PP     + (PP   - plow)
    S1 := PP     - (phigh - PP)
    R2 := PP     + (phigh - plow)
    S2 := PP     - (phigh - plow)
    R3 := phigh  + 2 * (PP   - plow)
    S3 := plow   - 2 * (phigh - PP)
 
if (pp_type == "Fibonacci")
    PP := (phigh + plow + pclose) / 3
    R1 := PP + (phigh - plow) * 0.382
    S1 := PP - (phigh - plow) * 0.382
    R2 := PP + (phigh - plow) * 0.618
    S2 := PP - (phigh - plow) * 0.618
    R3 := PP + (phigh - plow) * 1.000
    S3 := PP - (phigh - plow) * 1.000
 
if (pp_type == "Woodie")
    PP := (phigh + plow + 2 * popen) / 4
    R1 := PP + (PP - plow)
    S1 := PP - (phigh - PP)
    R2 := PP + (phigh - plow)
    S2 := PP - (phigh - plow)
    R3 := phigh + 2 * (PP - plow)
    S3 := plow  - 2 * (phigh - PP)
   
if (pp_type == "Camarilla")
    PP := (phigh + plow + pclose) / 3
    R1 := pclose + (phigh - plow) * 1.1/12
    S1 := pclose - (phigh - plow) * 1.1/12
    R2 := pclose + (phigh - plow) * 1.1/6
    S2 := pclose - (phigh - plow) * 1.1/6
    R3 := pclose + (phigh - plow) * 1.1/4
    S3 := pclose - (phigh - plow) * 1.1/4

// Projected levels

prPP = 0.0
prR1 = 0.0, prR2 = 0.0, prR3 = 0.0
prS1 = 0.0, prS2 = 0.0, prS3 = 0.0
 
if (pp_type == "Traditional")
    prPP := (high_cur + low_cur + close) / 3
    prR1 := prPP     + (prPP   - low_cur)
    prS1 := prPP     - (high_cur - PP)
    prR2 := prPP     + (high_cur - low_cur)
    prS2 := prPP     - (high_cur - low_cur)
    prR3 := phigh  + 2 * (prPP   - low_cur)
    prS3 := plow   - 2 * (high_cur - PP)  
 
//////////////
// PLOTTING //

bars_sinse = 0
bars_sinse := is_newbar(pp_res) ? 0 : bars_sinse[1] + 1

////////////////////////
// PLOT PIVOTS LEVELS //

vpp_p = line.new(bar_index[min(bars_sinse, 300)], PP, bar_index, PP, color=color.gray,  style =  line.style_solid, extend = extend.none)
vs1_p = line.new(bar_index[min(bars_sinse, 300)], S1, bar_index, S1, color=color.red,   style =  line.style_solid, extend = extend.none)
vs2_p = line.new(bar_index[min(bars_sinse, 300)], S2, bar_index, S2, color=color.red,   style =  line.style_solid, extend = extend.none)
vs3_p = line.new(bar_index[min(bars_sinse, 300)], S3, bar_index, S3, color=color.red,   style =  line.style_solid, extend = extend.none)
vr1_p = line.new(bar_index[min(bars_sinse, 300)], R1, bar_index, R1, color=color.green, style =  line.style_solid, extend = extend.none)
vr2_p = line.new(bar_index[min(bars_sinse, 300)], R2, bar_index, R2, color=color.green, style =  line.style_solid, extend = extend.none)
vr3_p = line.new(bar_index[min(bars_sinse, 300)], R3, bar_index, R3, color=color.green,   style =  line.style_solid, extend = extend.none)

// delete previous lines in the same period
if (not is_newbar(pp_res) or not show_historical_levels)
    line.delete(vpp_p[1])
    line.delete(vs1_p[1])
    line.delete(vs2_p[1]) 
    line.delete(vs3_p[1]) 
    line.delete(vr1_p[1])
    line.delete(vr2_p[1]) 
    line.delete(vr3_p[1])



// Add labels
label_vpp = label.new(bar_index, PP, text=show_level_value ? ("P"  + " " + tostring(nround(PP))) : "P",  style= label.style_none)
label_vs1 = label.new(bar_index, S1, text=show_level_value ? ("S1" + " " + tostring(nround(S1))) : "S1", style= label.style_none)
label_vs2 = label.new(bar_index, S2, text=show_level_value ? ("S2" + " " + tostring(nround(S2))) : "S2", style= label.style_none)
label_vs3 = label.new(bar_index, S3, text=show_level_value ? ("S3" + " " + tostring(nround(S3))) : "S3", style= label.style_none)
label_vr1 = label.new(bar_index, R1, text=show_level_value ? ("R1" + " " + tostring(nround(R1))) : "R1", style= label.style_none)
label_vr2 = label.new(bar_index, R2, text=show_level_value ? ("R2" + " " + tostring(nround(R2))) : "R2", style= label.style_none)
label_vr3 = label.new(bar_index, R3, text=show_level_value ? ("R3" + " " + tostring(nround(R3))) : "R3", style= label.style_none)
   
label.delete(label_vpp[1])
label.delete(label_vs1[1])
label.delete(label_vs2[1])
label.delete(label_vs3[1])
label.delete(label_vr1[1])
label.delete(label_vr2[1])
label.delete(label_vr3[1])   
   
// Projected levels   
line vpp_pr = na
line vs1_pr = na
line vs2_pr = na
line vs3_pr = na
line vr1_pr = na
line vr2_pr = na
line vr3_pr = na

if (show_current_levels)
   
    vpp_pr = line.new(bar_index[1], prPP, bar_index, prPP, color=color.gray,  style =  line.style_dashed, extend = extend.right)
    vs1_pr = line.new(bar_index[1], prS1, bar_index, prS1, color=color.red,   style =  line.style_dashed, extend = extend.right)
    vs2_pr = line.new(bar_index[1], prS2, bar_index, prS2, color=color.red,   style =  line.style_dashed, extend = extend.right)
    vs3_pr = line.new(bar_index[1], prS3, bar_index, prS3, color=color.red,   style =  line.style_dashed, extend = extend.right)
    vr1_pr = line.new(bar_index[1], prR1, bar_index, prR1, color=color.green, style =  line.style_dashed, extend = extend.right)
    vr2_pr = line.new(bar_index[1], prR2, bar_index, prR2, color=color.green, style =  line.style_dashed, extend = extend.right)
    vr3_pr = line.new(bar_index[1], prR3, bar_index, prR3, color=color.green, style =  line.style_dashed, extend = extend.right)
       
    line.delete(vpp_pr[1])
    line.delete(vs1_pr[1])
    line.delete(vs2_pr[1])
    line.delete(vs3_pr[1])
    line.delete(vr1_pr[1])
    line.delete(vr2_pr[1])
    line.delete(vr3_pr[1])
//
Pivot = input(false, title="Show Pivot High/Lows")
LP = input(defval = 4, title = "Left bars for Pivot")
RP = input(defval = 3, title = "Right bars for Pivot")

PH1 = pivothigh(LP,RP)
PH  = valuewhen(PH1,PH1,0)
plotshape(Pivot and barstate.ishistory?PH1:na,style=shape.circle, color=#FF4500, text = "PH", textcolor=color.orange,location=location.abovebar,  offset=-3, transp = 0, title="Pivot High")
plot(Pivot?PH:na,style=plot.style_circles, linewidth=2,color=security(syminfo.tickerid,timeframe.period,high,barmerge.lookahead_off)<=PH?#FF4500:na,title="Pivot High")

PL1 = pivotlow(LP,RP)
PL  = valuewhen(PL1,PL1,0)
plotshape(Pivot and barstate.ishistory?PL1:na,style=shape.circle, color=#6B8E23, text = "PL", textcolor=color.orange,location=location.belowbar,  offset=-3, transp = 0,title="Pivot High")
plot(Pivot?PL:na,style=plot.style_circles, linewidth=2, color=security(syminfo.tickerid,timeframe.period,low,barmerge.lookahead_off)>=PL?#6B8E23:na,title="Pivot High")

// inputs
Depth       = input(12, title="Depth")  // Depth
Deviation   = input(5, title="Deviation")  // Deviation

// ZigZag
lastlow = 0.0, lasthigh = 0.0
lastlow := nz(lastlow[1])
lasthigh := nz(lasthigh[1])

data(x) =>
    d = security(syminfo.tickerid, timeframe.period, x, gaps = barmerge.gaps_off,  lookahead = barmerge.lookahead_on)
    d
getLow(x, y, z, a) =>
    lastlow = y
    v = data(x)
    m = v==lastlow or data(z) - v > a*syminfo.mintick
    if v!=lastlow
        lastlow := v
    if m
        v := 0.0
    [v,lastlow]
getHigh(x, y, z, a) =>
    lasthigh = y
    v = data(x)
    m = v==lasthigh or v - data(z) > a*syminfo.mintick
    if v!=lasthigh
        lasthigh := v
    if m
        v := 0.0
    [v,lasthigh]

[v,e] = getLow(lowest(Depth), lastlow, low, Deviation)
lastlow := e
zBB =  v != 0.0
[v1,e1] = getHigh(highest(Depth), lasthigh, high, Deviation)
lasthigh := e1
zSS = v1 != 0.0

zigzagDirection = -1
zigzagHigh = 0
zigzagLow = 0
zigzagDirection := zBB ? 0 : zSS ? 1 : nz(zigzagDirection[1], -1)
virtualLow = zigzagLow[1] + 1
if not zBB or (zBB and zigzagDirection == zigzagDirection[1] and low > low[virtualLow])
    zigzagLow := nz(zigzagLow[1]) + 1
virtualHigh = zigzagHigh[1] + 1
if not zSS or (zSS and zigzagDirection == zigzagDirection[1] and high < high[virtualHigh])
    zigzagHigh := nz(zigzagHigh[1]) + 1
a=bar_index-zigzagLow
b=bar_index-zigzagHigh
var color c = na, c := fixnan(a < b[1] ? color.lime : a > b[1] ? color.red : na)
line zigzag = line.new(bar_index-zigzagLow, low[zigzagLow], bar_index-zigzagHigh, high[zigzagHigh], color=c, style=line.style_solid, width=4)
if (zigzagDirection == zigzagDirection[1])
    line.delete(zigzag[1])
   
zzPrevHigh = zigzagHigh[1]
zzPrevLow = zigzagLow[1]  
if not na(zzPrevHigh[1])
    zzPrevHigh := zzPrevHigh[1] + 1
if not na(zzPrevLow[1])
    zzPrevLow := zzPrevLow[1] + 1
if zigzagDirection != zigzagDirection[1]
    if zigzagDirection == 1
        zzPrevHigh := zigzagHigh[1] + 1
    if zigzagDirection == 0
        zzPrevLow := zigzagLow[1] + 1
       

//
f_draw_infopanel(_x, _y, _line, _text, _color)=>
    _rep_text = ""
    for _l = 0 to _line
        _rep_text := _rep_text + "\n"
    _rep_text := _rep_text + _text
    var label _la = na
    label.delete(_la)
    _la := label.new(
         x=_x, y=_y,
         text=_rep_text, xloc=xloc.bar_time, yloc=yloc.price,
         color=color.black, style=label.style_labelup, textcolor=_color, size=size.large)

info_label_off = input(50, title="Info panel offset")
position=input(8500,minval=-0.00001)
posx = timenow + round(change(time)*info_label_off)
posy = position


f_draw_infopanel(posx, posy, 0, "Zigzag", a < b ? color.lime : color.red)
 

Similar threads

Top