Returning True For Current Candle and Every Same Candle For Prior Days

I'm trying to figure out how I can write thinkscript to return true for the current candle and every candle of the same time period on the chart, and then automatically roll forward as time progresses. For example, If the current time was 10:00AM, It would return true for every 10:00AM candle, and then when it changed to 10:01, all of the 10:01 candles would return true.

Any thoughts on if this is possible?
 
Last edited:
Solution
Wow Josh thank you so much. That is exactly what I was looking for.

I spent the morning trying to implement it into the code I posted above. Unfortunately, it renders it too slow to be useful. I think because the frequent updating to pull in tick-by-tick volume data causes the complex code to re-run every tick and it can't keep up.

If there was a way to prevent your section of code from refreshing until the new candle is created, I think that would solve the problem.

Here is the code that combines the two:
Code:
declare on_volume;
declare zerobase;

input includeCurrentDayInAvg = no;
input barsToBeIncluded = {default OnlyCurrentBar, CurrentAndBefore, CurrentAndAfter};
input includePremarket = no;
input includePostmarket = no;
input...
When I plot this on the chart, it returns 9:30.

plot time = gettime();
plot open = RegularTradingStart(GetYYYYMMDD()) + 1;
addverticalline( time == open);

However, I'm stumped as far as how to manipulate it to move as the candles move.
 

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

You can use the SecondsTillTime() and SecondsFromTime() functions to locate the 10:00 candles:
Code:
def TenOclock = if SecondsTillTime(1000) == 0 and SecondsFromTime(1000) == 0 then 1 else 0;

def TenClose = if TenOclock == 1 then CLOSE else double.nan;

plot Ten = TenClose;

Then you can do whatever you want with the data in the TenClose holder.

Happy Trading,
Mashume
 
You can use the SecondsTillTime() and SecondsFromTime() functions to locate the 10:00 candles:
Code:
def TenOclock = if SecondsTillTime(1000) == 0 and SecondsFromTime(1000) == 0 then 1 else 0;

def TenClose = if TenOclock == 1 then CLOSE else double.nan;

plot Ten = TenClose;

Then you can do whatever you want with the data in the TenClose holder.

Happy Trading,
Mashume

I'm trying to get it to move automatically as the day progresses. So It would return true for every 10:00 candle, and then automatically switch to 10:01, etc without having to go in and update the code every minute. I updated the question so that it's clearer.
 
We can solve for the current time like this:
Code:
def timeNow = (getTime());
def hour = (timeNow % 86400) / 3600;
def minute = (timeNow % 86400) / 60 / 60 / 24 * 60;
 
def hourmin = hour * 100 + minute;

def TenOclock = if SecondsTillTime(hourmin) == 0 and SecondsFromTime(hourmin) == 0 then 1 else 0;

BUT

ToS won't let us use a variable in the Seconds functions...
'''
Only constants expected here: hourmin CL constant function parameter 'tillTime' at 16:36
Only constants expected here: hourmin CL constant function parameter 'fromTime' at 16:70
Only constants expected here: hourmin CL constant function parameter 'tillTime' at 16:36
Only constants expected here: hourmin CL constant function parameter 'fromTime' at 16:70'''

So there really isn't a good way to go about what you're looking for that I can see.

Not so helpful, but perhaps a little bit.

-mashume


EDIT:
Looking at the math for determining hours and minutes, I'm not sure I've got the minutes worked out quite right... use at your own risk
 
Last edited:
Yeah unfortunately that's the issue I'm running into as well. Still working through one possibility but I doubt it's going to work. It's a shame because it would be nice to get price and volume averages for each candle.
 
Here is the code I've settled on. If anyone knows of a way to have the time variable roll forward automatically, I would be eternally grateful if you shared.

Code:
declare on_volume;
declare zerobase;

input time = 0930;
input barwidth = 3;
input showVolume = yes;
input highlightDataPoints = yes;

def TimeBarWeAreLookingFor = SecondsTillTime(time) == 0;

def CurrentDay = GetDay() == GetLastDay();   #this removes current bar from average.

def NumOfInstances = if TimeBarWeAreLookingFor and CurrentDay == no
            then NumOfInstances[1] + 1
            else NumOfInstances[1];

def CumVol = if NumOfInstances != NumOfInstances[1]
                then CumVol[1] + volume
                else CumVol[1];

addverticalline(highlightDataPoints and NumOfInstances != NumofInstances[1],NumOfInstances != NumofInstances[1]);
addverticalline(highlightDataPoints and TimeBarWeAreLookingFor and CurrentDay == yes, TimeBarWeAreLookingFor and CurrentDay == yes,Color.yellow);

def AvgVol = Round(CumVol / NumOfInstances, 0);
def Percent = (volume / AvgVol) * 100;

AddLabel(1, "Current Candle: " + volume, Color.WHITE);
AddLabel(1,ROUND(Percent,2) + " %",if
Between(percent,100,110) then CreateColor(136,252,172)
                        else if Between(percent,110,120) then CreateColor(106, 252, 104)
                        else if percent >=120 then Color.Green
                        else if Between(percent,80,90) then Color.Pink
                        else if Between(percent,70,80) then  CreateColor(206,74,116)
                        else if percent <=80 then Color.Downtick
                        else Color.white);
AddLabel(1, "Avg Vol: " + AvgVol, Color.ORANGE);
AddLabel(1, "Prior Candles: " + CumVol, Color.ORANGE);
AddLabel(1, "Avg Over: " + NumOfInstances, Color.ORANGE);

# Plotting of the bar graph--------------------------------------------------------
plot CurrentCandleVolume = If ShowVolume then volume else Double.NaN;
CurrentCandleVolume.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
CurrentCandleVolume.SetLineWeight(barwidth);
 
Ruby:
declare upper;
def DayRoll =
    if GetDay() != GetDay()[1]
    and !IsNaN(close)
    then GetTime()
    else DayRoll[1]
;
def Time =
    if !isNaN(close)
    then GetTime()
    else double.nan
;
def aRoll = HighestAll(DayRoll);
def aTime = HighestAll(Time);
def aBarTime = aTime - aRoll;
def BarTime = Time - DayRoll;
def isSameBar = BarTime == aBarTime;
AddVerticalLine(isSameBar,"Same Bar",Color.green);
 
Wow Josh thank you so much. That is exactly what I was looking for.

I spent the morning trying to implement it into the code I posted above. Unfortunately, it renders it too slow to be useful. I think because the frequent updating to pull in tick-by-tick volume data causes the complex code to re-run every tick and it can't keep up.

If there was a way to prevent your section of code from refreshing until the new candle is created, I think that would solve the problem.

Here is the code that combines the two:
Code:
declare on_volume;
declare zerobase;

input includeCurrentDayInAvg = no;
input barsToBeIncluded = {default OnlyCurrentBar, CurrentAndBefore, CurrentAndAfter};
input includePremarket = no;
input includePostmarket = no;
input barwidth = 3;
input showVolume = yes;
input highlightDataPoints = yes;

#Preliminary Declarations -------------------------------
def PremarketTradingHours = RegularTradingStart(GetYYYYMMDD()) > GetTime();
def RegularTradingHours = RegularTradingStart(GetYYYYMMDD()) <= GetTime() and GetTime() < RegularTradingEnd(GetYYYYMMDD());
def PostmarketTradingHours = GetTime() >= RegularTradingEnd(GetYYYYMMDD());


def PremarketSessionStart = PostmarketTradingHours[1] and PremarketTradingHours;
def RegularSessionStart = PremarketTradingHours[1] and RegularTradingHours;
def PostmarketSessionStart = RegularTradingHours[1] and PostmarketTradingHours;

def CurrentDay = GetDay() == GetLastDay(); #this removes current bar from average.
#------------------------------------------------------------------------

# Code that Calculates Correct Population------------

def DayRoll = if GetDay() != GetDay()[1] and !IsNaN(close)
                    then GetTime()
                    else DayRoll[1];

def Time = if !IsNaN(close)
                then GetTime()
                else Double.NaN;

def aroll = HighestAll(DayRoll);

def aTime = HighestAll(Time);

def aBarTime = aTime - aroll;

def Bartime = Time - DayRoll;


def Population;
switch (barsToBeIncluded){
case OnlyCurrentBar:
    Population = if !includeCurrentDayInAvg
                            then !CurrentDay and Bartime == aBarTime
                            else Bartime == aBarTime;
case CurrentAndBefore:
    Population = if !includeCurrentDayInAvg
                            then !CurrentDay and if includePremarket == no
                                                    then Bartime <= aBarTime and !PremarketTradingHours
                                                    else Bartime <= aBarTime
                            else if includePremarket == no
                                    then Bartime <= aBarTime and !PremarketTradingHours
                                    else Bartime <= aBarTime;
case CurrentAndAfter:
    Population = if !includeCurrentDayInAvg
                            then !CurrentDay and if includePostmarket == no
                                                    then Bartime >= aBarTime and !PostmarketTradingHours
                                                    else Bartime >= aBarTime
                            else if includePostmarket == no
                                    then Bartime >= aBarTime and !PostmarketTradingHours
                                    else Bartime >= aBarTime;
}

#---------------------------------------------------------------------------



def NumOfInstances = if Population and CurrentDay == no
        then NumOfInstances[1] + 1
        else NumOfInstances[1];

def CumVol = if NumOfInstances != NumOfInstances[1]
            then CumVol[1] + volume
            else CumVol[1];

AddVerticalLine(highlightDataPoints and NumOfInstances != NumOfInstances[1], NumOfInstances != NumOfInstances[1]);
AddVerticalLine(highlightDataPoints and Population and CurrentDay == yes, Population and CurrentDay == yes, Color.YELLOW);

def AvgVol = Round(CumVol / NumOfInstances, 0);
def Percent = (volume / AvgVol) * 100;

AddLabel(1, "Current Candle: " + volume, Color.WHITE);
AddLabel(1, Round(Percent, 2) + " %", if
Between(Percent, 100, 110) then CreateColor(136, 252, 172)
                    else if Between(Percent, 110, 120) then CreateColor(106, 252, 104)
                    else if Percent >= 120 then Color.GREEN
                    else if Between(Percent, 80, 90) then Color.PINK
                    else if Between(Percent, 70, 80) then  CreateColor(206, 74, 116)
                    else if Percent <= 80 then Color.DOWNTICK
                    else Color.WHITE);
AddLabel(1, "Avg Vol: " + AvgVol, Color.ORANGE);
AddLabel(1, "Prior Candles: " + CumVol, Color.ORANGE);
AddLabel(1, "Avg Over: " + NumOfInstances, Color.ORANGE);

# Plotting of the bar graph--------------------------------------------------------
plot CurrentCandleVolume = if showVolume then volume else Double.NaN;
CurrentCandleVolume.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
CurrentCandleVolume.SetLineWeight(barwidth);
AddVerticalLine(Population,"Same Bar",Color.green);
 
Last edited:
Solution
Well, I generally avoid yellow triangle of doom code to begin with in my personal scripts, but it seems that highest all may have been throttled recently? I found a post from August speaking about this as a recent change. However, I believe this explanation may be incorrect. The issue actually seems to be that a once_per_bar declaration is being forced without consent, rather than a column/scan type update frequency being implemented. I will have to look into it more.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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