A Volume Pressure Moving Average For ThinkOrSwim

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

I found this Cumulative Vol Indicator on TV. Looks actually really good! It can filter wrong entries and keep you on the right side of the market.

@samer800 I know you are a wizard at this! If you have time, can you take a look at this one. I would really appreciate it!

Thank you in advance!

Source: https://www.tradingview.com/script/lsDHdn0H-Cumulative-Volume-Delta/

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

//@version=4
study("Cumulative Volume Delta")

upper_wick = close>open ? high-close : high-open
lower_wick = close>open ? open-low : close-low
spread = high-low
body_length = spread - (upper_wick + lower_wick)

percent_upper_wick = upper_wick/spread
percent_lower_wick = lower_wick/spread
percent_body_length = body_length/spread


buying_volume = close>open ? (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume : ((percent_upper_wick + percent_lower_wick)/2) * volume
selling_volume = close<open ? (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume : ((percent_upper_wick + percent_lower_wick)/2) * volume

cumulation_length = input(14)
cumulative_buying_volume = ema(buying_volume,cumulation_length)
cumulative_selling_volume = ema(selling_volume,cumulation_length)

fill_color = cumulative_buying_volume > cumulative_selling_volume ? color.green : cumulative_buying_volume < cumulative_selling_volume ? color.red : color.yellow

pb = plot(cumulative_buying_volume, color=color.green , transp=70)
ps = plot(cumulative_selling_volume, color=color.red , transp=70)

fill(pb, ps, color = fill_color)

volume_strength_wave = cumulative_buying_volume > cumulative_selling_volume ? cumulative_buying_volume : cumulative_selling_volume
ema_volume_strength_wave = ema(volume_strength_wave , cumulation_length)
plot(ema_volume_strength_wave, color=color.gray, transp=80)

cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume
plot(cumulative_volume_delta, color= cumulative_volume_delta>0 ? color.green : color.red, style=plot.style_columns, transp=61)
find the below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © Ankit_1618
#study("Cumulative Volume Delta")
# Converted by Sam4Cok@Samer800    - Request from useThinkScript.com member
declare Lower;

input cumulation_length = 14;
input movAvgType = AverageType.EXPONENTIAL;

def upper_wick = if close>open then high-close else high-open;
def lower_wick = if close>open then open-low else close-low;
def spread = high-low;
def body_length = spread - (upper_wick + lower_wick);

def percent_upper_wick = upper_wick/spread;
def percent_lower_wick = lower_wick/spread;
def percent_body_length = body_length/spread;

def buying_volume = if close>open then
               (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume else
               ((percent_upper_wick + percent_lower_wick)/2) * volume;

def selling_volume = if close<open then
                (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume else
                ((percent_upper_wick + percent_lower_wick)/2) * volume;

def cumulative_buying_volume = MovingAverage(movAvgType, buying_volume,cumulation_length);
def cumulative_selling_volume = MovingAverage(movAvgType, selling_volume,cumulation_length);

AddCloud(cumulative_buying_volume, cumulative_selling_volume, Color.DARK_GREEN, Color.DARK_RED, yes);


def volume_strength_wave = if cumulative_buying_volume > cumulative_selling_volume then
                          cumulative_buying_volume else cumulative_selling_volume;
def ema_volume_strength_wave = MovingAverage(movAvgType, volume_strength_wave , cumulation_length);

plot emaVol = ema_volume_strength_wave;
emaVol.SetDefaultColor(Color.GRAY);

def cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume;

plot CumVolDeltaHist = cumulative_volume_delta;#, color= cumulative_volume_delta>0 ? color.green : color.red, style=plot.style_columns, transp=61)
CumVolDeltaHist.AssignValueColor(if cumulative_volume_delta>0 then Color.GREEN else Color.RED);
CumVolDeltaHist.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);

#-- END of CODE
 
I found this Cumulative Vol Indicator on TV. Looks actually really good! It can filter wrong entries and keep you on the right side of the market.

@samer800 I know you are a wizard at this! If you have time, can you take a look at this one. I would really appreciate it!

Thank you in advance!

Source: https://www.tradingview.com/script/lsDHdn0H-Cumulative-Volume-Delta/
Hello @Luna. I copied the indicator into ToS (thanks t0 Sam4Cok). How do you use it to help with your technical analysis?
 
Hi @samer800, thanks for converting to TOS. Is it possible to add into the code signals to spot Divergence? I am using a Range timeframe of 40 Ticks - to 90 Days with this Cumulative Vol delta, and I see a divergence in the reversals. See below:

Is it possible to code?
@chewie76 @MerryDay
Thanks

How are you distinguishing a useful divergence from one that gives false signals? For example at 10:01 on the x-axis of your screenshot the histogram bars move in the opposite direction of the price candles but that’s not a reversal point. It seems like without cherry picking the divergences with hindsight, they’re not reliable - unless I’m missing something?
 
Last edited by a moderator:
How are you distinguishing a useful divergence from one that gives false signals? For example at 10:01 on the x-axis of your screenshot the histogram bars move in the opposite direction of the price candles but that’s not a reversal point. It seems like without cherry picking the divergences with hindsight, they’re not reliable - unless I’m missing something?
There is no holy grail anywhere that plots 100% accurate signals. It's not a false signal if you don't trade blindly and let the price action tell you what to do instead.
 
Last edited by a moderator:
Hi @samer800, thanks for converting to TOS. Is it possible to add into the code signals to spot Divergence? I am using a Range timeframe of 40 Ticks - to 90 Days with this Cumulative Vol delta, and I see a divergence in the reversals. See below:

Is it possible to code?
@chewie76 @MerryDay @halcyonguy @rad14733 @SleepyZ @Joshua @mashume @horserider
Thanks
add the below at the end of the code:

CSS:
#----Div-----------
input LookBackRight  = 5; # "Pivot Lookback Right"
input LookBackLeft  = 5;  # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = cumulative_volume_delta;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL + 1 and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL + 1 and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound1 = if plFound then divSrc else vlFound1[1];
def vlFound_ = if vlFound1==0 then divSrc[1] else vlFound1;
def vlFound = if vlFound_!=vlFound_[1] then vlFound_[1] else vlFound[1];
#valuewhen(plFound, divSrc, MinLookback, MaxLookback, 1);
def vhFound1 = if phFound then divSrc else vhFound1[1];
def vhFound_ = if vhFound1==0 then divSrc[1] else vhFound1;
def vhFound = if vhFound_!=vhFound_[1] then vhFound_[1] else vhFound[1];
#valuewhen(phFound, divSrc, MinLookback, MaxLookback, 1);
def plPrice1 = if plFound then l else plPrice1[1];
def plPrice_ = if plPrice1 == 0 then l[1] else plPrice1;
def plPrice = if plPrice_!=plPrice_[1] then plPrice_[1] else plPrice[1];
#valuewhen(plFound, l, MinLookback, MaxLookback, 1);
def phPrice1 = if phFound then h else phPrice1[1];
def phPrice_ = if phPrice1==0 then h[1] else phPrice1;
def phPrice = if phPrice_!=phPrice_[1] then phPrice_[1] else phPrice[1];
#valuewhen(phFound, h, MinLookback, MaxLookback, 1);

#// Regular Bullish
def inRangePl = _inRange(plFound[1],MaxLookback,MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = l > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1],MaxLookback,MinLookback);
def oscLH   = divSrc < vhFound and inRangePh;
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);


#----End
 
Last edited by a moderator:
Hey @samer800, Thanks for putting time into the div development; Is it possible to enable the divergence in all places where there is a change of Vol (white circles)?

3fSQkDu.png


Notice that the divergence also occurs in two bull Volume bars or two bear bars and does not necessarily need to be when the Volume bar changes from Bull to Bear or Bear to Bull.

See that the reversal is also more pronounced when the difference in volume bar height is more significant (also seen in the white circles of the screenshot) - maybe that can be measured by calculating the angle of the two-volume bar height. Can we add an input to adjust the delta change to filter out only the most considerable vol changes?

This version of the indicator (https://tos.mx/FLkNIyY) was made thanks to @chewie76.

Ruby:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © Ankit_1618
#study("Cumulative Volume Delta")
# Converted by Sam4Cok@Samer800    - Request from useThinkScript.com member
declare Lower;

input cumulation_length = 14;
input movAvgType = AverageType.EXPONENTIAL;

def upper_wick = if close>open then high-close else high-open;
def lower_wick = if close>open then open-low else close-low;
def spread = high-low;
def body_length = spread - (upper_wick + lower_wick);

def percent_upper_wick = upper_wick/spread;
def percent_lower_wick = lower_wick/spread;
def percent_body_length = body_length/spread;

def buying_volume = if close>open then
               (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume else
               ((percent_upper_wick + percent_lower_wick)/2) * volume;

def selling_volume = if close<open then
                (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume else
                ((percent_upper_wick + percent_lower_wick)/2) * volume;

def cumulative_buying_volume = MovingAverage(movAvgType, buying_volume,cumulation_length);
def cumulative_selling_volume = MovingAverage(movAvgType, selling_volume,cumulation_length);

#AddCloud(cumulative_buying_volume, cumulative_selling_volume, Color.DARK_GREEN, Color.DARK_RED, yes);


def volume_strength_wave = if cumulative_buying_volume > cumulative_selling_volume then
                          cumulative_buying_volume else cumulative_selling_volume;
def ema_volume_strength_wave = MovingAverage(movAvgType, volume_strength_wave , cumulation_length);

def emaVol = ema_volume_strength_wave;
#emaVol.SetDefaultColor(Color.GRAY);

def cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume;

plot CumVolDeltaHist = cumulative_volume_delta;#, color= cumulative_volume_delta>0 ? color.green : COLOR.DARK_RED, style=plot.style_columns, transp=61)
#CumVolDeltaHist.AssignValueColor(if cumulative_volume_delta>0 then Color.GREEN else COLOR.DARK_RED);
CumVolDeltaHist.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);

CumVolDeltaHist.DefineColor("Positive and Up", Color.dark_GREEN);
CumVolDeltaHist.DefineColor("Positive and Down", Color.light_green);
CumVolDeltaHist.DefineColor("Negative and Down", COLOR.DARK_RED);
CumVolDeltaHist.DefineColor("Negative and Up", Color.orange);
CumVolDeltaHist.AssignValueColor(if CumVolDeltaHist >= 0 then if CumVolDeltaHist > CumVolDeltaHist[1] then CumVolDeltaHist.Color("Positive and Up") else CumVolDeltaHist.Color("Positive and Down") else if CumVolDeltaHist < CumVolDeltaHist[1] then CumVolDeltaHist.Color("Negative and Down") else CumVolDeltaHist.Color("Negative and Up"));

plot UpSignal = if CumVolDeltaHist crosses above 0 then 0 else Double.NaN;
plot DownSignal = if CumVolDeltaHist crosses below 0 then 0 else Double.NaN;
UpSignal.SetDefaultColor(Color.WHITE);
UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
Upsignal.setlineWeight(1);
DownSignal.SetDefaultColor(Color.WHITE);
DownSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
Downsignal.setlineWeight(1);
Upsignal.HideBubble();
Upsignal.HideTitle();
Downsignal.HideBubble();
Downsignal.HideTitle();

#----Div-----------
input LookBackRight  = 5; # "Pivot Lookback Right"
input LookBackLeft  = 5;  # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = cumulative_volume_delta;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL + 1 and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL + 1 and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound1 = if plFound then divSrc else vlFound1[1];
def vlFound_ = if vlFound1==0 then divSrc[1] else vlFound1;
def vlFound = if vlFound_!=vlFound_[1] then vlFound_[1] else vlFound[1];
#valuewhen(plFound, divSrc, MinLookback, MaxLookback, 1);
def vhFound1 = if phFound then divSrc else vhFound1[1];
def vhFound_ = if vhFound1==0 then divSrc[1] else vhFound1;
def vhFound = if vhFound_!=vhFound_[1] then vhFound_[1] else vhFound[1];
#valuewhen(phFound, divSrc, MinLookback, MaxLookback, 1);
def plPrice1 = if plFound then l else plPrice1[1];
def plPrice_ = if plPrice1 == 0 then l[1] else plPrice1;
def plPrice = if plPrice_!=plPrice_[1] then plPrice_[1] else plPrice[1];
#valuewhen(plFound, l, MinLookback, MaxLookback, 1);
def phPrice1 = if phFound then h else phPrice1[1];
def phPrice_ = if phPrice1==0 then h[1] else phPrice1;
def phPrice = if phPrice_!=phPrice_[1] then phPrice_[1] else phPrice[1];
#valuewhen(phFound, h, MinLookback, MaxLookback, 1);

#// Regular Bullish
def inRangePl = _inRange(plFound[1],MaxLookback,MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = l > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1],MaxLookback,MinLookback);
def oscLH   = divSrc < vhFound and inRangePh;
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
#addchartbubble(bullCond, divSrc, "D", color.GREEN, no);
#addchartbubble(bearCond, divSrc, "D", CreateColor(156,39,176), yes);
#addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
#addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);


#----End

# DIVERGENCE

input divergenceLength = 5; #hint divergenceLength: The number of bars used to calculate divergences.

input divergenceType = {default regular, reverse}; #hint divergenceType: The type of divergence. A regular divergence is when price is making higher highs (or lower lows), while the indicator is making lower highs (or higher lows). A reverse divergence (also called a hidden divergence) is when the indicator is making higher highs (or lower lows), while price is making lower highs (or higher lows).
#Hint: The output of this indicator is for informational and educational use only, is not an investment recommendation or advice, and should not be relied upon in making the decision to buy or sell a security or pursue a particular investment strategy.

def xDownBars;
def xUpBars;
def xDowns;
def xUps;
def hiBars;
def loBars;
def pivotTop;
def pivotBottom;
def hiInd;
def loInd;
def hiPrice;
def loPrice;
plot bearishd;
plot bullishd;

def K = CumVolDeltaHist;
def Over_Boughta = 5;
def Over_Solda = -5;

#K.SetDefaultColor(color.white);
#K.SetLineWeight(2);

def ind;
ind = k;

# Bearish
pivotTop =
if
    divergenceType == divergenceType.regular
then
    ind[1] > over_Boughta and ind[1] == Highest(ind, divergenceLength + 1)
else
    ind[1] >= 50 and
    ind[1] == highest(ind, divergenceLength + 1) and
    ind[1] == highest(ind, divergenceLength+1)[-divergenceLength+1];

if pivotTop
then {
    hiBars = 1;
    hiInd = ind[1];
    hiPrice = max(high[2], max(high[1], high[0]));
}
else {
    hiBars = hiBars[1] + 1;
    hiInd = hiInd[1];
    hiPrice = hiPrice[1];
}

if ind[1] crosses below  Over_Boughta
then {
    xDownBars = 1;
    xDowns = xDowns[1] + 1;
}
else {
    xDownBars = xDownBars[1] + 1;
    xDowns = if pivotTop[1] then 0 else xDowns[1];
}

def bearCond1;
switch (divergenceType) {
case regular:
bearCond1 =
    ind[1] >= 0 and
    ind < ind[1] and
    high[1] == Highest(high, divergenceLength + 1) and
    hiBars[1] > xDownBars[1] and
    xDowns == 1 and
    close < close[1] and
    hiPrice[1] < high[1] and
    hiInd[1] > ind[1];
case reverse:
bearCond1 =
    ind[1] >= 0 and
    ind < ind[1] and
#    high[1] == Highest(high, divergenceLength) and
#    hiBars[1] > xDownBars[1] and
#    xDowns == 1 and
    close < close[1] and
    hiPrice[1] > high[1] and hiPrice[1] > high and
    hiInd[1] < ind[1];}

bearishd =
    if
        bearCond
    then
        ind[1]
    else
        Double.NaN;;

bearishd.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
bearishd.SetDefaultColor(Color.CYAN);
bearishd.setLineWeight(2);
bearishd.hideTitle();
bearishd.hideBubble();

def countBear = if bearCond[-1] then countBear[1] + 1 else countBear[1];
def recentBear = countBear == HighestAll(countBear);
def secHigh = highestAll(if bearCond[-1] and recentBear then ind else Double.NaN);
#def firstHigh = highestAll(if bearCond and recentBear and ind[1] == secHigh then hiInd[1] else double.NaN);
def FH_bar = highestAll(if recentBear and bearCond[-1] and ind == secHigh then getvalue(barNumber(), hibars) else double.NaN);

plot bearTrendline =
if
    recentBear and bearCond[-1] and ind == secHigh
then
    max(ind[1], ind[0])
else
#    if pivotTop and hiInd == firstHigh
    if
        FH_bar == barNumber()
    then
        ind
    else
        double.NaN;
bearTrendline.EnableApproximation();
bearTrendline.setDefaultColor(COLOR.DARK_RED);
bearTrendline.setLineWeight(4);
bearTrendline.hideBubble();
bearTrendline.hideTitle();

#Bullish
pivotBottom =
if
    divergenceType == divergenceType.regular
then
    ind[1] < over_Solda and ind[1] == lowest(ind, divergenceLength + 1)
else
    ind[1] <= 50 and
    ind[1] == lowest(ind, divergenceLength+1) and
    ind[1] == lowest(ind, divergenceLength+1)[-divergenceLength+1];

if pivotBottom
then {
    loBars = 1;
    loInd = ind[1];
    loPrice = min(low[2], min(low[1], low[0]));
}
else {
    loBars = loBars[1] + 1;
    loInd = loInd[1];
    loPrice = loPrice[1];
}

if ind[1] crosses above over_Solda
then {
    xUpBars = 1;
    xUps = xUps[1] + 1;
}
else {
    xUpBars = xUpBars[1] + 1;
    xUps = if pivotBottom[1] then 0 else xUps[1];
}

def bullCond1;
switch (divergenceType){
case regular:
bullCond1 =
    ind[1] <= 0 and
    ind > ind[1] and     
    low[1] == Lowest(low, divergenceLength + 1) and
    loBars[1] > xUpBars[1] and
    xUps == 1 and
    close > close[1] and
    loPrice[1] > low[1] and
    loInd[1] < ind[1];
case reverse:
bullCond1 =
    ind[1] <= 0 and
    ind > ind[1] and     
#    low[1] == Lowest(low, divergenceLength) and
#    loBars[1] > xUpBars[1] and
#    xUps == 1 and
    close > close[1] and
    loPrice[1] < low[1] and loPrice[1] < low and
    loInd[1] > ind[1];}

bullishd =
    if
        bullCond
    then
        ind[1]
    else
        Double.NaN;

bullishd.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
bullishd.SetDefaultColor(Color.CYAN);
bullishd.setLineWeight(2);
bullishd.HideTitle();
bullishd.HideBubble();

def countBull = if bullCond[-1] then countBull[1] + 1 else countBull[1];
def recentBull = countBull == HighestAll(countBull);
def secLow = highestAll(if bullCond[-1] and recentBull then ind else Double.NaN);
#def firstLow = highestAll(if bullCond and recentBull and ind[1] == secLow then loInd[1] else double.NaN);
def FL_bar = highestAll(if recentBull and bullCond[-1] and ind == secLow then getvalue(barNumber(), lobars) else double.NaN);

plot bullTrendline =
    if
        recentBull and bullCond[-1] and ind == secLow
    then
        min(ind[1], ind[0])
    else
        if
#            pivotBottom and loInd == firstLow
            FL_bar == barNumber()
        then
            ind[0]
        else
            double.NaN;
bullTrendline.EnableApproximation();
bullTrendline.setDefaultColor(color.GREEN);
bullTrendline.setLineWeight(4);
bullTrendline.hideBubble();
bullTrendline.hideTitle();


Let me know if these updates can be applied.

Thanks so much
 
can someone explain on how to use this? for a 5 min timeframe? what am i looking for?
This is a moving average indicator with a lookback of 14.
It wouldn't be used on charts of 5min due to the lag.

A large percentage of indicators on this forum are lagging indicators and thus not appropriate for scalper's aggregations.

Read more to see if you are trading on the right timeframe:
https://usethinkscript.com/threads/best-time-frame-for-trading-for-thinkorswim.12209/
 
@samer800 is it possible to have input for lines on this at a given high/low level and alert. For instance, for SPY, I'd like to set lines at 30,000/-30000 and alert when the that is crossed?
 
@samer800 is it possible to have input for lines on this at a given high/low level and alert. For instance, for SPY, I'd like to set lines at 30,000/-30000 and alert when the that is crossed?
add this at the end of the code.

CSS:
input threshold1 = 30000;
input threshold2 = -30000;

plot Line1 = threshold1;
plot Line2 = threshold2;
 
find the below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © Ankit_1618
#study("Cumulative Volume Delta")
# Converted by Sam4Cok@Samer800    - Request from useThinkScript.com member
declare Lower;

input cumulation_length = 14;
input movAvgType = AverageType.EXPONENTIAL;

def upper_wick = if close>open then high-close else high-open;
def lower_wick = if close>open then open-low else close-low;
def spread = high-low;
def body_length = spread - (upper_wick + lower_wick);

def percent_upper_wick = upper_wick/spread;
def percent_lower_wick = lower_wick/spread;
def percent_body_length = body_length/spread;

def buying_volume = if close>open then
               (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume else
               ((percent_upper_wick + percent_lower_wick)/2) * volume;

def selling_volume = if close<open then
                (percent_body_length + (percent_upper_wick + percent_lower_wick)/2)*volume else
                ((percent_upper_wick + percent_lower_wick)/2) * volume;

def cumulative_buying_volume = MovingAverage(movAvgType, buying_volume,cumulation_length);
def cumulative_selling_volume = MovingAverage(movAvgType, selling_volume,cumulation_length);

AddCloud(cumulative_buying_volume, cumulative_selling_volume, Color.DARK_GREEN, Color.DARK_RED, yes);


def volume_strength_wave = if cumulative_buying_volume > cumulative_selling_volume then
                          cumulative_buying_volume else cumulative_selling_volume;
def ema_volume_strength_wave = MovingAverage(movAvgType, volume_strength_wave , cumulation_length);

plot emaVol = ema_volume_strength_wave;
emaVol.SetDefaultColor(Color.GRAY);

def cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume;

plot CumVolDeltaHist = cumulative_volume_delta;#, color= cumulative_volume_delta>0 ? color.green : color.red, style=plot.style_columns, transp=61)
CumVolDeltaHist.AssignValueColor(if cumulative_volume_delta>0 then Color.GREEN else Color.RED);
CumVolDeltaHist.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);

#-- END of CODE
Hi @samer800, can the volume histogram be scaled from -100 to 100? That way, it is easier to combine with other indicators. Thanks
 
I am not a coder by any means of the imaginatoion lol, but i see quite a few people in here are absolutely incredible. Is it possible someone could take this tradingview Cumulative Volume Delta and convert it to TOS? I realize TOS nor tradingview provide real tick data but this is the best workaround i've seen. I've looked throught this site and searched and there is many flavors of something similar here already but nothing like this. Any help would be greatly appreciated. Thanks in advance.

https://www.tradingview.com/v/lsDHdn0H/
 

Attachments

  • Screen Shot 2023-11-21 at 2.46.05 PM.png
    Screen Shot 2023-11-21 at 2.46.05 PM.png
    168.5 KB · Views: 123
Last edited by a moderator:
# Cumulative Volume Delta
# This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
# © Ankit_1618 converted by Zlotko

declare upper;

# Calculate upper_wick, lower_wick, spread, and body_length
def upper_wick = if close > open then high - close else high - open;
def lower_wick = if close > open then open - low else close - low;
def spread = high - low;
def body_length = spread - (upper_wick + lower_wick);

# Calculate percent_upper_wick, percent_lower_wick, and percent_body_length
def percent_upper_wick = upper_wick / spread;
def percent_lower_wick = lower_wick / spread;
def percent_body_length = body_length / spread;

# Calculate buying_volume and selling_volume
def buying_volume = if close > open then (percent_body_length + (percent_upper_wick + percent_lower_wick) / 2) * volume else ((percent_upper_wick + percent_lower_wick) / 2) * volume;
def selling_volume = if close < open then (percent_body_length + (percent_upper_wick + percent_lower_wick) / 2) * volume else ((percent_upper_wick + percent_lower_wick) / 2) * volume;

# Input for cumulation_length
input cumulation_length = 14;

# Calculate cumulative_buying_volume and cumulative_selling_volume using EMA
def cumulative_buying_volume = ExpAverage(buying_volume, cumulation_length);
def cumulative_selling_volume = ExpAverage(selling_volume, cumulation_length);

# Calculate cumulative_volume_delta
def cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume;

# Plot histograms to represent cumulative volume delta
plot hist = cumulative_volume_delta;
hist.AssignValueColor(if cumulative_volume_delta > 0 then color.green else color.red);
hist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
hist.SetLineWeight(1);
hist.SetDefaultColor(GetColor(1));
hist.SetStyle(Curve.FIRM);

# Calculate volume_strength_wave and plot its EMA
def volume_strength_wave = if cumulative_buying_volume > cumulative_selling_volume then cumulative_buying_volume else cumulative_selling_volume;
def ema_volume_strength_wave = ExpAverage(volume_strength_wave, cumulation_length);
#plot ema_volume_strength_wave(color = color.gray, transp = 80);
 
add the below at the end of the code:

CSS:
#----Div-----------
input LookBackRight  = 5; # "Pivot Lookback Right"
input LookBackLeft  = 5;  # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = cumulative_volume_delta;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL + 1 and dat == Highest(dat, lbL + 1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL + 1 and dat == Lowest(dat, lbL + 1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound1 = if plFound then divSrc else vlFound1[1];
def vlFound_ = if vlFound1==0 then divSrc[1] else vlFound1;
def vlFound = if vlFound_!=vlFound_[1] then vlFound_[1] else vlFound[1];
#valuewhen(plFound, divSrc, MinLookback, MaxLookback, 1);
def vhFound1 = if phFound then divSrc else vhFound1[1];
def vhFound_ = if vhFound1==0 then divSrc[1] else vhFound1;
def vhFound = if vhFound_!=vhFound_[1] then vhFound_[1] else vhFound[1];
#valuewhen(phFound, divSrc, MinLookback, MaxLookback, 1);
def plPrice1 = if plFound then l else plPrice1[1];
def plPrice_ = if plPrice1 == 0 then l[1] else plPrice1;
def plPrice = if plPrice_!=plPrice_[1] then plPrice_[1] else plPrice[1];
#valuewhen(plFound, l, MinLookback, MaxLookback, 1);
def phPrice1 = if phFound then h else phPrice1[1];
def phPrice_ = if phPrice1==0 then h[1] else phPrice1;
def phPrice = if phPrice_!=phPrice_[1] then phPrice_[1] else phPrice[1];
#valuewhen(phFound, h, MinLookback, MaxLookback, 1);

#// Regular Bullish
def inRangePl = _inRange(plFound[1],MaxLookback,MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = l > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1],MaxLookback,MinLookback);
def oscLH   = divSrc < vhFound and inRangePh;
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);


#----End
can you make these arrows instead of chart bubbles? Please and thanks either way.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
301 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top