Black Friday 30% off Basic and ProBlack Friday −30%Ends in––d––h––m––sSee the deal

Candles and data

Candles of the chart and of other timeframes, the calendar, order flow and sentiment.

request.bars

Candles are always requested with request.bars(), the chart’s ones too, as the value of an argument. The function receives an object with one list per field.

Python
def calculate(bars=request.bars()):
    last = bars.close[-1]        # the latest close, maybe still forming
    first = bars.close[0]        # the oldest loaded candle
    body = [c - o for o, c in zip(bars.open, bars.close)]
FieldContent
open, high, low, closeThe prices
volumeThe contracts traded; nan if the symbol doesn’t have it
timeThe candle open, in UTC milliseconds
confirmedTrue if the candle is closed; False only on the one still forming
new_period(timeframe)True on the first candle of each period
match(other)The match with another request, see below
symbol.*Tick, point value, ticker, currency and available data
timeframe.*Unit, quantity, duration and whether it’s intraday
calendar.*Time and date in the symbol’s time zone, see below
orderflow.*With orderflow=: volumes and price levels
sentiment.*With sentiment=True: long and short percentages

All the fields are in the candles reference. Index 0 is the oldest loaded candle, -1 the latest. The fields are read-only.

Other timeframes

With timeframe you request the candles of another timeframe of the same symbol, even smaller than the chart’s. It’s written as in the top bar; None is the chart’s.

TimeframePeriod
"D", "W", "M", "3M", "12M"Trading day, week, month, quarter, year
"15", "60", "240"Minutes
"1S", "30S"Seconds

Periods follow the symbol’s sessions: for futures the day runs from 18:00 to 17:00 New York time. With bars.new_period("D") you find the first candle of each day, for example to restart a sum.

From the chart’s timeframe

The timeframe can depend on the chart’s: instead of the value, write the name of a module function. It receives the chart’s timeframe, with the same fields as bars.timeframe, and returns the one to request, or None for the chart’s. It’s called once, before the candles are downloaded.

Python
def lower(chart):
    if chart.seconds < 60:
        return "1S"
    if chart.intraday:
        return "1"
    return "60"

@indicator(plots=[plot.series("count", "Small candles")])
def calculate(bars=request.bars(), detail=request.bars(timeframe=lower)):
    return {"count": [pair[1] - pair[0] for pair in bars.match(detail)]}

Here a seconds chart requests 1-second candles, a minutes or hours chart 1-minute candles, the others 1-hour candles. If the function returns something that isn’t a timeframe, the indicator stops with the error, as with calculation errors.

Bringing values onto the chart: match

Each request has its own candles and its own index. bars.match(other) tells, for each candle of bars, which candles of other correspond to it: a (start, end) pair of indices. With a larger timeframe it’s (j, j + 1), the period that contains it; with a smaller one, all the candles inside; with no match, (j, j). It also works with news.

Previous day’s high and low on a 15-minute chart
Previous day’s high and low, taken from the daily candles.
Yesterday’s high and low
from totaltrade.v1 import indicator, request, plot, color, math

@indicator(short="Yesterday", overlay=True, plots=[
    plot.series("high", "High", type="step", color=color("#26A69A")),
    plot.series("low", "Low", type="step", color=color("#EF5350")),
])
def calculate(bars=request.bars(), daily=request.bars(timeframe="D", min_bars=2)):
    high = []
    low = []
    for start, end in bars.match(daily):
        # start is this candle's day: the day before is start - 1.
        if 0 < start < end:
            high.append(daily.high[start - 1])
            low.append(daily.low[start - 1])
        else:
            high.append(math.nan)
            low.append(math.nan)
    return {"high": high, "low": low}

The calendar

bars.calendar gives the time and date of each candle in the symbol’s time zone, not in the one chosen on the chart.

FieldContent
time_of_dayThe open time, "hh:mm:ss"
weekday1 Monday … 7 Sunday
day, month, yearThe open date, by the calendar
between(start, end, timezone=None)True on the candles that open inside the window
Python
morning = bars.calendar.between("09:30:00", "11:30:00")
london = bars.calendar.between("08:00:00", "16:30:00", timezone="Europe/London")
opening = [t == "09:30:00" for t in bars.calendar.time_of_day]

In between the start is included and the end is not; a window like "22:00:00"–"02:00:00" crosses midnight. timezone, like "Europe/London", is for the hours of another exchange.

The background colored during the session
between and plot.background: the background colors the session.

How many candles

The indicator calculates on the candles around the ones you’re looking at. Two arguments of request.bars change this:

ArgumentWhat it doesExample
min_barsThe extra history needed before the first visible candle. With a period, the calculation always starts from a whole period.200, or "W" for the whole week
max_barsHow far to calculate, counting from the latest candle: before that the indicator is empty.50000, or "3M" for the last three months

Both accept a number of candles of the request, a period like "D" or an input.int. For a 200-candle average, request at least 200 before: without them, the values on the left are missing. For exponential averages it’s best to request 3 or 4 times the length.

Python
length = input.int("Length", 200, min=1)

@indicator(overlay=True, plots=[plot.series("sma", "SMA")])
def calculate(bars=request.bars(min_bars=length), n=length):
    return {"sma": ta.sma(bars.close, n)}

Order flow

For symbols that have it, futures today, orderflow= downloads the price profile of each candle. You name the groups the code reads: the profile is heavy, and every extra group costs you on every data page.

Python
@indicator(short="POC", overlay=True, plots=[
    plot.series("poc", "POC", type="circle", color=color("#FF9800"), width=2),
])
def calculate(bars=request.bars(orderflow="volume")):
    return {"poc": ta.poc(bars.orderflow.levels)}

bars.orderflow.volume_bid and volume_ask are the market sells and buys. bars.orderflow.levels[i] is the list of levels of candle i, from the lowest price: each level is a Level.

Level fieldGroup to requestContent
priceAnyThe level’s price
volume_bid, volume_ask"volume"Sum of the individual trades
aggregate_bid, aggregate_ask"aggregate"Market orders, each counted whole at one price
biggest_volume_bid, biggest_volume_ask"biggest_volume"The largest single trade
biggest_aggregate_bid, biggest_aggregate_ask"biggest_aggregate"The largest market order

bid is market sells, ask market buys. You request one group, a list like ["volume", "biggest_volume"] or an input.choice whose options are groups: only the chosen one is downloaded.

Python
for candle in bars.orderflow.levels:
    for level in candle:
        delta = level.volume_ask - level.volume_bid
The POC of each candle on a futures chart
ta.poc: the price with the most volume in each candle.

Sentiment

For symbols that have it, sentiment=True downloads the percentages of long and short positions at the candle close, which add up to 100: bars.sentiment.long and bars.sentiment.short.

When data is missing

CaseWhat happens
The symbol has no volume, profile or sentimentnan and empty lists, plus a warning. Check first with bars.symbol.has_volume and the other has_*.
Data loadingThe calculation starts from what has arrived, from the latest candle backwards, and extends with each page; the circle spins in the legend while something is missing
History doesn’t go back that farnan where it’s missing
A timeframe that can’t be builtAn error in the legend
Reading bars.orderflow without requesting itA compile error, which says what to add