Unrequited Conversion Requests To ThinkOrSwim

vandell001

New member
2019 Donor
Hey Gang, There is an interesting MT4 indicator out there called 3 level ZZ semafor. There is one site that has it converted to TOS, they call it 3 Level Zigzag. The site patternsmart.com requires a VIP sign up (one month trial $30.00) and then an additional $99 for the indicator. I have the MT4 code. Is there anyone who can/would be interested in converting it.
 

halcyonguy

Well-known member
VIP
can you post a web link of where you found it? i searched and found a shorter version of this, but i didn't find what you posted.

i will try to convert it to thinkscript, but it could be a week or 2 or... i am in the middle of too many projects....
 

astro_phx

Member
Hi Halcyonguy, Thank you for your reply.
one of my friend send me the script. There are many things included into this indicator but the major one I am looking forward to is adxvma line that is showing uptrend=blue downtrend=red and sideways= yellow. other things we can find in other indicators.

thank you very much again for looking into it.

here is the link for the indicator. I guess this is the one you found online.

https://www.tradingview.com/script/waC5RGjN-ADX-Volatility-Moving-Average/
 

jorge50505

New member
VIP
Ruby:
//@version=4
study(title="Stochastic", shorttitle="Stoch", format=format.price, precision=2, resolution="")
periodK = input(14, title="K", minval=1)
periodD = input(3, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)
k = sma(stoch(close, high, low, periodK), smoothK)
d = sma(k, periodD)
plot(k, title="%K", color=#0094FF)
//plot(d, title="%D", color=#FF6A00)

plot(d, color= d[1] < d ? color.green : color.red)


periodK2 = input(21, title="K 2nd Stochastic", minval=1)
smoothK2 = input(5, title="Smooth 2nd Stochastic", minval=1)
periodD2 = input(5, title="D 2nd Indicator", minval=1)
k2 = sma(stoch(close, high, low, periodK2), smoothK2)
d2 = sma(k2, periodD2)
//plot(k > 80 ? color=color.red : k <20 ? color=color.green : color=color.white )

uptrend1 = k > 80
downtrend1 = k <20

plot(d2, color=d2[1] < d2 ? color.green : color.red, linewidth=2)

h0 = hline(100, "Upper Band", color=color.red, linestyle=hline.style_dotted, linewidth=2)
h1 = hline(0, "Lower Band", color=color.red, linestyle=hline.style_dotted, linewidth=2)
h2 = hline(80, "Upper Band", color=#606060)
h3 = hline(20, "Lower Band", color=#606060)
h4 = hline(55, "Upper Band", color=#606060)
h5 = hline(45, "Lower Band", color=#606060)

crosssell = crossunder(k,d) and k > 80
crossbuy = crossover(k,d) and k < 20

//bgcolor(crossbuy ? color.lime : na, transp=40)
//bgcolor(crosssell ? color.red : na, transp=40)



fill(h0, h2, color=color.gray, transp=80, title="Background")
fill(h1, h3, color=color.gray, transp=80, title="Background")

fill(h4,h5, color=color.yellow, transp=80)

fill(h2, h3, color=color.purple, transp=80, title="Background")



i suck at coding guys i use this free indicator off of tradingview to trigger alot of my trades has proven very profitable for me but would like to have it on thinkorswim when i am trading and would be awesome if some by up or sell down arrows could be added at cross of slow and fast stochastic

was created by softkill21 on tradingview

thanks in advance
 
Last edited by a moderator:

mirage6006

New member
VIP
Hi guys,

can some one help me to convert this trading view indicator to TOS
it called SSL hybrid https://www.tradingview.com/script/C3MlAWCw-SSL-Hybrid/
This script is designed for the NNFX Method, so it is recommended for Daily charts only.
Tried to implement a few VP NNFX Rules
This script has a SSL / Baseline (you can choose between the SSL or MA), a secondary SSL for continiuation trades and a third SSL for exit trades.
Alerts added for Baseline entries, SSL2 continuations, Exits.
Baseline has a Keltner Channel setting for "in zone" Gray Candles
Added "Candle Size > 1 ATR" Diamonds from my old script with the criteria of being within Baseline ATR range.
a3.png

Ruby:
//@version=4
//By Mihkel00
// This script is designed for the NNFX Method, so it is recommended for Daily charts only.
// Tried to implement a few VP NNFX Rules
// This script has a SSL / Baseline (you can choose between the SSL or MA), a secondary SSL for continiuation trades and a third SSL for exit trades.
// Alerts added for Baseline entries, SSL2 continuations, Exits.
// Baseline has a Keltner Channel setting for "in zone" Gray Candles
// Added "Candle Size > 1 ATR" Diamonds from my old script with the criteria of being within Baseline ATR range.
// Credits
// Strategy causecelebre https://www.tradingview.com/u/causecelebre/
// SSL Channel ErwinBeckers https://www.tradingview.com/u/ErwinBeckers/
// Moving Averages jiehonglim https://www.tradingview.com/u/jiehonglim/
// Moving Averages everget https://www.tradingview.com/u/everget/
// "Many Moving Averages" script Fractured https://www.tradingview.com/u/Fractured/
study("SSL Hybrid", overlay=true)
show_Baseline = input(title="Show Baseline", type=input.bool, defval=true)
show_SSL1 = input(title="Show SSL1", type=input.bool, defval=false)
show_atr = input(title="Show ATR bands", type=input.bool, defval=true)
//ATR
atrlen = input(14, "ATR Period")
mult = input(1, "ATR Multi", step=0.1)
smoothing = input(title="ATR Smoothing", defval="WMA", options=["RMA", "SMA", "EMA", "WMA"])

ma_function(source, atrlen) =>
if smoothing == "RMA"
rma(source, atrlen)
else
if smoothing == "SMA"
sma(source, atrlen)
else
if smoothing == "EMA"
ema(source, atrlen)
else
wma(source, atrlen)
atr_slen = ma_function(tr(true), atrlen)
////ATR Up/Low Bands
upper_band = atr_slen * mult + close
lower_band = close - atr_slen * mult

////BASELINE / SSL1 / SSL2 / EXIT MOVING AVERAGE VALUES
maType = input(title="SSL1 / Baseline Type", type=input.string, defval="HMA", options=["SMA","EMA","DEMA","TEMA","LSMA","WMA","MF","VAMA","TMA","HMA", "JMA", "Kijun v2", "EDSMA","McGinley"])
len = input(title="SSL1 / Baseline Length", defval=60)

SSL2Type = input(title="SSL2 / Continuation Type", type=input.string, defval="JMA", options=["SMA","EMA","DEMA","TEMA","WMA","MF","VAMA","TMA","HMA", "JMA","McGinley"])
len2 = input(title="SSL 2 Length", defval=5)
//
SSL3Type = input(title="EXIT Type", type=input.string, defval="HMA", options=["DEMA","TEMA","LSMA","VAMA","TMA","HMA","JMA", "Kijun v2", "McGinley", "MF"])
len3 = input(title="EXIT Length", defval=15)
src = input(title="Source", type=input.source, defval=close)

//
tema(src, len) =>
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
(3 * ema1) - (3 * ema2) + ema3
kidiv = input(defval=1,maxval=4, title="Kijun MOD Divider")

jurik_phase = input(title="* Jurik (JMA) Only - Phase", type=input.integer, defval=3)
jurik_power = input(title="* Jurik (JMA) Only - Power", type=input.integer, defval=1)
volatility_lookback = input(10, title="* Volatility Adjusted (VAMA) Only - Volatility lookback length")
//MF
beta = input(0.8,minval=0,maxval=1,step=0.1, title="Modular Filter, General Filter Only - Beta")
feedback = input(false, title="Modular Filter Only - Feedback")
z = input(0.5,title="Modular Filter Only - Feedback Weighting",step=0.1, minval=0, maxval=1)
//EDSMA
ssfLength = input(title="EDSMA - Super Smoother Filter Length", type=input.integer, minval=1, defval=20)
ssfPoles = input(title="EDSMA - Super Smoother Filter Poles", type=input.integer, defval=2, options=[2, 3])

//----

//EDSMA
get2PoleSSF(src, length) =>
PI = 2 * asin(1)
arg = sqrt(2) * PI / length
a1 = exp(-arg)
b1 = 2 * a1 * cos(arg)
c2 = b1
c3 = -pow(a1, 2)
c1 = 1 - c2 - c3

ssf = 0.0
ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2])

get3PoleSSF(src, length) =>
PI = 2 * asin(1)

arg = PI / length
a1 = exp(-arg)
b1 = 2 * a1 * cos(1.738 * arg)
c1 = pow(a1, 2)

coef2 = b1 + c1
coef3 = -(c1 + b1 * c1)
coef4 = pow(c1, 2)
coef1 = 1 - coef2 - coef3 - coef4

ssf = 0.0
ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3])

ma(type, src, len) =>
float result = 0
if type=="TMA"
result := sma(sma(src, ceil(len / 2)), floor(len / 2) + 1)
if type=="MF"
ts=0.,b=0.,c=0.,os=0.
//----
alpha = 2/(len+1)
a = feedback ? z*src + (1-z)*nz(ts[1],src) : src
//----
b := a > alpha*a+(1-alpha)*nz(b[1],a) ? a : alpha*a+(1-alpha)*nz(b[1],a)
c := a < alpha*a+(1-alpha)*nz(c[1],a) ? a : alpha*a+(1-alpha)*nz(c[1],a)
os := a == b ? 1 : a == c ? 0 : os[1]
//----
upper = beta*b+(1-beta)*c
lower = beta*c+(1-beta)*b
ts := os*upper+(1-os)*lower
result := ts
if type=="LSMA"
result := linreg(src, len, 0)
if type=="SMA" // Simple
result := sma(src, len)
if type=="EMA" // Exponential
result := ema(src, len)
if type=="DEMA" // Double Exponential
e = ema(src, len)
result := 2 * e - ema(e, len)
if type=="TEMA" // Triple Exponential
e = ema(src, len)
result := 3 * (e - ema(e, len)) + ema(ema(e, len), len)
if type=="WMA" // Weighted
result := wma(src, len)
if type=="VAMA" // Volatility Adjusted
/// Copyright © 2019 to present, Joris Duyck (JD)
mid=ema(src,len)
dev=src-mid
vol_up=highest(dev,volatility_lookback)
vol_down=lowest(dev,volatility_lookback)
result := mid+avg(vol_up,vol_down)
if type=="HMA" // Hull
result := wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
if type=="JMA" // Jurik
/// Copyright © 2018 Alex Orekhov (everget)
/// Copyright © 2017 Jurik Research and Consulting.
phaseRatio = jurik_phase < -100 ? 0.5 : jurik_phase > 100 ? 2.5 : jurik_phase / 100 + 1.5
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
alpha = pow(beta, jurik_power)
jma = 0.0
e0 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])
e1 = 0.0
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * pow(1 - alpha, 2) + pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
result := jma
if type=="Kijun v2"
kijun = avg(lowest(len), highest(len))//, (open + close)/2)
conversionLine = avg(lowest(len/kidiv), highest(len/kidiv))
delta = (kijun + conversionLine)/2
result :=delta
if type=="McGinley"
mg = 0.0
mg := na(mg[1]) ? ema(src, len) : mg[1] + (src - mg[1]) / (len * pow(src/mg[1], 4))
result :=mg
if type=="EDSMA"

zeros = src - nz(src[2])
avgZeros = (zeros + zeros[1]) / 2

// Ehlers Super Smoother Filter
ssf = ssfPoles == 2
? get2PoleSSF(avgZeros, ssfLength)
: get3PoleSSF(avgZeros, ssfLength)

// Rescale filter in terms of Standard Deviations
stdev = stdev(ssf, len)
scaledFilter = stdev != 0
? ssf / stdev
: 0

alpha = 5 * abs(scaledFilter) / len

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

///SSL 1 and SSL2
emaHigh = ma(maType, high, len)
emaLow = ma(maType, low, len)

maHigh = ma(SSL2Type, high, len2)
maLow = ma(SSL2Type, low, len2)

///EXIT
ExitHigh = ma(SSL3Type, high, len3)
ExitLow = ma(SSL3Type, low, len3)

///Keltner Baseline Channel
BBMC = ma(maType, close, len)
useTrueRange = input(true)
multy = input(0.2, step=0.05, title="Base Channel Multiplier")
Keltma = ma(maType, src, len)
range = useTrueRange ? tr : high - low
rangema = ema(range, len)
upperk =Keltma + rangema * multy
lowerk = Keltma - rangema * multy

//Baseline Violation Candle
open_pos = open*1
close_pos = close*1
difference = abs(close_pos-open_pos)
atr_violation = difference > atr_slen
InRange = upper_band > BBMC and lower_band < BBMC
candlesize_violation = atr_violation and InRange
plotshape(candlesize_violation, color=color.white, size=size.tiny,style=shape.diamond, location=location.top, transp=0,title="Candle Size > 1xATR")


//SSL1 VALUES
Hlv = int(na)
Hlv := close > emaHigh ? 1 : close < emaLow ? -1 : Hlv[1]
sslDown = Hlv < 0 ? emaHigh : emaLow

//SSL2 VALUES
Hlv2 = int(na)
Hlv2 := close > maHigh ? 1 : close < maLow ? -1 : Hlv2[1]
sslDown2 = Hlv2 < 0 ? maHigh : maLow

//EXIT VALUES
Hlv3 = int(na)
Hlv3 := close > ExitHigh ? 1 : close < ExitLow ? -1 : Hlv3[1]
sslExit = Hlv3 < 0 ? ExitHigh : ExitLow
base_cross_Long = crossover(close, sslExit)
base_cross_Short = crossover(sslExit, close)
codiff = base_cross_Long ? 1 : base_cross_Short ? -1 : na

//COLORS
show_color_bar = input(title="Color Bars", type=input.bool, defval=true)
color_bar = close > upperk ? #00c3ff : close < lowerk ? #ff0062 : color.gray
color_ssl1 = close > sslDown ? #00c3ff : close < sslDown ? #ff0062 : na

//PLOTS
plotarrow(codiff, colorup=#00c3ff, colordown=#ff0062,title="Exit Arrows", transp=20, maxheight=20, offset=0)
p1 = plot(show_Baseline ? BBMC : na, color=color_bar, linewidth=4,transp=0, title='MA Baseline')
DownPlot = plot( show_SSL1 ? sslDown : na, title="SSL1", linewidth=3, color=color_ssl1, transp=10)
barcolor(show_color_bar ? color_bar : na)
up_channel = plot(show_Baseline ? upperk : na, color=color_bar, title="Baseline Upper Channel")
low_channel = plot(show_Baseline ? lowerk : na, color=color_bar, title="Basiline Lower Channel")
fill(up_channel, low_channel, color=color_bar, transp=90)

////SSL2 Continiuation from ATR
atr_crit = input(0.9, step=0.1, title="Continuation ATR Criteria")
upper_half = atr_slen * atr_crit + close
lower_half = close - atr_slen * atr_crit
buy_inatr = lower_half < sslDown2
sell_inatr = upper_half > sslDown2
sell_cont = close < BBMC and close < sslDown2
buy_cont = close > BBMC and close > sslDown2
sell_atr = sell_inatr and sell_cont
buy_atr = buy_inatr and buy_cont
atr_fill = buy_atr ? color.green : sell_atr ? color.purple : color.white
LongPlot = plot(sslDown2, title="SSL2", linewidth=2, color=atr_fill, style=plot.style_circles, transp=0)
u = plot(show_atr ? upper_band : na, "+ATR", color=color.white, transp=80)
l = plot(show_atr ? lower_band : na, "-ATR", color=color.white, transp=80)

//ALERTS
alertcondition(crossover(close, sslDown), title='SSL Cross Alert', message='SSL1 has crossed.')
alertcondition(crossover(close, sslDown2), title='SSL2 Cross Alert', message='SSL2 has crossed.')
alertcondition(sell_atr, title='Sell Continuation', message='Sell Continuation.')
alertcondition(buy_atr, title='Buy Continuation', message='Buy Continuation.')
alertcondition(crossover(close, sslExit), title='Exit Sell', message='Exit Sell Alert.')
alertcondition(crossover(sslExit, close), title='Exit Buy', message='Exit Buy Alert.')
alertcondition(crossover(close, upperk ), title='Baseline Buy Entry', message='Base Buy Alert.')
alertcondition(crossover(lowerk, close ), title='Baseline Sell Entry', message='Base Sell Alert.')
 
Last edited by a moderator:

mirage6006

New member
VIP
@mirage6006 I would never say never. :)
uTS has insightful, gifted, smart traders and fellow thinkscripters that have contributed scripts that leave me in awe.
While most are not expert at TradingView, the math and logic of indicators is the same across platforms so simpler scripts can be done.
  1. But this is not a simpler script
  2. The majority of the traders on the forum do not trade Forex so there might not be any interest
actually, im using this on stocks and it work good for me if i combine it with QQE
 

mirage6006

New member
VIP
@mirage6006

Great! The more you can tell us about how this indicator enhances your trading, what type of equities, what aggregations, what indicators you pair it with, what type of results, will go toward generating interest in getting this to work in ToS. :)
im trading stocks options only for now.
im always looking for liqued stocks like SPY or QQQ or AMZN ......ext

combining the SSL hybrid with QQE mod turn out to be very good so far

my long signal is when the blue arrow is pointing up, and the candle closes above the middle line + QQE is blue, thats my go signal,
and i close my position only if im up 10% on my option, or a red arrow pointing down appears

sometime i close some of my positions and leave runners, they often hit 100% or 150%

for short positions just do the opposites

the only down side so far is waiting for these signals to appear
 

jordan belfort

New member
First time poster, so please take it easy on me. lol A friend of mine recently stumbled across the below feature on trading view. We would like to be able to run a custom scanner for this script below in TOS to find stocks that meet this criteria. Also if possible add this to our chart in TOS as well. Can anyone help? Thanks in advance

DESCRIPTION:
This Alert indicator utilizes the Heiken Ashi with non lag EMA was a scalping and intraday trading system
that has been adapted also for trading with binary options high/low. There is also included
filtering on MACD direction and trend direction as indicated by two MA: smoothed MA (11) and EMA (89).
The the Heiken Ashi candles are great as price action trending indicator, they shows smooth strong
and clear price fluctuations.
https://www.tradingview.com/script/aDYKgCBv-Heiken-Ashi-zero-lag-EMA-v1-1-by-JustUncleL/
Screenshot (8).png

Ruby:
//@version=3
//
study(title = "Heiken Ashi zero lag EMA v1.2 by JustUncleL", shorttitle="HAZEMA v1.2 by JustUncleL", overlay=true)
//

// Title: Heiken Ashi with non lag dot by JustUncleL
// Author: JustUncleL
// Version: 1.2
// Date: 5-feb-2016
//
// Description:
// This Alert indicator utilizes the Heiken Ashi with non lag EMA was a scalping and intraday trading system
// that has been adapted also for trading with binary options high/low. There is also included
// filtering on MACD direction and trend direction as indicated by two MA: smoothed MA(11) and EMA(89).
// The the Heiken Ashi candles are great as price action trending indicator, they shows smooth strong
// and clear price fluctuations.
//
// Financial Markets: any.
// Optimsed settings for 1 min, 5 min and 15 min Time Frame;
// Expiry time for Binary options High/Low 3-6 candles.
//
// Indicators used in calculations:
// - Exponential moving average, period 89
// - Smoothed moving average, period 11
// - Non lag EMA, period 20
// - MACD 2 colour (13,26,9)
//
//
// Generate Alerts use the following Trading Rules
// Heiken Ashi with non lag dot
// Trade only in direction of the trend.
// UP trend moving average 11 period is above Exponential moving average 89 period,
// Doun trend moving average 11 period is below Exponential moving average 89 period,
//
// CALL Arrow appears when:
// Trend UP SMA11>EMA89 (optionally disabled),
// Non lag MA blue dot and blue background.
// Heike ashi green color.
// MACD 2 Colour histogram green bars (optional disabled).
//
// PUT Arrow appears when:
// Trend UP SMA11<EMA89 (optionally disabled),
// Heike ashi red color.
// Non lag MA red dot and red background
// MACD 2 colour histogram red bars (optionally disabled).
//
// Modifications:
// 1.2 - Added extra Alerts.
// - Added optional Arrows for ZEMA direction change alerts.
// - Updated to version3 Pinescript.
// - Replace ZEMA calculation with more accurate formula.
//
// 0.2 - Added MACD and directional filtering.
// Added background highlighting of Zero Lag EMA dots.
// Replaced Bollinger Band squeeze indicator with MACD 2 colour
// 0.1 - Original version.
//
// References:
// - Almost Zero Lag EMA [LazyBear]
// - MACD 2 colour v0.2 by JustUncleL
// - http://www.forexstrategiesresources...rategies-ii/163-heiken-ashi-with-non-lag-dot/
//

FastLen = input(11,minval=2,title="Fast Smoothed MA Length")
SlowLen = input(89,minval=10,title="Slow EMA Length")
length=input(20, minval=2,title="Zero Lag EMA (DOTS) Length")
umaf = input(true,title="Use Trend Directional Filter")
sarrows = input(false,title="Show ZEMA Directional Change Arrows")

//Function to Calculate Zero lag EMA
zema(src,len) =>
lag = len>1 ? (len - 1)/2 : 0
ema_data = (src + (src - nz(src[lag])))
return = ema(ema_data, len)
return


//Collect source input and Moving Average Lengths
//
// Use only Heikinashi Candles for all calculations
srcClose = security(heikinashi(tickerid), period, close)
srcOpen = security(heikinashi(tickerid), period, open)
srcHigh = security(heikinashi(tickerid), period, high)
srcLow = security(heikinashi(tickerid), period, low)
//
//
fastMA = input(title="MACD Fast MA Length", type = integer, defval = 13, minval = 2)
slowMA = input(title="MACD Slow MA Length", type = integer, defval = 26, minval = 7)
signal = input(title="MACD Signal Length", type = integer, defval = 9, minval=1)
umacd = input(true,title="Use MACD Filtering")
//
[currMacd,currSig,_] = macd(srcClose[0], fastMA, slowMA, signal)
macdH = currMacd > 0 ? rising(currMacd,3) ? green : red : falling(currMacd,3) ? red : green
//
//Calculate No lag EMA
//ema1=ema(srcClose, length)
//ema2=ema(ema1, length)
//d=ema1-ema2
//zlema=ema1+d
zlema = zema(srcClose, length)
//
col = zlema > zlema[1] ? blue : red
up = zlema > zlema[1] ? true : false
down = zlema < zlema[1] ? true : false
// Draw the DOT no lag MA and colour background to make it easier to see.
plot(zlema,color=col, style=circles, linewidth=4, transp=30, title="HAZEMA ZEMA line")
bgcolor(col, transp=85)

//
// Calculate Smoothed MA and EMA
FastMA = 0.0
FastMA := na(FastMA[1]) ? sma(srcClose, FastLen) : (FastMA[1] * (FastLen - 1) + srcClose) / FastLen
SlowMA = ema(srcClose,SlowLen)

// Draw the directional MA's
plot(FastMA,color=olive,transp=0,style=line,linewidth=2)
plot(SlowMA,color=red,transp=0,style=line,linewidth=2)

//
//Calculate potential Entry point
trendup = 0
trenddn = 0
trendup := up and srcOpen<srcClose and (not umaf or FastMA>SlowMA) and (not umacd or macdH==green)? na(trendup[1]) ? 1 : trendup[1]+1 : 0
trenddn := down and srcOpen>srcClose and (not umaf or FastMA<SlowMA) and (not umacd or macdH==red)? na(trenddn[1]) ? 1 : trenddn[1]+1 : 0
//Plot PUT/CALL pointer for entry
plotshape(trenddn==1, title="HAZEMA Up Arrow", style=shape.triangledown,location=location.abovebar, color=red, transp=0, size=size.small,text="PUT")
plotshape(trendup==1, title="HAZEMA Down Arrow", style=shape.triangleup,location=location.belowbar, color=green, transp=0, size=size.small,text="CALL")

// Create alert to signal entry and plot circle along bottom to indicate alarm set
zDirection = zlema > zlema[1] ? 1 : 2
trendalert = trendup==1 or trenddn==1
isZEMAup = change(zDirection) and zDirection==1
isZEMAdn = change(zDirection) and zDirection==2
//
alertcondition(trendalert,title="HAZEMA Alert",message="HAZEMA Alert")
alertcondition(trendup==1,title="HAZEMA Call",message="HAZEMA CALL")
alertcondition(trenddn==1,title="HAZEMA Put",message="HAZEMA PUT")
alertcondition(isZEMAup, title="HAZEMA ZEMA UP",message="HAZEMA ZEMA UP")
alertcondition(isZEMAdn, title="HAZEMA ZEMA DOWN",message="HAZEMA ZEMA DOWN")
//
plotshape(trendalert[1], title="HAZEMA Alert Dot", style=shape.circle,location=location.bottom, color=trendup[1]?green:trenddn[1]?red:na, transp=0,offset=-1)
plotarrow(sarrows? (isZEMAup? 1 : isZEMAdn ? -1 : na) : na, title="HAZEMA ZEMA Direction", colorup=blue, colordown=red, transp=10, minheight = 40, maxheight=50, offset=0)

//EOF
 
Last edited by a moderator:

grasshopper123

New member
Hi All

I want to plot the moving average envelope as it appears in this video
EMA Heikin Ashi Scalping

He is using Trading View so he is able to shade the channel according to its slope. Is there a way to do that in TOS?

I tried to post this in the TV to TOS forum but I get an error message when I try to open that forum.

Thanks
 

Brew

New member
I've been searching the internet for months trying to find an indicator like this, but have not been able to find even a single lead. I've been looking for a volume profile similar to Trading View/ Trend Spider's.
I'd love to have a volume profile with these features:
  1. Profile that has a base on the right hand side of the chart going left
  2. Has buying/ selling volume differentiated on it
  3. Has a highlighted Volume Point of Control
If anyone could help out with that, you would be a god sent.

Thank you for your time, this community is amazing.

Here is an example of something similar to what I'm looking for:

unknown.png
 

obada yousif

New member
Hi all,
this is the code for tradeview for a more advanced tsv, can anyone covert to tos?
Ruby:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Original TSV Indicator was written by liw0 active on https://www.tradingview.com/u/liw0 Updated/Enhancements by @StephXAGs with inspiration from @storma
// CREDITS: http://quant.stackexchange.com/questions/2816/how-to-calculate-time-segmented-volume and special thanks to mohanee for the base divergece hunter code

//@version=4
study(title="Time Segmented Volume with divergence and Kumo cloud background", shorttitle="TSV", format=format.volume, precision=0, resolution="")

// Getting inputs

len = input(13, title="TSV Length")
smoothing = input(defval="EMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA"], title="Moving Average")

toast(rsi ,l_ma) =>
if smoothing == "RMA"
rma(rsi ,l_ma)
else
if smoothing == "SMA"
sma(rsi ,l_ma)
else
if smoothing == "EMA"
sma(rsi ,l_ma)
else
if smoothing == "WMA"
wma(rsi ,l_ma)
else
if smoothing == "VWMA"
vwma(rsi ,l_ma)




l_ma = input(3, title="MA Length")
src = input(close, "Source", type = input.source)
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
lbR = input(title="Pivot Lookback Right", defval=5)
lbL = input(title="Pivot Lookback Left", defval=5)
rangeUpper = input(title="Max of Lookback Range", defval=100)
rangeLower = input(title="Min of Lookback Range", defval=2)
plotBull = input(title="Plot Bullish", defval=true)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=true)
plotBear = input(title="Plot Bearish", defval=true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=true)




// Additional Plot colors
//col_grow_above = input(#26A69A, "Above Grow", input.color, group="Histogram", inline="Above")
//col_fall_above = input(#B2DFDB, "Fall", input.color, group="Histogram", inline="Above")
//col_grow_below = input(#FFCDD2, "Below Grow", input.color, group="Histogram", inline="Below")
//col_fall_below = input(#FF5252, "Fall", input.color, group="Histogram", inline="Below")

bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
rsi = sum(close>close[1]?volume*close-close[1]:close<close[1]?(volume*-1)*close-close:0,len)
m = sum(close>close[1]?volume*close-close[1]:close<close[1]?(volume*-1)*close-close:0,len)

xLag = (l_ma - 1) / 2
EMAData = (rsi + (rsi - rsi[xLag]))
ZLEMA = ema(EMAData, l_ma)

osc = toast(rsi ,l_ma)

//zero lag ema variant
//osc = ZLEMA


tsvColor = m > 0 ? color.new(#b2b5be, 0) : color.new(#b2b5bf, 0)
plot(m, color=tsvColor, title="TSVr", linewidth=2, style=plot.style_histogram)

//plot(m, title="TSV", linewidth=1, style=plot.style_histogram, color=color.new((m>=0 ? (m[1] < m ? col_grow_above : col_fall_above) : (m[1] < m ? col_grow_below : col_fall_below) ),0))
//plot(m, title="TSV", linewidth=1, color=#f2f2f2, style=plot.style_histogram)
plot(osc, title="TSV VWMA", linewidth=1, color=#f2f2f2)
hline(0, title="Middle Line", linestyle=hline.style_solid)
bgcolor(color=crossover(osc, 0) ? #f2f2f2 : na, transp=100, title="Background Cross Up")
bgcolor(color=crossunder(osc, 0) ? #f2f2f2 : na, transp=100, title="Background Cross Down")

//Additional crossovers

//plotshape(series=crossover(m, osc), style=shape.triangledown, color=#ffffff, transp=0, location=location.belowbar)
//plotshape(series=crossunder(m, osc), style=shape.triangleup, color=#ffffff, transp=0, location=location.abovebar)
plotshape(series=crossover(osc, 0), title="Cross Up", size=size.auto, style=shape.diamond, color=#a0d99e, transp=0, location=location.bottom)
plotshape(series=crossunder(osc, 0), title="Cross Down", size=size.auto, style=shape.diamond, color=#b04735, transp=0, location=location.bottom)
crossoverCond = crossover(osc, 0)
crossunderCond = crossunder(osc, 0)

Long = (m > osc) and (m > 0)
Long_fail = (m < osc) and (m > 0)
Short = (m < osc) and (m < 0)
Short_fail = (m > osc) and (m < 0)

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



//Kumo Cloud

conversionPeriods = input(9, minval=1, title="Conversion Line Length")
basePeriods = input(26, minval=1, title="Base Line Length")
laggingSpan2Periods = input(52, minval=1, title="Lagging Span 2 Length")
displacement = input(1, minval=0, title="Displacement")
donchian(len) => avg(lowest(len), highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)

//Additional options to Kumo

//plot(conversionLine, color=#2962FF, title="Conversion Line")
//plot(baseLine, color=#B71C1C, title="Base Line")
//plot(close, offset = -displacement + 1, color=#43A047, title="Lagging Span")

p1 = plot(leadLine1, offset = displacement, color=#A5D6A7, transp=100,
title="Lead 1")
p2 = plot(leadLine2, offset = displacement, color=#EF9A9A, transp=100,
title="Lead 2")
//fill(p1, p2, color = leadLine1 > leadLine2 ? color.rgb(67, 160, 71, 70) : color.rgb(244, 67, 54, 70))

bgcolor (color = leadLine1 > leadLine2 ? color.rgb(67, 160, 71, 90) : color.rgb(244, 67, 54, 90))
crossKumoCond = cross(leadLine1, leadLine2)

plFound = na(pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low

oscHL = osc[lbR] > valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Lower Low

priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound

plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=1,
color=(bullCond ? bullColor : noneColor),
transp=0
)

plotshape(
bullCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text="B",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)

//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low

oscLL = osc[lbR] < valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Higher Low

priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound

plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=1,
color=(hiddenBullCond ? hiddenBullColor : noneColor),
transp=0
)

plotshape(
hiddenBullCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text="H",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)

//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High

oscLH = osc[lbR] < valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Higher High

priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1)

bearCond = plotBear and priceHH and oscLH and phFound

plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=1,
color=(bearCond ? bearColor : noneColor),
transp=0
)

plotshape(
bearCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text="B",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)

//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High

oscHH = osc[lbR] > valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Lower High

priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1)

hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound

plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=1,
color=(hiddenBearCond ? hiddenBearColor : noneColor),
transp=0
)

plotshape(
hiddenBearCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text="H",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)



alertcondition(crossKumoCond, title="Kumo Cloud Change", message="Kumo Cloud changed color {{ticker}} XXmin")
alertcondition(crossoverCond, title="Cross Up", message="TSV Cross Up {{ticker}} XXmin")
alertcondition(crossoverCond, title="Cross Down", message="TSV Cross Down {{ticker}} XXmin")
alertcondition(bullCond, title="Bull", message="TSV Regular Bull Div {{ticker}} XXmin")
alertcondition(bearCond, title="Bear", message="TSV Regular Bear Div {{ticker}} XXmin")
alertcondition(hiddenBullCond, title="Hidden Bull", message="TSV Hidden Bull Div {{ticker}} XXmin")
alertcondition(hiddenBearCond, title="Hidden Bear", message="TSV Hidden Bear Div {{ticker}} XXmin")
 
Last edited by a moderator:

zeek

Active member
2019 Donor
I found this Market Delta Volume indicator on Tradingview platform and think it looks great. Is there any possibilty to convert this into a lower TOS study?

https://www.tradingview.com/script/3KPtU6i6-Market-Delta-Volume-for-Realtime-Bars/


Source code:

Code:
//@version=4
//@the_MarketWhisperer
//Based on Pinecoders' codebase

// What is it?
// Market Delta Volume Tool
// A market delta tool that shows, (1) the volume that got transacted on upticks - or the market buy volume; (2) the volume that got transacted on downticks - or the market sell volume
// (3) the market delta volume (i.e., market buy volume - market sell volume); (4) the total volume (market buy volume + market sell volume + neutral volume)
// and (4) the volume that got transacted without a change in price - or the neutral volume (total volume = market buy volume + market sell volume + neutral volume)
// NOTE: THIS WORKS ONLY ON REALTIME BARS, NOT ON HISTORICAL BARS!
// The dotted line marks the start of realtime data (i.e., the bar from which the indicator started collecting and displaying data)
// You will see accurate data for bars to the right of this line. The longer you keep a chart open with the study enabled, the more data it collects and displays.
// and the better your analysis can potentially be.
// Note that the data gets reset everytime any of the options is changed, the market is switched, browser is refreshed, or the script is reloaded
// DATA ISN'T STORED. I.e., every time a new chart is loaded, data gets refreshed.
// Who is it for?
// For traders who are used to analysing buy/sell activity using market delta information
// Especially, short-term trader/scalpers who are used to keeping the same chart open through the trading session
// Also for traders to see and study how anomalies in volume can give clues to buyer/seller absorption, initiative buying/selling etc.
// Can be used to better understand VSA as well, although not necessary
// Essentially, this gives realtime delta volume information; use it however you see fit

study("Market Delta Volume for Realtime Bars",  shorttitle="MarketDelta_MW", overlay=true, max_labels_count=500)

isDisplayBuySellVol = input(defval=true, type=input.bool, title="Show Market Buy/Sell Volume")
isDisplayDeltaVol = input(defval=true, type=input.bool, title="Show Market Delta Volume")
isDisplayTotalVol = input(defval=true, type=input.bool, title="Show Total Volume")
isDisplayNeutralVol = input(defval=true, type=input.bool, title="Show Neutral Volume")
isDisplayStartLine = input(defval=true, type=input.bool, title="Show Start Line", tooltip="Realtime data starts from the bar to the right of this line")
isDisplayPercent = input(defval=false, type=input.bool, title="Show Buy/Sell/Neutral Volume as Percent of Total Volume")
scaleDownFactor = input(defval=1.0, type=input.float, options=[1.0, 10.0, 100.0, 1000.0, 10000.0], title="Volume Scale Down Factor")
color colorBuyVol = input(color.green, "Market Buy Volume", type = input.color)
color colorSellVol = input(color.red, "Market Sell Volume", type = input.color)
color colorDeltaPositive = input(color.green, "Delta Positive", type = input.color)
color colorDeltaNegative = input(color.red, "Delta Negative", type = input.color)
color colorDeltaNeutral = input(color.gray, "Delta Neutral", type = input.color)
color colorTotalVol = input(color.blue, "Total Volume", type = input.color)
color colorNeutralVol = input(color.gray, "Neutral Volume", type = input.color)

f_upDnNtVolume() =>
    varip float _prevClose = open
    varip float _prevVolume = 0.
    varip float _newVolume = 0.
    varip float _volUp = 0.
    varip float _volDn = 0.
    varip float _volNt = 0.
    if barstate.isnew
        _volUp := 0.
        _volDn := 0.
        _volNt := 0.
        _prevClose := nz(close[1])
        _prevVolume := 0.
    _newVolume := volume - _prevVolume

    if close > _prevClose
        _volUp += _newVolume
    else if close < _prevClose
        _volDn += _newVolume
    else
        _volNt += _newVolume
    _prevClose := close
    _prevVolume := volume
    [_volUp, _volDn, _volNt]

var int barConsidered = 0
var int firstBar = 1
[volUp, volDn, volNt] = f_upDnNtVolume()
deltaVol = volUp - volDn
totVol   = volUp + volDn + volNt

barConsidered := barstate.isrealtime? 1:barConsidered
var string label_text = na

if barConsidered
    if isDisplayBuySellVol
        volDnDisplay = isDisplayPercent? nz((volDn/totVol)*100):int(volDn/scaleDownFactor)
        volUpDisplay = isDisplayPercent? nz((volUp/totVol)*100):int(volUp/scaleDownFactor)
            
        label.new(bar_index, high, yloc = yloc.price, color=color.white, textcolor=colorSellVol, style=label.style_none, textalign=text.align_center, text=tostring(volDnDisplay, '#.#'))
        label.new(bar_index, high, yloc = yloc.abovebar, color=color.white, textcolor=colorBuyVol, style=label.style_none, textalign=text.align_center, text= tostring(volUpDisplay, '#.#'))
    
    if isDisplayDeltaVol
        text_color = volUp - volDn>0? colorDeltaPositive: volUp - volDn < 0? colorDeltaNegative:colorDeltaNeutral
        label_text := tostring(int((volUp-volDn)/scaleDownFactor))
        label.new(bar_index, low, yloc = yloc.belowbar, color=color.white, textcolor=text_color, style=label.style_none, textalign=text.align_center, text=label_text)

    if isDisplayTotalVol
        text_color = colorTotalVol
        label_text := "\n\n" + tostring(int(totVol/scaleDownFactor))
        label.new(bar_index, low, yloc = yloc.belowbar, color=color.white, textcolor=text_color, style=label.style_none, textalign=text.align_center, text=label_text)

    if isDisplayNeutralVol
        text_color = colorNeutralVol
        volNtDisplay = isDisplayPercent? nz((volNt/totVol)*100):int(volNt/scaleDownFactor)
        label_text := label_text + "\n\n" + tostring(volNtDisplay, '#.#')
        label.new(bar_index, low, yloc = yloc.belowbar, color=color.white, textcolor=text_color, style=label.style_none, textalign=text.align_center, text=label_text)

    if firstBar
        if isDisplayStartLine
            line.new(bar_index, high+(syminfo.mintick*15), bar_index, high+(syminfo.mintick*30), extend=extend.right, color=color.black, style = line.style_dashed)
            line.new(bar_index, low-(syminfo.mintick*20), bar_index, low-(syminfo.mintick*30), extend=extend.right, color=color.black, style = line.style_dashed)
        firstBar := 0
 

Askia

New member
Rate of Change - Weekly Signals
Can anyone help to convert the following from TradingView to thinkscript
https://www.tradingview.com/script/iK7wg6w3-Rate-Of-Change-Weekly-Signals/
gC4fQbA.png

From the author:
This indicator gives a potential "buy signal" using Rate of Change of SPX and VIX together,
using the following criteria:

SPX Weekly ROC (10) has been BELOW -9 and now rises ABOVE -5
PLUS
VIX Weekly ROC (10) has been ABOVE +80 and now falls BELOW +10

The background will turn RED when ROC (SPX) is below -9 and ROC ( VIX ) is above +80.
The background will turn GREEN when ROC (SPX) is above -5 and ROC ( VIX ) is below +10.

So the potential "buy signal" is when you start to get GREEN BARS AFTER RED - usually with
some white/empty bars in between...but wait for the green. This indicates that the volatility
has settled down, and the market is starting to turn up.

This indicator gives excellent entry points, but be careful of the occasional false signals.
See Nov. 2001 and Nov. 2008, in both cases the market dropped another 25-30% before the final
bottom was formed. Always have an exit strategy, especially when buying in after a downtrend.

How I use this indicator, pretty much as shown in the preview. Weekly SPX as the main chart with
some medium/long moving averages to identify the trend, VIX added as a "Compare Symbol" in red,
and then the Weekly ROC signals below.

For the ROC graphs, you can show SPX+VIX together, SPX alone, or VIX alone. I prefer to display
them separately because they don't scale well together ( VIX crowds out the SPX when it spikes).
Background color is still based on both SPX / VIX together, regardless of which graph is shown.
Ruby:
//@version=3
study(title="Rate Of Change - Weekly Signals", shorttitle="Weekly ROC", precision=2)

//**************************************************************************************************
// Rate of Change - Weekly Signals
//
// This indicator gives a potential "buy signal" using Rate of Change of SPX and VIX together,
// using the following criteria:
//
// SPX Weekly ROC(10) has been BELOW -9 and now rises ABOVE -5
// PLUS
// VIX Weekly ROC(10) has been ABOVE +80 and now falls BELOW +10
//
// The background will turn RED when ROC(SPX) is below -9 and ROC(VIX) is above +80.
// The background will turn GREEN when ROC(SPX) is above -5 and ROC(VIX) is below +10.
//
// So the potential "buy signal" is when you start to get GREEN BARS AFTER RED - usually with
// some white/empty bars in between...but wait for the green. This indicates that the volatility
// has settled down, and the market is starting to turn up.
//
// This indicator gives excellent entry points, but be careful of the occasional false signals.
// See Nov. 2001 and Nov. 2008, in both cases the market dropped another 25-30% before the final
// bottom was formed. Always have an exit strategy, especially when buying in after a downtrend.
//
// How I use this indicator, pretty much as shown in the preview. Weekly SPX as the main chart with
// some medium/long moving averages to identify the trend, VIX added as a "Compare Symbol" in red,
// and then the Weekly ROC signals below.
//
// For the ROC graphs, you can show SPX+VIX together, SPX alone, or VIX alone. I prefer to display
// them separately because they don't scale well together (VIX crowds out the SPX when it spikes).
// Background color is still based on both SPX/VIX together, regardless of which graph is shown.
//
// Note that there is no VIX data available on Trading View prior to 1990, so for those dates the
// formula is using only ROC(SPX) and the assigned thresholds (-9 and -5, or whatever you choose).
//**************************************************************************************************

show = input(title="Show", defval="SPX+VIX", options=["SPX+VIX", "SPX", "VIX"])
length = input(title="ROC Length", defval=10, minval=1)

rocSpx = security("SPCFD:SPX", "W", roc(close, length))
rocVix = security("CBOE:VIX", "W", roc(close, length))

showSpx = (show == "SPX+VIX") or (show == "SPX")
showVix = (show == "SPX+VIX") or (show == "VIX")

plot(showSpx ? rocSpx : na, color=black, title="SPX ROC", transp=0)
plot(showVix ? rocVix : na, color=red, title="VIX ROC", transp=0)
hline(0, title="Zero Line")

spxLow = rocSpx < input(title="SPX Low", defval=-9)
spxHigh = rocSpx > input(title="SPX High", defval=-5)
vixLow = rocVix < input(title="VIX Low", defval=10)
vixHigh = rocVix > input(title="VIX High", defval=80)

score = ((spxLow ? -1 : 0) + (spxHigh ? 1 : 0) + (vixLow ? 1 : 0) + (vixHigh ? -1 : 0)) * (na(rocVix) ? 2 : 1)
col = score == -2 ? #ff0000 : score == 2 ? #00ff00 : #ffffff
bgcolor(col, 80)

//EOF
 
Last edited by a moderator:

MerryDay

Administrative
Staff member
Staff
VIP
@irishgold It is the /ES strategy, the following indicators would need to be converted and then assembled into a TradingView strategy:
Slim Ribbon
True Momentum Oscillator
RSI laguerre
Wave Trend
Money Flow Index
to name a few... :eek:
 
Last edited:

abehnam

New member
Hello. I found this indicator in TradingView and MT4 interesting. The name is Slope direction line indicator. I found a MQ4 code attached bellow. Can anyone convert it to TOS thinkscript?

Thanks
https://www.forexfactory.com/thread/166758-i-will-code-your-eas-and-indicators-for?page=1275
a1.png

//+------------------------------------------------------------------+
//| Slope Direction Line.mq4 |
//| Yuriy Tokman (YTG) |
//| http://ytg.com.ua/ |
//+------------------------------------------------------------------+
#property copyright "Yuriy Tokman (YTG)"
#property link "http://ytg.com.ua/"
#property version "1.00"
#property strict
#property indicator_chart_window
//---
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color2 Red
#property indicator_color3 Blue
#property indicator_width2 2
#property indicator_width3 2
//---
extern int period = 32;
extern double FilterNumber = 2;
extern int ma_method = 3;
extern int applied_price = 0;
//---- buffers
double B0[];
double B1[];
double B2[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
int shift_begin=int(MathSqrt(period)+period+1);
IndicatorShortName("Slope_Direction_Line("+DoubleToStr(period,0)+")");
SetIndexBuffer(0,B0);
SetIndexBuffer(1,B1);
SetIndexBuffer(2,B2);
SetIndexStyle(0,DRAW_NONE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
SetIndexDrawBegin(1,shift_begin);
SetIndexDrawBegin(2,shift_begin);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int limit=rates_total-prev_calculated;
if(prev_calculated==0)limit--;
else limit++;
//---
for(int i=0; i<limit && !IsStopped(); i++)
B0=2*MA(i,(int)MathRound((double)period/FilterNumber))-MA(i,period);
//---
for(int i=0; i<limit && !IsStopped(); i++)
B1=iMAOnArray(B0,0,(int)MathRound(MathSqrt(period)),0,ma_method,i);
//---
for(int i=0; i<limit && !IsStopped(); i++)
{
if(B1>B1[i+1]) B2=B1;
else B2=EMPTY_VALUE;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double MA(int shift,int p)
{
return(iMA(Symbol(), 0, p, 0, ma_method, applied_price, shift));
}
//+------------------------------------------------------------------+
 
Last edited by a moderator:

Similar threads

Top