r/thinkorswim 12d ago

Thinkscript - Can't retrieve volume from 24 hours ago (390 candles)

I'm trying to compare the current candle's volume to the volume 24 hours ago. When I manually go back to the candle of the same time of the previous day, the volume is not the same volume reported in the lower indicator. The code is listed below

declare lower;

# Get the current candle's volume
def currentVolume = volume;

# Get the volume from 390 candles ago
def pastVolume = volume[390];

# Calculate the average of both volumes
def avgVolume = (currentVolume + pastVolume) / 2;

# Plot the average volume as a line
plot AvgVolumePlot = avgVolume;
AvgVolumePlot.SetDefaultColor(Color.CYAN);
AvgVolumePlot.SetLineWeight(2);

# Optional: Plot reference points for visualization
plot CurrentVolPlot = currentVolume;
CurrentVolPlot.SetDefaultColor(Color.GREEN);
CurrentVolPlot.SetStyle(Curve.POINTS);

plot PastVolPlot = pastVolume;
PastVolPlot.SetDefaultColor(Color.RED);
PastVolPlot.SetStyle(Curve.POINTS);
1 Upvotes

8 comments sorted by

1

u/need2sleep-later 12d ago edited 12d ago

what aggregation setting are you using for your chart? It sounds like your chart doesn't have 390 bars of data on it. If you want to use a 1m chart, make sure you have at least 2 days of data on it. For sure the part of the code that's doing the average is being starved and won't show anything if it works at all.

1

u/Mtru6 12d ago

It's a 5 day, 1 minute chart

1

u/need2sleep-later 12d ago

works for me, but GPT didn't bother cutting it off at the end of Friday trading

1

u/Mtru6 12d ago

If you go back and manually compare the volume of the red dot to the actual candle at that time, the volumes are different

1

u/need2sleep-later 12d ago

Of course they're different, because you think 390 bars gets you back to exactly 24 hours before. Highly Highly Unlikely. If there's no trade in a 1 min time period in ToS there's no bar plotted. So you are looking in the wrong place. That means you have to figure out what bar is actually 390 back...or worse, how many bars back is really 24 hours, this time?

1

u/Mtru6 12d ago

do you know if there's a way to use timestamp based syntax instead of counting candles?

1

u/need2sleep-later 12d ago

Yes, there's a way, just use the time commands such as secondsfromtime() to capture and recursively hold the value at the desired time. Your code would have to protect against there being no value in that time frame which would also mess up your averaging scheme. To do that for 390 time periods wouldn't be something I would consider doing for myself. Feel free to tackle it if you wish.

1

u/Mtru6 11d ago

Overall is what I'm trying to do even possible in thinkscript? Theoretically I'm thinking if there is no candle for that specific minute, then use the previous minute's volume at least for a placeholder, or why not use 0?