Session-wise Volume Deviation Indicator: But it does not work in a scanner - ideas?

TraderZen

Member
I attempted to create a Session-wise Volume Deviation Indicator. I want to share it with the forum after is it completed.
It works for an Individual chart. Pre-requisite: The time interval of the chart should be set to 5 days or more.
Problem: The code does not work in a Scanner [as a filter criteria] or as a custom column. Any ideas about how to make it work?

---- The code ---

Code:
#  This code calculates Relative Volume Deviation from prev 5 sessions - Sessionwise.
#  The Volume deviation is calculated from the average of five prior corresponding sessions.
#  Three Sessions are Seperately calculated - Pre-Market,MainSession and After-Market.
#  There is an option to perform periodic calculations in the main session.
#  For example - hour-over-hour relative volume can also be calculated.
#  How to use this indicator:
## ** Important ** The timeframe should be set to 5-10 days for proper calculations.
## This should be used in a scanner to find stocks with unusual deviation from their mean in any session.
## Best used in Pre-Makret session to identify unusual volume activity.

Declare Lower;

Input AverageBy = {default Session, Period};
Input PeriodinMin = 60;

Def CurrentTime = getTime() / 1000 ;
Def TimeFromMidNight = SecondsfromTime(0000) ;

#-- All of the calculations will be done in seconds.
def FromMidNight = SecondsFromTime(0000);
def ToPreMktStart = (7*3600) + (30*60);
def ToSessionStart = (9*3600) + (30*60);
def ToSessionEnd = (16*3600);
def AfterHourEnd = (20*3600);

#-- Calculate relative averages for the session or for the duration
def Session_PreMkt = if FromMidNight >= ToPreMktStart and FromMidNight < TosessionStart then 1 else 0;
def session_Main  = if FromMidNight >= ToSessionStart and FromMidNight < ToSessionEnd then 1 else 0;
def Session_AfterMkt = if fromMidNight >= toSessionEnd and FromMidNight < AfterHourEnd then 1 else 0;

def newPreMktSession;
def cPreMktVolume;

def newSessionMain;
def cSessionMainVolume;

def NewAfterMktSession;
def cAfterMktVolume;

def MainSessionDuration = ToSessionEnd - ToSessionStart;
Def CycleCount = floor(MainSessionDuration/(PeriodinMin*60));
def newCycle;

Switch (AverageBy) {

    Case Session:
        newPreMktSession = Session_PreMkt and !Session_PreMkt[1];
        cPreMktVolume = if NewPreMktSession then volume else if Session_PreMkt then cPreMktVolume[1] + volume else cPreMktVolume[1];

        newSessionMain = Session_Main and !Session_Main[1];
        newCycle = double.NaN;

        cSessionMainVolume = if NewSessionMain then volume else if Session_Main then cSessionMainvolume[1] + volume else cSessionMainVolume[1];

        NewAfterMktSession = Session_AfterMkt and !Session_AfterMkt[1];
        cAfterMktVolume = if NewAfterMktSession then volume else if Session_AfterMkt then cAfterMktVolume[1] + volume else cAfterMktVolume[1];


    Case Period:

        newPreMktSession = Session_PreMkt and !Session_PreMkt[1];
        cPreMktVolume = if NewPreMktSession then volume else if Session_PreMkt then cPreMktVolume[1] + volume else cPreMktVolume[1];

         
        newSessionMain = Session_Main and !Session_Main[1];
        NewCycle = fold index = 1 to CycleCount while (Session_Main)
                     do if (TimeFromMidNight % (PeriodinMin*60)) == 0 then 1 else 0;


        cSessionMainVolume = if NewSessionMain then volume
                             else if NewCycle then volume  
                             else if Session_Main then cSessionMainvolume[1] + volume
                             else cSessionMainVolume[1];
     

        NewAfterMktSession = Session_AfterMkt and !Session_AfterMkt[1];
        cAfterMktVolume = if NewAfterMktSession then volume else if Session_AfterMkt then cAfterMktVolume[1] + volume else cAfterMktVolume[1];

}


def countPreMkt = countPreMkt[1] + if newPreMktSession then 1 else 0;
def PreMktVolume1;
def PreMktVolume2;
def PreMktVolume3;
def PreMktVolume4;
def PreMktVolume5;
if (newPreMktSession and countPreMkt > 1) {
    PreMktVolume1 = cPreMktVolume[1];
    PreMktVolume2 = PreMktVolume1[1];
    PreMktVolume3 = PreMktVolume2[1];
    PreMktVolume4 = PreMktVolume3[1];
    PreMktVolume5 = PreMktVolume4[1];
} else {
    PreMktVolume1 = PreMktVolume1[1];
    PreMktVolume2 = PreMktVolume2[1];
    PreMktVolume3 = PreMktVolume3[1];
    PreMktVolume4 = PreMktVolume4[1];
    PreMktVolume5 = PreMktVolume5[1];
}


def countSessionMain = countSessionMain[1] + if newSessionMain then 1 else 0;
def MainSessionVolume1;
def MainSessionVolume2;
def MainSessionVolume3;
def MainSessionVolume4;
def MainSessionVolume5;
if (newSessionMain and countSessionMain > 1) {
    MainSessionVolume1 = cSessionMainVolume[1];
    MainSessionVolume2 = MainSessionVolume1[1];
    MainSessionVolume3 = MainSessionVolume2[1];
    MainSessionVolume4 = MainSessionVolume3[1];
    MainSessionVolume5 = MainSessionVolume4[1];
} else {
    MainSessionVolume1 = MainSessionVolume1[1];
    MainSessionVolume2 = MainSessionVolume2[1];
    MainSessionVolume3 = MainSessionVolume3[1];
    MainSessionVolume4 = MainSessionVolume4[1];
    MainSessionVolume5 = MainSessionVolume5[1];
}


def countAfterMkt = countAfterMkt[1] + if newAfterMktSession then 1 else 0;
def AfterMktVolume1;
def AfterMktVolume2;
def AfterMktVolume3;
def AfterMktVolume4;
def AfterMktVolume5;
if (newAfterMktSession and countAfterMkt > 1) {
    AfterMktVolume1 = cAfterMktVolume[1];
    AfterMktVolume2 = AfterMktVolume1[1];
    AfterMktVolume3 = AfterMktVolume2[1];
    AfterMktVolume4 = AfterMktVolume3[1];
    AfterMktVolume5 = AfterMktVolume4[1];
} else {
    AfterMktVolume1 = AfterMktVolume1[1];
    AfterMktVolume2 = AfterMktVolume2[1];
    AfterMktVolume3 = AfterMktVolume3[1];
    AfterMktVolume4 = AfterMktVolume4[1];
    AfterMktVolume5 = AfterMktVolume5[1];
}


def CumulativePreMktVolume = if Session_PreMkt then cPreMktVolume else Double.Nan;
def CumulativeMainSessionVolume = if Session_Main then cSessionMainVolume else Double.Nan;
def CumulativeAfterMktVolume = if Session_AfterMkt then cAfterMktVolume else Double.Nan;

def AveragePreMktVolume = if countPreMkt > 5 then (PreMktVolume1 + PreMktVolume2 + PreMktVolume3 + PreMktVolume4 + PreMktVolume5) / 5 else Double.NaN;
def AverageMainSessionVolume = if countSessionMain > 5 then (MainSessionVolume1 + MainSessionVolume2 + MainSessionVolume3 + MainSessionVolume4 + MainSessionVolume5)/5 else Double.NaN;
def AverageAfterMktVolume = if countAfterMkt > 5 then (AfterMktVolume1 + AfterMktVolume2 + AfterMktVolume3 + AfterMktVolume4 + AfterMktVolume5) / 5 else Double.Nan;


Def PreMktDeviation = if (!isNan(CumulativePreMktVolume) and !isNan(AveragePreMktVolume)) then ((CumulativePreMktVolume - AveragePreMktVolume)/AveragePreMktVolume) * 100 else double.NaN;
plot PreMktVolumeDeviation = PreMktDeviation;

Def MainSessionDeviation = if (!isNan(CumulativeMainSessionVolume) and !isNan(AverageMainSessionVolume)) then ((CumulativeMainSessionVolume - AverageMainSessionVolume)/AverageMainSessionVolume) * 100 else double.nan;
Plot MainSessionVolumeDeviation = MainSessionDeviation;


def AfterMktDeviation = if (!isNan(CumulativeAfterMktVolume) and !isNan(AverageAfterMktVolume)) then ((CumulativeAfterMktVolume - AverageAfterMktVolume)/AverageAfterMktVolume) * 100 else double.Nan;
plot AfterMktVolumeDeviation = AfterMktDeviation;
 

plot zeroline = 0;
zeroline.setPaintingStrategy(paintingStrategy.LINE);

PreMktVolumeDeviation.DefineColor("Below", GetColor(0));
PreMktVolumeDeviation.DefineColor("Above", GetColor(1));
PreMktVolumeDeviation.AssignValueColor(if PreMktVolumeDeviation >= 0 then PreMktVolumeDeviation.Color("Above") else PreMktVolumeDeviation.Color("Below"));
PreMktVolumeDeviation.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);

MainSessionVolumeDeviation.DefineColor("Below", GetColor(0));
MainSessionVolumeDeviation.DefineColor("Above", GetColor(1));
MainSessionVolumeDeviation.AssignValueColor(if MainSessionVolumeDeviation >= 0 then MainSessionVolumeDeviation.Color("Above") else MainSessionVolumeDeviation.Color("Below"));
MainSessionVolumeDeviation.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);

AfterMktVolumeDeviation.DefineColor("Below", GetColor(0));
AfterMktVolumeDeviation.DefineColor("Above", GetColor(1));
AfterMktVolumeDeviation.AssignValueColor(if AfterMktVolumeDeviation >= 0 then AfterMktVolumeDeviation.Color("Above") else AfterMktVolumeDeviation.Color("Below"));
AfterMktVolumeDeviation.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);

# - End
--- End code ---
 
Last edited:
Solution
## ** Important ** The timeframe should be set to 5-10 days for proper calculations.

I ran into similar problems with a similar script of my own. I eventually wrote a script designed to count the number of bars and how many days worth of data are available to the scanner. It turns out there is only about five days worth of historical data available to the scanner on sub-hourly intraday aggregations. The documentation says its longer than that, but this is out of date. This is very likely the culprit, but I haven't examined your script in detail either.

What aggregation are you setting the scan to? If its less than hourly, try checking today against the previous three days, for a total of four, and leave off that final fifth...
## ** Important ** The timeframe should be set to 5-10 days for proper calculations.

I ran into similar problems with a similar script of my own. I eventually wrote a script designed to count the number of bars and how many days worth of data are available to the scanner. It turns out there is only about five days worth of historical data available to the scanner on sub-hourly intraday aggregations. The documentation says its longer than that, but this is out of date. This is very likely the culprit, but I haven't examined your script in detail either.

What aggregation are you setting the scan to? If its less than hourly, try checking today against the previous three days, for a total of four, and leave off that final fifth day. There is no guarantee that the fifth day is complete or begins where you would like it too on that loose end. You need a safety buffer, for lack of a better word.
 
Solution
I ran into similar problems with a similar script of my own. I eventually wrote a script designed to count the number of bars and how many days worth of data are available to the scanner. It turns out there is only about five days worth of historical data available to the scanner on sub-hourly intraday aggregations. The documentation says its longer than that, but this is out of date. This is very likely the culprit, but I haven't examined your script in detail either.

What aggregation are you setting the scan to? If its less than hourly, try checking today against the previous three days, for a total of four, and leave off that final fifth day. There is no guarantee that the fifth day is complete or begins where you would like it too on that loose end. You need a safety buffer, for lack of a better word.
Thank you for your insight Joshua!
Default setting was at Day level, given your explanation I have decided to use this as a intraday scanner instead - and it works fine on less than or equal to 30 min setting. Both the filter and the custom column work!
NzJhDsn.png
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
430 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