# Indicator documentation — TotalCharts > Complete documentation for writing Python indicators for TotalCharts, the TotalTrade chart (https://www.totaltrade.ai). Scripts are written in the indicator editor of app.totaltrade.ai. Every page also has a web version. # Indicators in Python Write your own indicators in Python, see them on the chart in seconds and share them with the community. ![The indicator editor next to the chart](https://www.totaltrade.ai/assets/docs-indicatori/editorOverview.webp) *The editor sits in the right panel: write, press Add to chart and the indicator appears.* ## How it works - You write in **Python**, with everything you need to calculate: functions, loops, lists, dictionaries and simple classes. The libraries are ours: `ta` for series, `math` for numbers, `format` for text and `draw` for drawings. - The indicator function receives **all the candles** at once and returns one series per plot: one value per candle. If it asks for them, it also receives the economic calendar **news**. - Short name, inputs and plots are **declared in the code**: settings, legend and scale come from there, with no extra work. - The code runs **in your browser, isolated**: it can’t see your account, your data or the network. - The built-in indicators are written in the same language: you can read their code and start from a copy. ## Where to start - [**Your first indicator**](https://www.totaltrade.ai/en/indicatori/documentazione/il-primo-indicatore) — From an empty editor to a moving average on the chart, in five steps. - [**The editor**](https://www.totaltrade.ai/en/indicatori/documentazione/editor) — Saving, testing, reading errors and suggestions as you type. - [**How a script is built**](https://www.totaltrade.ai/en/indicatori/documentazione/struttura-script) — Import, declarations, the function that calculates and what it returns. - [**Plots**](https://www.totaltrade.ai/en/indicatori/documentazione/plot) — Lines, columns, areas, shapes, candles and fills. - [**Examples**](https://www.totaltrade.ai/en/indicatori/documentazione/esempi) — Complete scripts to open in the editor and edit. - [**The ta functions**](https://www.totaltrade.ai/en/indicatori/documentazione/ta) — Averages, oscillators, volatility, volume and candlestick patterns. --- # Your first indicator From an empty editor to a moving average on the chart, in five steps. ![Animation: a new indicator added to the chart](https://www.totaltrade.ai/assets/docs-indicatori/firstIndicator.webp) *Create indicator, a name, Add to chart: the average is on the chart.* ### 1. Open the editor In the **Indicators** dialog press **Create indicator**, at the bottom of the sections column. The editor opens in the right panel with a ready-made example. ### 2. Give it a name Type it in the field above the script, up to 40 characters. The name isn’t in the code: you see it in the catalog and in the legend. ### 3. Read the example It’s the smallest indicator that works: a simple average of the close, with the length among the inputs. ### 4. Add to chart The button with the chart, next to the name, saves the script, compiles it and, if there are no errors, adds it to the active chart. If there is an error, you find it in the console below the script, with the line. ### 5. Change the inputs Double-click the line, or press the gear in the legend: the Inputs tab has the Length. The chart updates as you change it. ## The example, line by line ```python title="Moving average" # Example: a simple moving average of the close from totaltrade.v1 import indicator, request, input, plot, ta @indicator(overlay=True, plots=[plot.series("sma", "SMA")]) def calculate(bars=request.bars(), length=input.int("Length", 20, min=1)): # One series per plot, by key return {"sma": ta.sma(bars.close, length)} ``` | Line | What it does | |---|---| | `from totaltrade.v1 import …` | The only import: the declarations and libraries you use. `v1` is the language version, and a script written for it always gives the same results. | | `@indicator(…)` | How it looks: `overlay=True` puts it on the price, `plots` lists what it draws. | | `def calculate(…)` | The function that calculates. Its arguments are the candles, with `request.bars()`, the news, with `request.events("news")`, and the inputs, which become the settings. | | `return {…}` | One series per plot, with its key: here `"sma"`, one value per candle. | > **What next?** > > Try changing `ta.sma` to `ta.ema` and press Add to chart again: the indicator on the chart updates, without adding another one. Then read [How a script is built](https://www.totaltrade.ai/en/indicatori/documentazione/struttura-script). --- # The editor Where indicators are written, tested and saved. ## The commands Next to the name are the script commands, in the order you use them; full screen is at the top. There is no separate Compile: Save and Add to chart do it, after saving. | Command | What it does | |---|---| | **Save** ⌘ S | Always saves, even with errors. Then it compiles and writes the result in the console. The dot on the icon means there are unsaved changes. On systems other than Mac the shortcut is Ctrl S. | | **Add to chart** | Saves and compiles. Without errors it adds the indicator to the active chart, or updates the one already there; with an error the chart doesn’t change. | | **Full screen** | The editor covers the charts, to give you room. The same button puts it back. | Every save that compiles updates the copies of the indicator already on charts, with their settings. If you removed an option from an `input.choice`, anyone who had chosen it goes back to the default. ## The script menu The arrow at the end of the name row opens the script menu: **New indicator**, **Make a copy**, **Delete…**, **Publish to TotalTrade…**, this **Documentation** and, below, your saved indicators, to open with one click. Before you lose unsaved changes, the editor asks. ## Suggestions as you type ![Animation: the suggestions after ta. and the signature](https://www.totaltrade.ai/assets/docs-indicatori/completion.webp) *After ta. the functions appear; when you open the parenthesis, the arguments.* - As you type, the script’s names, the language keywords and the allowed Python functions appear. After a dot, the members of `ta`, `math`, `format`, `draw`, `input`, `plot`, `request`, the candles, price levels, news, lists, dictionaries and your classes. A news item is recognised in `for event in news`, also with `enumerate` and in comprehensions, and in `news[i]`. - Enter or Tab accept, Ctrl Space opens them, Esc closes them. - When you open a function’s parenthesis its signature appears, with the argument you’ve reached highlighted. ![Animation: the explanation of a function on hover](https://www.totaltrade.ai/assets/docs-indicatori/hover.webp) *Hovering over a name shows its signature and what it does.* ## Errors ![Animation: a syntax error underlined and then in the console](https://www.totaltrade.ai/assets/docs-indicatori/syntaxError.webp) *Syntax errors show up right away; the others on save, with the line.* - Syntax errors, like an unclosed parenthesis, are underlined as you type, with a mark next to the line number. Hover over it to read the message. - On save the compiler checks everything else: the error goes to the console, with the line, and stays marked on the line until the next edit. - Errors during the calculation, like a division by zero, appear in the Log tab, with the line. The indicator’s legend only says “Script error”. See [Errors and recalculation](https://www.totaltrade.ai/en/indicatori/documentazione/errori-e-ricalcolo). ## The console Below the script there are two tabs. To raise them drag the top edge: an error raises them by itself. ![The console with a compile error](https://www.totaltrade.ai/assets/docs-indicatori/consoleMessages.webp) *Messages: every save adds a line, with the time.* - **Messages** is the editor’s log: every save or publication adds a line with the time, and the error with its line. It keeps the last 100; right-click for “Clear messages”. - **Log** shows the `print` output and the errors of the last calculation of each indicator, on all charts. Each calculation redoes everything, so the lines are replaced instead of repeating. ![Animation: print output in the Log tab](https://www.totaltrade.ai/assets/docs-indicatori/printLog.webp) *print writes to Log, with the calculation time and the code line.* ## Reading the built-ins’ code In the Indicators dialog, a card’s `` button opens the code in the editor as an unsaved copy, “Name (copy)”. “Source code” and “Copy code” in the legend’s More menu do the same. If you save it, it becomes one of your indicators. ![Animation: a built-in’s code opened in the editor](https://www.totaltrade.ai/assets/docs-indicatori/viewCode.webp) *A built-in’s code, opened as a copy to edit.* ## Where scripts end up Saved and without errors, a script is in the catalog, under **My indicators**. With an error it stays in the editor menu, but leaves the catalog until you fix it. To share it, see [Publishing](https://www.totaltrade.ai/en/indicatori/documentazione/pubblicare). --- # Build indicators with your AI TotalCharts doesn’t have a built-in AI or an MCP server yet. But you can write your indicators with the AI you already use, like ChatGPT, Claude or Gemini, and paste them into the editor. ## In five steps ### 1. Give the documentation to the AI Write in the chat the link to the complete documentation in a single text file: `https://www.totaltrade.ai/llms-full.txt`. If your AI doesn’t open links, open the file yourself and paste its text into the chat. ### 2. Describe the indicator What it calculates, what it draws on the chart, on the price or in a pane, and which settings you want to be able to change. The more precise you are, the fewer fixes you need. ### 3. Paste the code into the editor In the **Indicators** dialog press **Create indicator**, give it a name, paste the script in place of the example and press **Add to chart**. ### 4. Send the errors back to the AI If there is an error, you find it in the console below the script, with the line. Copy it into the chat and ask for the script to be fixed. Repeat until the indicator is on the chart. ### 5. Check the result Compare the values on the chart with the ones you expect, on several timeframes and several instruments, before using it to trade. ## A prompt to copy Replace the part in square brackets with your indicator. ```text title="Prompt" Write an indicator for TotalTrade's TotalCharts, in Python, following only the documentation at https://www.totaltrade.ai/llms-full.txt. Rules: - a single import: from totaltrade.v1 import … - the @indicator decorator and the calculate function, which receives all the candles and returns one series per plot - only the ta, math, format and draw libraries and the Python allowed by the documentation - settings as inputs, with clear names The indicator: [what it calculates, what it draws, which settings]. Reply with the complete script, ready to paste into the editor. ``` ## Good to know - The AI works only on the text you give it: it can’t see your chart, your account or your data. - The AI can make mistakes: always check the code and the values. What you can write is in [Allowed Python](https://www.totaltrade.ai/en/indicatori/documentazione/python-ammesso), the limits are in [Errors and recalculation](https://www.totaltrade.ai/en/indicatori/documentazione/errori-e-ricalcolo#limits). - You can also start from a built-in indicator: open its code, make a copy and ask the AI to modify it. - Creating your own indicators and publishing them in the community is included in the Pro plan. --- # How a script is built One import, the declarations, a function that calculates and a dictionary of series. ```python title="Bands" """An average with bands.""" from totaltrade.v1 import indicator, request, input, plot, color, ta # Module names: constants and declarations to use more than once. BLUE = color("#2962FF") period = input.int("Length", 20, min=1) @indicator(short="Bands", overlay=True, plots=[ plot.series("middle", "Average", color=BLUE), plot.series("upper", "Upper", color=BLUE, pattern="dashed"), plot.series("lower", "Lower", color=BLUE, pattern="dashed"), ]) def calculate( bars=request.bars(min_bars=period), length=period, mult=input.float("Deviations", 2.0, min=0, step=0.5), ): middle, upper, lower = ta.bb(bars.close, length, mult) return {"middle": middle, "upper": upper, "lower": lower} ``` ## The import The first line of code imports from `totaltrade.v1` only what you use: the declarations (`indicator`, `request`, `input`, `plot`, `color`) and the libraries (`ta`, `math`, `format`, `draw`). There are no other imports. `v1` is the language version: a script written for it gives the same results even when a new one arrives. ## Module names Before the functions you can give a name to a constant or a declaration, and use it wherever you need it. Each name is assigned only once. - A named input is **a single setting**, even if you use it several times: above, `period` sets both the length and how many candles to load. - Constants, like `BLUE` or `LEVELS = [30, 70]`, can be used anywhere and are read-only: to modify a list, make a copy, like `list(LEVELS)`. - In the function body, a name that holds an input, a request or a plot is an error: there the value comes from the arguments. ## @indicator The decorator says how the indicator looks: the short name in the legend, whether it sits on the price or in its own pane, the plots it draws, the scale and the number format. You only write the arguments you need: an indicator made only of drawings is `@indicator(overlay=True)`. All the arguments are in the [reference](https://www.totaltrade.ai/en/indicatori/documentazione/dichiarazioni). > **The name isn’t in the code** > > Name and description are saved separately: the name goes in the field above the script, the description when you publish it. This way a script is saved even when it doesn’t compile. ## The function that calculates Only one function has `@indicator`, with any name you like. Each of its arguments has a declaration as its default value: `request.bars(…)` for the candles, `request.events(…)` for the [news](https://www.totaltrade.ai/en/indicatori/documentazione/news), an `input.*` for a setting, written there or through a module name. An input’s key is the name it’s assigned to: the name of the variable or the argument. The function receives the whole series, one list per field, from the oldest candle to the latest, and the news as a list in time order, and calculates everything in one go. ## What it returns A dictionary with one entry per plot, under its key. Each series is as long as the chart’s candles, and `nan`, `None` or infinity leave a gap. A missing or extra key is an error. Fills between two plots don’t have an entry, and neither do drawings: an indicator made only of drawings returns nothing. ## Declarations and calculations Declarations, that is `@indicator`, `input.*`, `plot.*`, `request.bars` and `request.events`, contain only literal values: text, numbers, `True`, `False`, `None`, lists, tuples, dictionaries, colors and module names. This way settings and legend are known without running the code. ```python plot.series("sma", "SMA", width=2) # OK plot.series("sma", "SMA", width=1 + 1) # error: a calculation in a declaration ``` ## Your own functions and classes After the module names you can write other functions and [simple classes](https://www.totaltrade.ai/en/indicatori/documentazione/python-ammesso#classes), to call from the function that calculates. A docstring at the start of the file stays a comment. --- # Inputs The settings the user changes in the dialog, written as arguments of the function. ![An indicator’s settings, split into sections](https://www.totaltrade.ai/assets/docs-indicatori/inputsDialog.webp) *The sections, the row with two times and the help next to the label come from the code below.* ```python title="Average with the session" from totaltrade.v1 import indicator, request, input, plot, color, ta @indicator(short="Session", overlay=True, plots=[ plot.series("average", "Average", color=color("#2962FF"), width=2), plot.background("session", "Session", color=color("#2962FF", 10)), ]) def calculate( bars=request.bars(), length=input.int("Length", 20, min=1, group="Average"), kind=input.choice("Type", "ema", options=[ ("sma", "Simple"), ("ema", "Exponential"), ], group="Average"), start=input.time("Start", "09:30:00", group="Session", inline="session", tooltip="In the symbol time zone"), end=input.time("End", "16:00:00", group="Session", inline="session"), show=input.bool("Color the session", True, group="Session"), ): average = ta.ma(bars.close, length, kind) inside = bars.calendar.between(start, end) return {"average": average, "session": [show and x for x in inside]} ``` ## Types | Input | In the settings | The function receives | |---|---|---| | `input.int(label, default)` | A whole number | `int` | | `input.float(label, default)` | A decimal number | `float` | | `input.bool(label, default)` | A toggle | `bool` | | `input.choice(label, default, options)` | A dropdown | The chosen value, a text or `None` | | `input.time(label, default)` | A time, with hours, minutes and seconds | `"hh:mm:ss"` | | `input.color(label, default)` | A color with opacity | A color | | `input.line(label, default)` | The drawings’ line | The `line=` dictionary | | `input.fill(label, default)` | The drawings’ fill | The `fill=` dictionary | | `input.font(label, default)` | The drawings’ font | The `"style"` dictionary in `text=` | - `input.int` and `input.float` also have `min`, `max` and the `step`. - The options of `input.choice` are `(value, label)` pairs: the user sees the label, the function receives the value. - A time is always written with seconds, `"09:30:00"`: this way times can also be compared as text. ## In the legend Next to the indicator’s name the legend shows the values of the numeric inputs and of the choices, the choices with their label: for example “Session 20 Exponential”. Toggles, times, colors and styles don’t appear: they are settings, not calculation parameters, and ten session times would fill the row. ## When you change the script When you save the script, its copies on the charts keep the values chosen by the user. If you remove an option from an `input.choice`, anyone who had chosen it goes back to the default value, both in the calculation and in the settings. A new input starts from its default. ## Sections, rows and help All inputs accept four arguments to decide where they sit and when they apply: - `group`: the title of the section it appears in. - `inline`: any name; inputs with the same `inline` sit on the same row, like Start and End above. - `tooltip`: a help text, shown when you hover over the icon next to the label. - `active`: an `input.bool`. When it’s off the field stays visible but dimmed, and can’t be changed. The function still receives its value. ```python show_ma = input.bool("Show the average", True) length = input.int("Length", 20, min=1, active=show_ma) # in the function arguments: show=show_ma, n=length ``` Inputs appear in the order you write them; a section or a row sits where the first input that uses it appears. In a row, an `input.bool` written last shows only the toggle, and the label of the field before applies to both. ## Drawing styles `input.line`, `input.fill` and `input.font` are the drawing styles, each in a single setting, with the same popover as a drawing’s settings. The default is written like the drawing’s argument; whatever is missing comes from the drawings. The function receives the same dictionary, to pass on as it is. ```python line=input.line("Line", {"color": color("#FFFF00"), "width": 2}), fill=input.fill("Zone", {"color": color("#2962FF", 15), "gradient": True}), font=input.font("Text", {"color": color("#FFFFFF"), "size": 12}), # in the function: draw.trend_line((i, price), (i + 1, price), line=line) draw.rectangle((start, high), (end, low), fill=fill, text={"value": "Zone", "style": font}) ``` The colors of these inputs are hexadecimal, like those of the drawings: a theme color like `color("up")` is an error. ## An input for the timeframe An `input.choice` passed to `request.bars` lets the user choose the timeframe. Each option must be a valid timeframe, or `None` for the chart’s. To pick it from the chart’s timeframe, without an input, see [From the chart’s timeframe](https://www.totaltrade.ai/en/indicatori/documentazione/candele-e-dati#timeframe-function). ```python htf=request.bars(timeframe=input.choice("Timeframe", "W", options=[ (None, "Chart"), ("D", "Day"), ("W", "Week"), ])), ``` Here the input’s key is `htf`: written inside another declaration, it takes that one’s name. In the same way an `input.choice` passed to `request.events` chooses the news currencies or impacts: see [News](https://www.totaltrade.ai/en/indicatori/documentazione/news#inputs). --- # 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)] ``` | Field | Content | |---|---| | `open, high, low, close` | The prices | | `volume` | The contracts traded; `nan` if the symbol doesn’t have it | | `time` | The candle open, in UTC milliseconds | | `confirmed` | `True` 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](https://www.totaltrade.ai/en/indicatori/documentazione/riferimento-candele). 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. | Timeframe | Period | |---|---| | `"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](https://www.totaltrade.ai/en/indicatori/documentazione/news#match). ![Previous day’s high and low on a 15-minute chart](https://www.totaltrade.ai/assets/docs-indicatori/matchDaily.webp) *Previous day’s high and low, taken from the daily candles.* ```python title="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. | Field | Content | |---|---| | `time_of_day` | The open time, `"hh:mm:ss"` | | `weekday` | 1 Monday … 7 Sunday | | `day, month, year` | The 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](https://www.totaltrade.ai/assets/docs-indicatori/calendarSession.webp) *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: | Argument | What it does | Example | |---|---|---| | `min_bars` | The 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_bars` | How 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 field | Group to request | Content | |---|---|---| | `price` | Any | The 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](https://www.totaltrade.ai/assets/docs-indicatori/orderflowPoc.webp) *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 | Case | What happens | |---|---| | The symbol has no volume, profile or sentiment | `nan` and empty lists, plus a warning. Check first with `bars.symbol.has_volume` and the other `has_*`. | | Data loading | The 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 far | `nan` where it’s missing | | A timeframe that can’t be built | An error in the legend | | Reading `bars.orderflow` without requesting it | A compile error, which says what to add | --- # News The economic calendar news, like jobs data, inflation and rate decisions: time, currency, impact and the actual, forecast and previous values. ![High-impact news as vertical lines on the chart](https://www.totaltrade.ai/assets/docs-indicatori/exampleNews.webp) *One line for each hour with news, green if the data is better than forecast and red if worse, and the background on the candles with a news event.* ## request.events News is requested with `request.events("news")`, as the value of an argument, next to the candles. The first argument is the event type: today there is only `"news"`. The other two choose which news arrives. ```python def calculate( bars=request.bars(), news=request.events("news", currencies=["USD", "EUR"], impacts="high"), ): for event in news: print(event.title, event.actual_text) ``` | Argument | What it chooses | Default | |---|---|---| | `kind` | The event type: `"news"` | Always written | | `currencies` | The currencies, one or a list: `"USD"`, `"EUR"`, `"GBP"`, `"JPY"`, `"CAD"`, `"AUD"`, `"CHF"`, `"NZD"`, `"CNY"` or `"All"` for global news | `None`: the symbol’s | | `impacts` | The impacts, one or a list: `"high"`, `"medium"`, `"low"` or `"none"`, for holidays and the like | `None`: all | - The symbol’s currencies are the same as “From chart” in the calendar: the symbol’s currency and, for a forex pair like EURUSD, the first one too. Global news, `"All"`, arrives only if you request it. - The script’s news doesn’t follow the calendar filters or “Show on chart”: only `currencies` and `impacts` decide. - A value that doesn’t exist, like `"SEK"` or `"huge"`, or an empty list is a compile error, with the allowed values. ### With an input Currencies and impacts can be chosen with an `input.choice`: each option is a currency or an impact, or `None` for the default. An input delivers a single value; to choose several together, request them all and filter in the code. As with `request.bars`, the input’s key is the argument name, here `news`. ```python news=request.events("news", impacts=input.choice("Impact", "high", options=[ (None, "All"), ("high", "High"), ("medium", "Medium"), ])), ``` ## The list The function receives a list of news in time order: from the first calculated candle as far as the drawings reach, up to 500 candles after the latest one. So it also includes upcoming news, with the forecast and the previous value but without the actual. ```python count = len(news) # how many news events last = news[-1] if news else None # the furthest ahead in time high = [e for e in news if e.impact == "high"] usd = [e for e in news if e.currency == "USD"] ``` The list and the news are read-only, like the candles: to work on a list, make a copy, `list(news)`, or a comprehension. `print(event)` only writes ``: to read its values print the fields, like `print(event.title, event.actual)`. ## What’s in a news event | Field | Content | |---|---| | `time` | The time, in UTC milliseconds, like `bars.time` | | `currency` | The currency, or `"All"` for global news | | `impact` | `"high"`, `"medium"`, `"low"` or `"none"` | | `title` | The name, like `"CPI m/m"` | | `actual, forecast, previous` | Actual, forecast and previous as numbers, `nan` if missing | | `actual_text, forecast_text, previous_text` | The same as the source writes them, `""` if missing | | `higher_is_better` | `True` if a higher value is better for the currency, `False` if lower, `None` if not compared | | `tone` | The data compared with the forecast: `"better"`, `"worse"`, `"even"` or `None` | | `id` | The news code: it stays the same for its whole life, even if the time changes | All the fields are also in the [news reference](https://www.totaltrade.ai/en/indicatori/documentazione/riferimento-news). ### Numbers and text The fields with `_text` are the values as the source writes them, to put in labels with the percentage or the K. Those without are the numbers, for calculations: | Text | Number | |---|---| | `"0.3%"` | `0.3`, the number as written | | `"165K", "-1.4M", "3.25B", "1.49T"` | Thousands, millions, billions, trillions: 165000, -1400000… | | `"-$87.62B", "C$0.71B"` | Without the currency symbol | | `"<0.25%"` | `0.25`, the stated limit | | `"4.22\|1.4"` | `4.22`: in auctions the yield counts, the first number | | `"", "Pass", "Yes", "2-0-7"` | `nan`: missing, not a number, or a vote | Data not yet released has `actual` `nan` and `actual_text` empty; when it’s released both are filled. A speech or a holiday has no numbers. ### Better or worse than forecast `tone` compares the actual with the forecast, or with the previous if the forecast is missing, in the direction of `higher_is_better`: for unemployment, jobless claims or inventories a lower value is `"better"`. Equal values give `"even"`. It’s the same color as the actual value in the calendar. `tone` is `None` if the data hasn’t been released yet, if there’s nothing to compare it with or if `higher_is_better` is `None`: speeches, holidays, meetings, votes and auctions. `higher_is_better` is set per series, so it’s the same for every release of the same data. ```python surprises = [e for e in news if e.tone == "better" and e.impact == "high"] change = event.actual - event.forecast # nan if either is missing ``` ## On the candles: match `bars.match(news)` gives, for each candle, the `(start, end)` pair of indices of the news that falls inside it: its news is `news[start:end]`, and a candle without news has `start == end`. It works with any candle request, even of another timeframe, like `daily.match(news)`. - A news event belongs to the candle that opens before it, up to the open of the next one. A news event in the gap between two candles, like over the weekend, goes with the candle before, like the dots on the chart. - After the latest candle, only up to its end: upcoming news further ahead isn’t in any candle. - A filtered list works too, as long as it stays in time order: a list in another order is a `ValueError`, a list that isn’t news a `TypeError`. ```python title="Candles with news" from totaltrade.v1 import indicator, request, plot, color @indicator(short="News", overlay=True, plots=[ plot.background("news", "High-impact news", color=color("#F23645", 15)), ]) def calculate(bars=request.bars(), news=request.events("news", impacts="high")): # The background colors the candles with at least one high-impact news event. return {"news": [end > start for start, end in bars.match(news)]} ``` ```python # For each candle, how many news events and the first one. for i, (start, end) in enumerate(bars.match(news)): if end > start: print(i, end - start, news[start].title) ``` ## Drawing them With `xloc="time"` a point’s x is a time: a drawing falls at the exact time of the news, even after the latest candle. Inside a market pause the time is split proportionally between the two candles: a Saturday news event falls in the space between Friday and the reopening. ```python title="News lines" from totaltrade.v1 import indicator, request, draw, color TONES = {"better": color("#26A69A"), "worse": color("#EF5350")} GRAY = color("#787B86") @indicator(short="News", overlay=True) def calculate(bars=request.bars(), news=request.events("news", impacts="high")): for event in news: line = {"color": TONES.get(event.tone, GRAY), "pattern": "dashed"} # The text runs along the line, at the top; the point's price doesn't matter. draw.vertical_line((event.time, bars.close[-1]), xloc="time", line=line, text={"value": event.title, "align": "right"}, show_time_label=False) ``` Several news events at the same time make lines on top of each other: the example [News on the chart](https://www.totaltrade.ai/en/indicatori/documentazione/esempi#news) draws only one, with the number of the others. ## When they change - When data is released the news event stays the same, with the same `id`: `actual` and `tone` are filled in, and the indicator recalculates by itself, as with a new candle. - If the source moves the time or corrects the title, currency or impact, the news event keeps its `id` and changes place in the list. - A news event cancelled by the source stays in the list until the chart is next loaded. This is rare. ## When they’re missing | Case | What happens | |---|---| | The news is arriving | The calculation waits, with the circle spinning in the legend | | The chart doesn’t have news | The list is empty and the legend warns about it | | The news can’t be downloaded | An error in the legend: the indicator doesn’t draw | | No news for the chosen currencies and impacts | The list is empty | Event requests count towards the request limit together with candle requests: see [Limits](https://www.totaltrade.ai/en/indicatori/documentazione/errori-e-ricalcolo#limits). --- # Plots What the indicator draws for each candle: lines, columns, areas, shapes, candles, numbers, fills and backgrounds. ![A line plot](https://www.totaltrade.ai/assets/docs-indicatori/plotLine.webp) *Line* ![A step plot](https://www.totaltrade.ai/assets/docs-indicatori/plotStep.webp) *Step* ![A columns plot](https://www.totaltrade.ai/assets/docs-indicatori/plotColumns.webp) *Columns* ![A histogram plot](https://www.totaltrade.ai/assets/docs-indicatori/plotHistogram.webp) *Histogram* ![An area plot](https://www.totaltrade.ai/assets/docs-indicatori/plotArea.webp) *Area* ![A baseline plot](https://www.totaltrade.ai/assets/docs-indicatori/plotBaseline.webp) *Baseline* ![A circles plot](https://www.totaltrade.ai/assets/docs-indicatori/plotCircles.webp) *Circles* ![A crosses plot](https://www.totaltrade.ai/assets/docs-indicatori/plotCrosses.webp) *Crosses* ![Arrows above and below the candles](https://www.totaltrade.ai/assets/docs-indicatori/plotShapes.webp) *Shapes* ![A character above the candles](https://www.totaltrade.ai/assets/docs-indicatori/plotChar.webp) *Character* ![Candles drawn by an indicator](https://www.totaltrade.ai/assets/docs-indicatori/plotOhlc.webp) *Candles* ![A row of numbers below the candles](https://www.totaltrade.ai/assets/docs-indicatori/plotText.webp) *Text* ![A fill between two lines](https://www.totaltrade.ai/assets/docs-indicatori/plotFill.webp) *Fill* ![The colored background](https://www.totaltrade.ai/assets/docs-indicatori/plotBackground.webp) *Background* ## How to write them Plots are listed in the `plots` of `@indicator`, in the order they stack: the first one sits at the bottom. They are all written `plot.type(key, label, …)`. - `key` is the plot’s entry in the returned dictionary, and the name its settings are saved under: unique within the indicator, in `snake_case`. - `label` is the plot’s name in the Style tab of the settings. The legend shows only the values, in the plot’s color. - The other arguments are the style: color, width, line style, type. They become the settings the user changes. ## plot.series One number per candle. `nan` leaves a gap. | type | Drawing | |---|---| | `"line"` | A line; it’s the default type | | `"step"` | A step line | | `"columns"` | Bars as wide as the candle, from `base` to the value | | `"histogram"` | Thin bars, from `base` to the value | | `"area"` | A line with the `area` fill | | `"baseline"` | Line and two-color fills around a level | | `"circle", "cross"` | A circle or a cross at the value | ```python plot.series("sma", "SMA", color=color("#2962FF"), width=2) plot.series("level", "Level", type="step", pattern="dashed") plot.series("delta", "Delta", type="columns", base=0) ``` `width` is the width of the line, of the histogram bars, or the size of circles and crosses. `pattern` is `"solid"`, `"dashed"`, `"dotted"` or `"dash_dot"`. Area and baseline are explained in [Colors and style](https://www.totaltrade.ai/en/indicatori/documentazione/colori-e-stile). ## plot.shape A shape where the returned series is `True`: `"circle"`, `"square"`, `"cross"`, `"arrow_up"`, `"arrow_down"`, or `"char"` with the character `char`, even an emoji. ```python plot.shape("up", "Bullish cross", type="arrow_up", location="below", color=color("up"), text="Long") # in the function: return {"up": ta.crossover(fast, slow)} ``` - `location` is `"above"` or `"below"`, above the high or below the low of the candle, or `"top"` or `"bottom"`, on the edges of the pane. - `size` is the size in pixels; without it, it adapts to the candle width. - `text` is a fixed text next to each shape. ## plot.ohlc Candles or bars drawn by the indicator: the function returns `(open, high, low, close)`. With the default colors, Up and Down, it also chooses the color of each candle. ```python title="Heikin Ashi" from totaltrade.v1 import indicator, request, plot, ta @indicator(short="HA", plots=[plot.ohlc("candles", "Heikin Ashi")]) def calculate(bars=request.bars()): o, h, l, c = ta.heikinashi(bars.open, bars.high, bars.low, bars.close) colors = ["up" if b >= a else "down" for a, b in zip(o, c)] return {"candles": ((o, h, l, c), colors)} ``` `type` is `"candles"`, with `wicks` and `hollow`, or `"bars"`, with `hlc` and `thin`. ## plot.text A row of numbers at the bottom of the pane, one below each candle, like the footprint ones. Several rows stack in the order of `plots`, the first at the top, and each row’s name sits on the scale, at its height. If a number doesn’t fit in its candle, all the numbers in the row are hidden. `size` is the text size, from 8 to 20 px. With `cell` each number has a colored cell. The cell has a single color or, like `color`, a list of named colors. The entry becomes a tuple: the values, the cell names if there is more than one, and the intensity of each cell, from 0 to 1, which sets its opacity. If `color` is a list too, its names come right after the values. ![A pane with five rows of colored cells](https://www.totaltrade.ai/assets/docs-indicatori/plotCells.webp) *Volume, buys, sells and delta of each candle, with each row’s name on the scale.* ```python plot.text("delta", "Delta", cell=[ ("buy", "Buys", color("up")), ("sell", "Sells", color("down")), ]) # in the function: sides = ["buy" if d >= 0 else "sell" for d in delta] strength = [abs(d) / top for d in delta] # top: the largest delta you want return {"delta": (delta, sides, strength)} ``` - A cell with the name `None`, or with intensity `nan` or 0, stays empty. A `nan` value leaves the cell without a number. - On a strong cell the number turns white or black, to be readable on any color. - If the pane has only rows, they share its height and the scale shows only their names. This is how you build a table, like Bar Statistics: only `plot.text` rows, in their own pane. The rows stay put even when you drag the scale, don’t count towards the drawing limit and, with `scale="left"`, the names sit on the left. Better than drawn rectangles and texts. ## plot.fill A fill between two bounds, `upper` and `lower`: `plot.series` keys, numbers, or `"bottom"`, the bottom of the pane. It has no entry in the dictionary, because it always fills between its bounds. ```python plot.fill("band", "Background", 70, 30, fill={"color": color("#7E57C2", 10)}) plot.fill("cloud", "Cloud", "fast", "slow", fill={"color": color("#2962FF", 15)}) ``` ## plot.background Colors the full height of the pane where the returned series is `True`, with a transparent color to let the candles show through. ## What to return | Plot | Dictionary entry | |---|---| | `plot.series` | A list of numbers | | `plot.shape` | A list of bools | | `plot.ohlc` | `(open, high, low, close)`, four lists | | `plot.text` | A list of numbers; with `cell`, a tuple with the cells | | `plot.fill` | Nothing | | `plot.background` | A list of bools | With [named colors](https://www.totaltrade.ai/en/indicatori/documentazione/colori-e-stile#named) the entry becomes a pair: the values and the color name of each candle. ## Common options | Argument | What it does | |---|---| | `display` | `"all"` draws it, `"none"` starts it hidden: in the settings it’s the Visible toggle. | | `format, precision` | As in `@indicator`, which they take their value from: for legend, labels and numbers. | | `show_last_value` | The last value label on the scale; on if you don’t write it. | | `show_last_value_line` | The last value line up to the right edge. | | `editable=False` | The appearance doesn’t show in the settings. | ## In the Style tab ![Animation: a plot’s display changed](https://www.totaltrade.ai/assets/docs-indicatori/plotStyle.webp) *Each plot has its own section: the user changes type, color and width.* The type is also a setting: a line can become columns, area or baseline, but not an arrow, which needs `True` and `False` instead of numbers. --- # Colors and style How to write colors, fills, baselines and colors that change candle by candle. ## color ```python color("#2962FF") # hex color("#2962FF", 50) # with opacity, from 0 to 100 color("up", 30) # theme color ``` The theme colors are `up`, `down`, `line`, `buy`, `sell`, `neutral` and `text`: they follow the light and dark theme until the user changes them. They exist only in plots; drawings use hex colors. A text instead of `color(…)` is an error. ## One color per candle Instead of a color you can write a list of named colors: `(name, label, color)`. The function picks a name for each candle and returns a pair: the values and the names. The settings have one button per color, with its label. ![A histogram with four colors](https://www.totaltrade.ai/assets/docs-indicatori/namedColors.webp) *The MACD histogram with four colors: rising or falling, above or below zero.* ```python plot.series("hist", "Histogram", type="columns", color=[ ("rising_above", "Rising above zero", color("#26A69A")), ("falling_above", "Falling above zero", color("#B2DFDB")), ("rising_below", "Rising below zero", color("#FFCDD2")), ("falling_below", "Falling below zero", color("#FF5252")), ]) # in the function: return {"hist": (hist, colors)} ``` The name is in `snake_case` and is also the key of the saved color: you can change the label without losing the colors chosen by the user. ## Fills and gradient A fill is a dictionary: `color` and, if you want a gradient, `"gradient": True` with `bottom_color`. In plots it fades from the top to the bottom of the pane. ![A gradient fill below an average](https://www.totaltrade.ai/assets/docs-indicatori/gradientFill.webp) *A fill from the average down to the bottom of the pane, with a gradient.* ```python plot.fill("glow", "Fill", "sma", "bottom", fill={ "color": color("#7E57C2", 40), "gradient": True, "bottom_color": color("#7E57C2", 0), }) ``` ## Baseline The `"baseline"` type colors above and below a level, like an oscillator’s zero: `up` and `down` are the lines, `up_fill` and `down_fill` the fills. You only write what changes. ```python plot.series("momentum", "Momentum", type="baseline", baseline={ "level": 0, "up": {"color": color("up"), "width": 2}, "down": {"color": color("down"), "width": 2}, }) ``` ## How style is written Plots and drawings write their style the same way, with the names of their settings: - a simple field is an argument: `type="line"`, `extend_end=True`; - a group is a dictionary: `line={"color": color("#2962FF"), "width": 2}`; - names are in `snake_case`, and a missing field takes the default value. A wrong name or value is a compile error, with the line: the message says what was expected. --- # Panes and scales Where the indicator sits: on the price or in its own pane, with which scale and which numbers. ## overlay ![An indicator on the price](https://www.totaltrade.ai/assets/docs-indicatori/paneOverlay.webp) *overlay=True* ![An indicator in its own pane](https://www.totaltrade.ai/assets/docs-indicatori/paneNew.webp) *overlay=False* With `overlay=True` the indicator sits on the price pane. With `overlay=False`, the default, it creates a pane below, which disappears with the last indicator it contains. The user moves it to another pane from the legend, with “Move”. ## scale | scale | Scale | |---|---| | `"auto"` | The price scale, if it sits on the price, or the pane’s. It’s the default. | | `"left", "right"` | The scale on that side | | `"none"` | No scale, only on the price: it fits the pane height by itself. | A pane can have several scales, on the right and on the left, and autoscale only looks at what is attached to each scale. The user changes it from the legend menu, with “Pin to scale”. ## No scale, with margins Without a scale the indicator doesn’t touch the price scale and shows no numbers on the axis. `margins`, `(top, bottom)` as percentages, sets the band it sits in: here is the volume in the lowest fifth of the chart. ![The volume at the bottom, below the candles](https://www.totaltrade.ai/assets/docs-indicatori/scaleNone.webp) *scale="none" and margins=(80, 0): the volume below the candles.* ```python title="Volume at the bottom" from totaltrade.v1 import indicator, request, plot, color @indicator(short="Vol", overlay=True, scale="none", margins=(80, 0), format="quantity", plots=[plot.series("volume", "Volume", type="columns", color=[ ("up", "Up", color("up", 50)), ("down", "Down", color("down", 50)), ])]) def calculate(bars=request.bars()): colors = ["up" if c >= o else "down" for o, c in zip(bars.open, bars.close)] return {"volume": (bars.volume, colors)} ``` ## name_labels With `name_labels=True`, the name of each plot appears next to its last value label. The user can also turn them on and off, at the bottom of the Style tab. ![The name labels next to the value labels](https://www.totaltrade.ai/assets/docs-indicatori/nameLabels.webp) *The name labels on the scale, next to the values.* ## format and precision | format | How numbers are written | |---|---| | `"price"` | Like the symbol’s prices; it’s the default | | `"quantity"` | Whole numbers below 10,000, then K, M and B, like volumes | | `"percent"` | With the percent sign | `precision` changes the decimals. They apply to legend, labels and axis, and each plot can have its own. --- # Drawings Rectangles, lines, texts, Fibonacci and all the other chart drawings, created from code. ![Rectangles drawn by an indicator](https://www.totaltrade.ai/assets/docs-indicatori/drawingsZones.webp) *The zones of each session, drawn with draw.rectangle.* ## Creating a drawing Drawings aren’t declared: they are created in the code, with `draw.type(points, …)`. The type is the drawing’s name in `snake_case`: `rectangle`, `trend_line`, `horizontal_line`, `text`, `fib_retracement`… All the types, with how many points they need, are in the [draw reference](https://www.totaltrade.ai/en/indicatori/documentazione/draw). ```python draw.rectangle((start, high), (end, low), fill={"color": color("#2962FF", 15)}) draw.horizontal_line((0, 70), line={"color": color("#787B86"), "pattern": "dashed"}) draw.text((i, high), text={"value": f"High {format.price(high)}"}) ``` They return nothing and don’t go in the dictionary: all the drawings created during the calculation appear. It’s best to create them when they are final, usually at the end. ## Points - Each point is `(index, price)`, with the index of a chart candle. As in Python, `-1` is the latest. - After the latest candle the index goes on, up to 500: the point falls where the chart expects that candle. This way `draw.trend_line((i, p), (i + 1, p))` works on the latest one too. - With `xloc="time"` the points’ x values are times in UTC milliseconds, like `bars.time`: useful when the x comes from a time of day or another timeframe. ```python # Up to 16:00: the latest candle opens at 15:00, so one hour is missing. end = bars.time[-1] + 60 * 60 * 1000 draw.trend_line((bars.time[-1], price), (end, price), xloc="time") ``` ## Style The other arguments are the drawing’s settings, written as in [Colors and style](https://www.totaltrade.ai/en/indicatori/documentazione/colori-e-stile), text included: `text={"value": "…"}`. Colors are hexadecimal. To let the user choose the style, use the [style inputs](https://www.totaltrade.ai/en/indicatori/documentazione/input#styles) and pass them to the drawing. ## An example: each day’s low At the end of each day the script looks for the candle with the low and puts a price label on it, which writes the value by itself. ![Price labels on each day’s lows](https://www.totaltrade.ai/assets/docs-indicatori/drawingsLabels.webp) *draw.price_label on each day’s low.* ```python title="Daily lows" from totaltrade.v1 import indicator, request, draw @indicator(short="Lows", overlay=True) def calculate(bars=request.bars()): new_day = bars.new_period("D") start = 0 for i in range(1, len(bars.close) + 1): if i < len(bars.close) and not new_day[i]: continue # The low of the day just ended, with its price. bottom = start for j in range(start, i): if bars.low[j] < bars.low[bottom]: bottom = j draw.price_label((bottom, bars.low[bottom])) start = i ``` ## How many drawings An indicator keeps at most `max_drawings` drawings, 500 if you don’t write it, up to 10,000: beyond that, the last ones created remain. Every drawing has a cost, both to create and to draw, so it’s best to stop when you have enough. ```python BUBBLES = 200 @indicator(overlay=True, max_drawings=BUBBLES) def calculate(bars=request.bars()): count = 0 for i in reversed(range(len(bars.close))): # from the most recent candle if count == BUBBLES: break ... ``` > **The indicator’s drawings can’t be touched** > > They can’t be selected or saved: they are recreated at every calculation. Drawings that calculate by themselves, like volume profiles and the anchored VWAP, only receive the position and load their own data. --- # Text and numbers Writing numbers in drawing texts, and reading what happens during the calculation. ## f-string F-strings are written in the simple form, `f"RSI {value}"`: each brace writes the value like `str()`. Format specs inside the braces, like `{x:.2f}`, aren’t used: for numbers there is `format`. ## format The `format` functions write numbers the way the chart does: decimal point, no thousands separator, and `nan` as empty text. | Function | Example | |---|---| | `format.price(x)` | With the symbol’s decimals: `21534` → `"21534.00"` | | `format.quantity(x)` | Like volumes: `12345` → `"12.3K"` | | `format.percent(x)` | `12.5` → `"12.50%"` | | `format.number(x, precision)` | `format.number(1.23456, 2)` → `"1.23"` | ```python high = bars.high[i] draw.text((i, high), text={"value": f"High {format.price(high)}"}) ``` > **A single number type** > > Integers and decimals are the same number: `str(3.0)` gives `"3"`, and very large numbers are written in full. For text meant to be read, use `format`. ## print `print` writes to the Log tab of the console, with the calculation time and the code line; on the chart it does nothing. It helps you understand what the script calculates: you see the lines of the last calculation, up to 1000, and if the calculation stops with an error the lines written up to that point remain, with the error below. ```python rsi = ta.rsi(bars.close, 14) print("last RSI", rsi[-1]) ``` --- # Allowed Python The Python you need to calculate, with Python’s rules where they matter. ## Constructs `def`, `return`, `if`/`elif`/`else`, `for`, `while`, `break`, `continue`, `pass`, multiple and augmented assignments (`a, b = b, a`, `x += 1`), `x if c else y`, list and dictionary comprehensions, indexes and slices, chained comparisons (`0 < x <= 10`), `and`, `or`, `not`, `in`, `is None`, `raise ValueError(…)` and simple f-strings. ## Built-in functions `abs`, `all`, `any`, `bool`, `dict`, `enumerate`, `float`, `int`, `len`, `list`, `max`, `min`, `pow`, `print`, `range`, `reversed`, `round`, `sorted`, `str`, `sum`, `tuple`, `zip`. They can be passed as values, for example `sorted(x, key=abs)`. Lists and dictionaries have their methods, like `append`, `pop` and `get`: they are in the [reference](https://www.totaltrade.ai/en/indicatori/documentazione/liste-e-dizionari). There are no sets. ## Simple classes They keep together the data of one thing, like a zone or a level. They have only `__init__` and normal methods, and all fields are assigned in `__init__`: a wrong name is a compile error. Objects are passed by reference and `==` compares identity. ```python class Zone: def __init__(self, top, bottom, start): self.top = top self.bottom = bottom self.start = start self.end = None def contains(self, price): return self.bottom <= price <= self.top ``` There is no inheritance, no operators or other `__` methods, no class variables, decorators, `@dataclass`, `isinstance` or `type`. ## Not allowed `lambda`, `with`, `try`, `yield`, `async`, `global`, `nonlocal`, `del`, sets, mutable default values in your functions, other decorators and imports, and names starting with `__` (except `__init__`). The compiler flags them with the line. ## As in Python Where a result would change, Python rules: | | Result | |---|---| | Truthiness | An empty list is false, `nan` is true | | Floor division and remainder | `-7 // 2` is −4, `-7 % 2` is 1 | | `round` | `round(2.5)` is 2: ties go to even | | Errors | `1 / 0` is a `ZeroDivisionError`, an index out of the list an `IndexError`, always with the line | | Dictionaries | They keep insertion order | | Variables | The `for` variable remains after the loop | Where only the way a number is written would change, the browser rules instead: - integers and decimals are the same number, and beyond ±2⁵³ integers lose precision; - `exp`, `log`, `pow` and trigonometry may differ from Python in the last digit; - in texts with emoji, length and indexes count UTF-16 units: `len("😀")` is 2. ## Read-only values Candles, price levels, news and module constants can’t be modified: changing them is an error. This way no calculation changes the next one. To work on a list, make a copy: `list(bars.close)` or `list(news)`. --- # Errors and recalculation Where errors show up, when the indicator recalculates and what the limits are. ## Two kinds of error | Error | Examples | Where it shows | |---|---|---| | Compile error | Syntax, a construct that isn’t allowed, a name that doesn’t exist, a wrong argument in a declaration | In the editor, on the line, and in the console | | During the calculation | A division by zero, an index out of the list, a `raise ValueError` | In the Log tab, with the line; in the legend only “Script error”: the indicator doesn’t draw | Compile errors show up when you save: the compiler checks the whole script, even the lines that wouldn’t run. The messages are in Italian and say what was expected, like `Nelle dichiarazioni si scrivono solo valori, non calcoli` or `Le candele non hanno il campo closes`. ```python if length < 2: raise ValueError("Length must be at least 2") ``` With `raise ValueError(…)` you stop the calculation with your own message, which appears in the legend. ## When it recalculates - When data or settings change: a new or updated candle, a page of history, a new news event or data just released, an input, the chart’s timeframe. Never when scrolling or zooming. - Each calculation redoes everything, from the first candle: that’s why the function receives the whole series. In real time each tick restarts the calculation, and the indicator lags by at most one calculation. - While data is arriving, candles or news, the legend shows a spinning circle and the previous values remain. ## Timed out A full calculation has 5 seconds: beyond that, it stops with “Timed out”, and the other indicators carry on. Once stopped it doesn’t download more data, not even when you move the chart: “Reload” in the legend’s More menu restarts it, after the other errors too. If the calculation is slow, reduce the candles with [max_bars](https://www.totaltrade.ai/en/indicatori/documentazione/candele-e-dati#how-many) or avoid loops inside loops over all candles. ## Limits | Limit | Value | |---|---| | Code size | 200 KB | | Name of a script or a publication | 40 characters | | Description of a publication | 500 characters | | Inputs | 32 | | Plots | 32 | | Drawings per indicator | 500, up to 10,000 with max_drawings | | Candles after the latest, for drawing points | 500 | | print lines per calculation | 1000 | | Distinct requests, request.bars and request.events | 8 | | Candles per calculation, for each request | 200,000 if max_bars is missing | | Time for a full calculation | 5 seconds | --- # Examples Complete scripts: open them in the editor, add them to the chart and change them as you like. ## Hand-written RSI The same value as ta.rsi, with the explicit formula: Wilder averages of the gains and losses, the fill between 70 and 30 and two dashed lines. ![Hand-written RSI](https://www.totaltrade.ai/assets/docs-indicatori/exampleRsi.webp) ```python title="Hand-written RSI" from totaltrade.v1 import indicator, request, input, plot, color, draw, ta @indicator( short="RSI", precision=2, plots=[ plot.fill("band", "Background", 70, 30, fill={"color": color("#7E57C2", 10)}), plot.series("rsi", "RSI", color=color("#7E57C2")), ], ) def calculate(bars=request.bars(), length=input.int("Length", 14, min=1)): change = ta.change(bars.close) gains = ta.rma([max(c, 0.0) for c in change], length) losses = ta.rma([max(-c, 0.0) for c in change], length) rsi = [] for gain, loss in zip(gains, losses): if loss == 0: rsi.append(100.0) else: rsi.append(100 - 100 / (1 + gain / loss)) # Overbought and oversold: two gray dashed horizontal lines. for level in (70, 30): draw.horizontal_line((0, level), line={"color": color("#787B86"), "pattern": "dashed"}) return {"rsi": rsi} ``` ## Four-color MACD The histogram changes color if it rises or falls, above or below zero: four named colors, each with its own button in the settings. ![Four-color MACD](https://www.totaltrade.ai/assets/docs-indicatori/exampleMacd.webp) ```python title="Four-color MACD" from totaltrade.v1 import indicator, request, input, plot, color, draw, ta @indicator( short="MACD", plots=[ plot.series("hist", "Histogram", type="columns", color=[ ("rising_above", "Rising above zero", color("#26A69A")), ("falling_above", "Falling above zero", color("#B2DFDB")), ("rising_below", "Rising below zero", color("#FFCDD2")), ("falling_below", "Falling below zero", color("#FF5252")), ]), plot.series("macd", "MACD", color=color("#2962FF")), plot.series("signal", "Signal", color=color("#FF6D00")), ], ) def calculate( bars=request.bars(), fast=input.int("Fast", 12, min=1), slow=input.int("Slow", 26, min=1), smoothing=input.int("Signal", 9, min=1), ): macd, signal, hist = ta.macd(bars.close, fast, slow, smoothing) colors = [] for i, value in enumerate(hist): rising = i > 0 and value > hist[i - 1] if value >= 0: colors.append("rising_above" if rising else "falling_above") else: colors.append("rising_below" if rising else "falling_below") draw.horizontal_line((0, 0.0)) # the zero line, with the default style return {"hist": (hist, colors), "macd": macd, "signal": signal} ``` ## Moving average cross Two exponential averages and an arrow where they cross: plot.shape with a list of True and False. ![Moving average cross](https://www.totaltrade.ai/assets/docs-indicatori/exampleCross.webp) ```python title="Moving average cross" from totaltrade.v1 import indicator, request, input, plot, color, ta @indicator(short="Cross", overlay=True, plots=[ plot.series("fast", "Fast", color=color("#2962FF")), plot.series("slow", "Slow", color=color("#FF6D00")), plot.shape("up", "Bullish cross", type="arrow_up", location="below", color=color("up")), plot.shape("down", "Bearish cross", type="arrow_down", location="above", color=color("down")), ]) def calculate( bars=request.bars(min_bars=100), fast_length=input.int("Fast", 9, min=1), slow_length=input.int("Slow", 21, min=1), ): fast = ta.ema(bars.close, fast_length) slow = ta.ema(bars.close, slow_length) return { "fast": fast, "slow": slow, "up": ta.crossover(fast, slow), "down": ta.crossunder(fast, slow), } ``` ## VWAP with bands The volume-weighted average price, which restarts every day, with a band at one standard deviation and the fill between the two. ![VWAP with bands](https://www.totaltrade.ai/assets/docs-indicatori/exampleVwap.webp) ```python title="VWAP with bands" from totaltrade.v1 import indicator, request, input, plot, color, ta @indicator(short="VWAP", overlay=True, plots=[ plot.fill("band", "Background", "upper", "lower", fill={"color": color("#26A69A", 8)}), plot.series("upper", "Upper band", color=color("#26A69A")), plot.series("vwap", "VWAP", color=color("#2962FF"), width=2), plot.series("lower", "Lower band", color=color("#26A69A")), ]) def calculate( bars=request.bars(min_bars="D"), mult=input.float("Deviations", 1.0, min=0, step=0.5), ): hlc3 = ta.source(bars.open, bars.high, bars.low, bars.close, "hlc3") vwap, stdev = ta.vwap(hlc3, bars.volume, bars.new_period("D")) upper = [v + mult * s for v, s in zip(vwap, stdev)] lower = [v - mult * s for v, s in zip(vwap, stdev)] return {"upper": upper, "vwap": vwap, "lower": lower} ``` ## Session zones Each session’s range becomes a rectangle, which ends when a close breaks out of it: a simple class and drawings. ![Session zones](https://www.totaltrade.ai/assets/docs-indicatori/drawingsZones.webp) ```python title="Session zones" from totaltrade.v1 import indicator, request, input, color, draw class Zone: def __init__(self, top, bottom, start): self.top = top self.bottom = bottom self.start = start self.end = None @indicator(short="Zones", overlay=True) def calculate( bars=request.bars(), keep=input.int("Zones to keep", 5, min=1), fill=input.fill("Fill", {"color": color("#2962FF", 15)}), ): new_session = bars.new_period("D") zones = [] start = 0 for i in range(1, len(bars.close)): # A zone ends when a close breaks out of its range. for zone in zones: if zone.end is None and not zone.bottom <= bars.close[i] <= zone.top: zone.end = i if new_session[i]: high = max(bars.high[start:i]) low = min(bars.low[start:i]) zones.append(Zone(high, low, i)) start = i # A zone not yet broken extends to the latest candle. Without plots nothing is # returned: the rectangles created appear by themselves. last = len(bars.close) - 1 for z in zones[-keep:]: end = last if z.end is None else z.end draw.rectangle((z.start, z.top), (end, z.bottom), fill=fill) ``` ## Yesterday’s high and low The daily candles on an intraday chart, brought onto the chart’s candles with match. ![Yesterday’s high and low](https://www.totaltrade.ai/assets/docs-indicatori/matchDaily.webp) ```python title="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} ``` ## POC of each candle The price with the most volume in each candle, from the futures price profile: order flow with only the group it needs. ![POC of each candle](https://www.totaltrade.ai/assets/docs-indicatori/orderflowPoc.webp) ```python title="POC of each candle" from totaltrade.v1 import indicator, request, plot, color, ta @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)} ``` ## News on the chart One line for each hour with high-impact news, green if the data is better than forecast and red if worse, with the title and the actual value. The background marks the candles with a news event, and the impact is chosen in the settings. ![News on the chart](https://www.totaltrade.ai/assets/docs-indicatori/exampleNews.webp) ```python title="News on the chart" from totaltrade.v1 import indicator, request, input, plot, color, draw TONES = {"better": color("#26A69A"), "worse": color("#EF5350")} GRAY = color("#787B86") @indicator(short="News", overlay=True, plots=[ plot.background("news", "Candles with news", color=color("#FF9800", 12)), ]) def calculate( bars=request.bars(), news=request.events("news", impacts=input.choice("Impact", "high", options=[ (None, "All"), ("high", "High"), ("medium", "Medium"), ])), ): # How many news events there are at each time: one line per time. count = {} for event in news: count[event.time] = count.get(event.time, 0) + 1 drawn = {} for event in news: if event.time in drawn: continue drawn[event.time] = True # Green if the data beats the forecast, red if worse, gray if not released yet. tone = TONES.get(event.tone, GRAY) label = f"{event.title} {event.actual_text}" if count[event.time] > 1: label = f"{label} +{count[event.time] - 1}" draw.vertical_line((event.time, bars.close[-1]), xloc="time", line={"color": tone, "pattern": "dashed"}, text={"value": label, "align": "right", "style": {"color": tone}}, show_time_label=False) # The background marks the candles with at least one news event. return {"news": [end > start for start, end in bars.match(news)]} ``` --- # Publishing Sharing an indicator with everyone, updating it and withdrawing it. ![The dialog for publishing an indicator](https://www.totaltrade.ai/assets/docs-indicatori/publishDialog.webp) *The name is already filled in; the description is optional.* ## Publishing In the script menu, **Publish to TotalTrade…** saves the script, which must compile without errors. The first time you choose your username; then the dialog asks for the publication name and a description, optional, up to 500 characters. - The publication is a separate copy of the saved code: you can keep editing the script without touching it. - When you’re ready, the same command becomes **Update publication…**: users get the new version the next time they open the chart. - In the community the code is visible to everyone: anyone can read it and start from a copy. ## In the catalog Publications are in **Most used**, starting from the most used, with the author and how many people use each one. Yours are also in **Published by you**. ## Withdrawing From **Published by you** you withdraw a publication, after a confirmation: nobody can find it any more, and anyone who had it on the chart loses it the next time they open it. If you publish the script again it comes back as it was, with the same people using it. > **Deleting the script doesn’t withdraw the publication** > > The publication stays in the community until you withdraw it from Published by you. --- # Declarations The decorator, colors, inputs, plots and the candle and event requests. The plot style arguments are too many for one signature: they are explained in [Plots](https://www.totaltrade.ai/en/indicatori/documentazione/plot) and in [Colors and style](https://www.totaltrade.ai/en/indicatori/documentazione/colori-e-stile). ## The decorator and colors #### `indicator(short=None, overlay=False, plots=[], scale="auto", margins=None, name_labels=False, format="price", precision=None, max_drawings=500)` The decorator of the function that calculates: short name, pane, plots, scale and value format. You only write the arguments you need. #### `color(value, opacity=100)` A hex color, `"#RRGGBB"`, or a theme color: `up`, `down`, `line`, `buy`, `sell`, `neutral` or `text`. Opacity goes from 0 to 100. ## input #### `input.int(label, default, min=None, max=None, step=1, group=None, inline=None, tooltip=None, active=None)` A whole number, with `min`, `max` and the `step` if needed. The function receives an `int`. #### `input.float(label, default, min=None, max=None, step=None, group=None, inline=None, tooltip=None, active=None)` A decimal number, with `min`, `max` and the `step` if needed. The function receives a `float`. #### `input.bool(label, default, group=None, inline=None, tooltip=None, active=None)` A toggle. The function receives `True` or `False`. #### `input.choice(label, default, options, group=None, inline=None, tooltip=None, active=None)` A dropdown. `options` is a list of `(value, label)`, with text values or `None`: the function receives the chosen value. #### `input.time(label, default, group=None, inline=None, tooltip=None, active=None)` A time of day, with hours, minutes and seconds. It’s written and received as `"hh:mm:ss"`, like `bars.calendar.time_of_day`. #### `input.color(label, default, group=None, inline=None, tooltip=None, active=None)` A color with opacity, to pass to drawing arguments. The default is `color("#RRGGBB")`, without theme colors. #### `input.line(label, default, group=None, inline=None, tooltip=None, active=None)` The drawings’ line: color, width, line style and, if the default writes them, the line ends. The function receives the dictionary to pass to `line=`. #### `input.fill(label, default, group=None, inline=None, tooltip=None, active=None)` The drawings’ fill, with color and gradient. The function receives the dictionary to pass to `fill=`. #### `input.font(label, default, group=None, inline=None, tooltip=None, active=None)` The drawings’ font: color, size, bold and italic. The function receives the dictionary to pass to `"style"` in `text=`. ## plot #### `plot.series(key, label, **style)` One number per candle: line, step, columns, histogram, area, baseline, circles or crosses. `nan` leaves a gap. #### `plot.shape(key, label, **style)` A shape where the series is `True`: circle, square, cross, arrow or a character, above or below the candle. #### `plot.ohlc(key, label, **style)` Candles or bars: the function returns `(open, high, low, close)`. #### `plot.text(key, label, **style)` A row of numbers at the bottom of the pane, one below each candle, with the name on the scale. With `cell` each number has a colored cell. #### `plot.fill(key, label, upper, lower, **style)` A fill between two bounds: `plot.series` keys, numbers or `"bottom"`, the bottom of the pane. #### `plot.background(key, label, **style)` Colors the full height of the pane where the series is `True`. ## request #### `request.bars(timeframe=None, min_bars=0, max_bars=200000, orderflow=None, sentiment=False)` The candles of the chart symbol, or of another timeframe with `timeframe`: a value, an `input.choice` or a function that calculates it from the chart’s. `min_bars` and `max_bars` say how many to calculate; `orderflow` and `sentiment` also download that data. #### `request.events(kind, currencies=None, impacts=None)` Events over time of one type, today only `"news"`: the list of economic calendar news, in time order, from the first calculated candle to the upcoming ones. `currencies` are the currencies, like `["USD", "EUR"]` or `"All"` for global news; `None` the symbol’s. `impacts` are the impacts, like `["high", "medium"]`; `None` all. --- # Candles The fields of a candle request, its groups and the price levels. Here the candles are called `bars`, like the usual argument; they apply to any name you assign `request.bars(…)` to. A price level, `Level`, is an element of `bars.orderflow.levels[i]`. ## The candles #### `bars.open` · *field* The open of each candle. #### `bars.high` · *field* The high of each candle. #### `bars.low` · *field* The low of each candle. #### `bars.close` · *field* The close of each candle. #### `bars.volume` · *field* The contracts traded; `nan` if the symbol has no volume. #### `bars.time` · *field* The open time of each candle, in UTC milliseconds. #### `bars.confirmed` · *field* `True` if the candle is closed; `False` only on the one still forming. #### `bars.new_period(timeframe)` · *method* `True` on the first candle of each period of the timeframe, like `"D"` or `"W"`. #### `bars.match(other)` · *method* For each candle, the `(start, end)` range of indices of the candles of another request that correspond to it, or of the news in a list that falls inside it. #### `bars.orderflow` · *field* Market buys and sells and the price levels. Requires `request.bars(orderflow=…)`. #### `bars.sentiment` · *field* The long and short percentages, which add up to 100. Requires `request.bars(sentiment=True)`. #### `bars.symbol` · *field* The symbol: tick, point value, ticker, currency and which data it has. #### `bars.timeframe` · *field* The request’s timeframe: unit, quantity and duration. #### `bars.calendar` · *field* Time and date of each candle, in the symbol’s time zone. ## bars.orderflow #### `bars.orderflow.volume_bid` · *field* The market sells of each candle. #### `bars.orderflow.volume_ask` · *field* The market buys of each candle. #### `bars.orderflow.levels` · *field* For each candle, the list of its `Level`, from the lowest price. ## bars.sentiment #### `bars.sentiment.long` · *field* The percentage of long positions at the candle close. #### `bars.sentiment.short` · *field* The percentage of short positions at the candle close. ## bars.symbol #### `bars.symbol.tick_size` · *field* The minimum price increment. #### `bars.symbol.point_value` · *field* What one price point is worth, in the symbol’s currency. #### `bars.symbol.ticker` · *field* The symbol name. #### `bars.symbol.currency` · *field* The symbol’s currency, or `None`. #### `bars.symbol.has_volume` · *field* `True` if the symbol has volume. #### `bars.symbol.has_orderflow` · *field* `True` if the symbol has the price profile. #### `bars.symbol.has_sentiment` · *field* `True` if the symbol has sentiment. ## bars.timeframe #### `bars.timeframe.unit` · *field* The unit: `"second"`, `"minute"`, `"day"`, `"week"` or `"month"`. #### `bars.timeframe.value` · *field* How many units: 15 for 15 minutes. #### `bars.timeframe.seconds` · *field* The duration in seconds; a month is 2,628,003. #### `bars.timeframe.intraday` · *field* `True` below one day. ## bars.calendar #### `bars.calendar.time_of_day` · *field* The open time, always `"hh:mm:ss"`. #### `bars.calendar.weekday` · *field* The day of the week: 1 is Monday, 7 Sunday. #### `bars.calendar.day` · *field* The day of the month, by the calendar and not by the session. #### `bars.calendar.month` · *field* The month, from 1 to 12. #### `bars.calendar.year` · *field* The year. #### `bars.calendar.between(start, end, timezone=None)` · *method* `True` on the candles that open between `start`, included, and `end`, excluded. The window can cross midnight; `timezone` is for the hours of another exchange. ## Level #### `level.price` · *field* The level’s price. #### `level.volume_bid` · *field* Sum of the individual trades, on the sell side. #### `level.volume_ask` · *field* Sum of the individual trades, on the buy side. #### `level.aggregate_bid` · *field* Market orders, each counted whole at one price, on the sell side. #### `level.aggregate_ask` · *field* Market orders, each counted whole at one price, on the buy side. #### `level.biggest_volume_bid` · *field* The largest single trade, on the sell side. #### `level.biggest_volume_ask` · *field* The largest single trade, on the buy side. #### `level.biggest_aggregate_bid` · *field* The largest market order, on the sell side. #### `level.biggest_aggregate_ask` · *field* The largest market order, on the buy side. --- # News The fields of a news event, an element of the request.events("news") list. Here a news event is called `event`, as in `for event in news`. How to request them and bring them onto the candles is in [News](https://www.totaltrade.ai/en/indicatori/documentazione/news). #### `event.id` · *field* The news code: it stays the same for its whole life, even when the time changes. #### `event.time` · *field* The time, in UTC milliseconds, like `bars.time`. #### `event.currency` · *field* The currency, like `"USD"`, or `"All"` for global news. #### `event.impact` · *field* The expected impact: `"high"`, `"medium"`, `"low"` or `"none"`, as for holidays. #### `event.title` · *field* The name, as the source writes it: `"CPI m/m"`. #### `event.actual` · *field* The actual as a number: `"0.3%"` is `0.3`, `"165K"` is `165000`. `nan` if it hasn’t been released yet or isn’t a number. #### `event.forecast` · *field* The forecast as a number, `nan` if missing. #### `event.previous` · *field* The previous value as a number, `nan` if missing. #### `event.actual_text` · *field* The actual as the source writes it, for labels: `"0.3%"`. `""` if missing. #### `event.forecast_text` · *field* The forecast as the source writes it, `""` if missing. #### `event.previous_text` · *field* The previous value as the source writes it, `""` if missing. #### `event.higher_is_better` · *field* `True` if a higher value is better for the currency, `False` if lower, as for unemployment. `None` if not compared, as for speeches and auctions. #### `event.tone` · *field* The actual compared with the forecast, or with the previous value if the forecast is missing: `"better"`, `"worse"` or `"even"` for the currency. `None` if not compared. It’s the same color as in the calendar. --- # ta Functions on series: averages, oscillators, volatility, volume, order flow, windows, events and candlestick patterns. - Each function returns lists as long as the input; multiple outputs are a tuple, like `middle, upper, lower = ta.bb(…)`. - `length` is an integer greater than 0. Windows give `nan` until they are full, or if they contain a `nan`. - In `crossover`, `crossunder` and `cross` the second argument can be a number, like `ta.crossover(rsi, 70)`. ### Averages #### `ta.sma(src, length)` Simple average of the last length values. nan until the window is full, or if it contains a nan. #### `ta.ema(src, length)` Exponential moving average. Each value weighs alpha = 2 / (length + 1). It starts from the first value. A nan gives nan, and the average restarts from the next value. #### `ta.rma(src, length)` Wilder’s moving average. It starts from the simple average of the first length values, then each value weighs 1 / length. A nan gives nan, and the average starts over with the next length values. #### `ta.wma(src, length)` Weighted average: the most recent value weighs length, the previous one length - 1, and so on. nan until the window is full, or if it contains a nan. #### `ta.vwma(src, volume, length)` Volume-weighted average: sma(src * volume) / sma(volume). nan if volume is zero. #### `ta.hma(src, length)` Hull moving average: wma(2 * wma(src, length // 2) - wma(src, length), floor(sqrt(length))). length must be at least 2, because the first average uses length // 2. #### `ta.alma(src, length, offset=0.85, sigma=6)` Arnaud Legoux moving average: bell-shaped weights over the window. offset moves the center of the bell, from 0 (the oldest value) to 1 (the most recent); sigma narrows it. #### `ta.swma(src)` Symmetric average of the last 4 values, with weights 1/6, 2/6, 2/6, 1/6. #### `ta.linreg(src, length, offset=0)` Linear regression of the last length values. The least squares line, read offset candles before the latest: with offset 0 it’s its value on the current candle. ### Oscillators #### `ta.rsi(src, length)` Relative strength index, from 0 to 100. Wilder averages of gains and losses; with no losses it’s 100. #### `ta.macd(src, fast_length, slow_length, signal_length)` (macd, signal, hist): difference between two emas, its ema and the difference between the two. #### `ta.stoch(src, high, low, length)` Stochastic: where src sits between the low and the high of the last length, from 0 to 100. With the low equal to the high the ratio doesn’t exist, and the previous value remains. #### `ta.cci(src, length)` Commodity channel index: (src - sma) / (0.015 * mean deviation). With zero deviation, that is a flat window, the previous value remains. #### `ta.mfi(src, volume, length)` Money flow index, from 0 to 100: an rsi that weighs each price by its volume. On the first candle the change is nan, and a comparison with nan is false, so the flow ends up in both sums. With no outflow it’s 100. #### `ta.cmo(src, length)` Chande momentum oscillator, from -100 to 100: gains minus losses, over their sum. The first change is nan and ends up only among the losses, so the first value arrives at candle length. A flat window gives nan. #### `ta.roc(src, length)` Rate of change: percentage change from length candles before. nan if that value is 0. #### `ta.tsi(src, short_length, long_length)` True strength index, from -1 to 1. Changes smoothed twice with ema (first long_length, then short_length), divided by the absolute changes smoothed the same way. The TSI indicator multiplies it by 100. #### `ta.wpr(high, low, close, length)` Williams %R, from -100 to 0: distance of the close from the high of the last length. #### `ta.uo(high, low, close, fast_length, middle_length, slow_length)` Larry Williams’ Ultimate Oscillator, from 0 to 100. Buying pressure, that is the close minus the lower of the low and the previous close, is summed over three windows and divided by the sum of the true ranges; the three averages weigh 4, 2 and 1. nan on the first candle and where a window has zero range. #### `ta.dmi(high, low, close, di_length, adx_length)` (plus_di, minus_di, adx): directional movement, like the DMI indicator. The DIs are the Wilder averages of the up and down moves, divided by that of the true range; a DI that can’t be calculated keeps the previous value. The ADX is the Wilder average of |plus - minus| / (plus + minus). ### Volatility #### `ta.tr(high, low, close)` True range: the largest of h - l, |h - previous close| and |l - previous close|. Without a previous close, as on the first candle, it’s h - l. #### `ta.atr(high, low, close, length)` Average true range: the Wilder average of the true range. #### `ta.variance(src, length)` Population variance of the last length values (divided by length). #### `ta.stdev(src, length)` Population standard deviation of the last length values. #### `ta.dev(src, length)` Mean absolute deviation: the average of |value - sma| over the last length values. #### `ta.bb(src, length, mult)` Bollinger Bands (middle, upper, lower): sma and sma ± mult standard deviations. #### `ta.bbw(src, length, mult)` Bollinger Bands width as a percentage of the average. (upper - lower) / middle * 100; nan if the average is zero. #### `ta.kc(src, high, low, close, length, mult, use_true_range=True)` Keltner Channels (middle, upper, lower): ema of src ± mult times the ema of the range. The range is the true range, or h - l with use_true_range=False. #### `ta.supertrend(high, low, close, factor, atr_length)` (line, direction): Supertrend. direction is 1 in an uptrend, with the line below the price, and -1 in a downtrend. The bands are hl2 ± factor * atr, and each one can only tighten until the close crosses it. Where the atr is nan, line and direction are nan. #### `ta.sar(high, low, close, start=0.02, increment=0.02, maximum=0.2)` Parabolic SAR. It starts from the second candle: in an uptrend if the close rises. The point moves towards the trend extreme with an acceleration that grows by increment at each new extreme, up to maximum; when the price touches it, the trend reverses. If a nan makes the point nan, it starts again as from the second candle. ### Volume #### `ta.vwap(src, volume, reset=None)` (vwap, stdev): volume-weighted average price, and its standard deviation. The sums start from the first candle and restart where reset is True, for example with bars.new_period("D") for the session; without reset they never restart. Candles with src or volume nan don’t count. nan as long as the summed volume is zero. #### `ta.obv(close, volume)` On balance volume: running sum of volume, with the sign of the change. #### `ta.accdist(high, low, close, volume)` Accumulation/distribution: running sum of volume, weighted by the close. The weight is the position of the close within the candle’s range: -1 at the low, 1 at the high. #### `ta.pvt(close, volume)` Price volume trend: running sum of volume times the relative change. The change is that of the close over the previous one; a previous close of zero doesn’t count. #### `ta.signed_volume(open, close, volume)` The volume of each candle with the sign of its direction: positive if it rises, negative if it falls. It rises if it closes above the open and falls if it closes below; on a tie the previous close decides, and if that’s equal too the direction of the candle before remains. The first candle rises. It’s the Delta volume rule, which applies it to the intrabar candles. ### Order flow #### `ta.poc(levels)` The price with the most volume in each candle; on a tie the lowest. nan without volume. #### `ta.value_area(levels, percent=70)` (high, low): the value area of each candle, that is the prices that hold percent% of the volume. From the POC, each step adds the adjacent level, above or below, with more volume (on a tie the one above), until the sum reaches percent% of the candle’s volume. nan without volume. #### `ta.imbalances(levels, tick, percent=300)` (buy, sell): for each candle, the lists of prices with a diagonal imbalance. Buy at p if the buys at p are at least percent% of the sells at p - tick; sell if the sells at p are at least percent% of the buys at p + tick. The adjacent level must exist, and volume at p must be greater than zero. tick is bars.symbol.tick_size. ### Missing values #### `ta.nz(src, value=0)` src with nans replaced by value. #### `ta.fixnan(src)` src with each nan replaced by the last valid value; nan before the first. ### Windows #### `ta.cum(src, reset=None)` Running sum; restarts from zero where reset is True. nans count as 0. #### `ta.sum(src, length)` Sum of the last length values. nan until the window is full, or if it contains a nan. #### `ta.highest(src, length)` The highest value of the last length. #### `ta.lowest(src, length)` The lowest value of the last length. #### `ta.highestbars(src, length)` How many candles ago the highest value of the last length was: 0 is the current candle. Positive; on a tie, the most recent candle. #### `ta.lowestbars(src, length)` How many candles ago the lowest value of the last length was, like highestbars. #### `ta.median(src, length)` The median of the last length values: with an even length, the average of the two middle ones. #### `ta.percentile(src, length, percent)` The percent percentile (from 0 to 100) of the last length values. In the sorted values the position is percent / 100 * length - 0.5, counting from 0, with linear interpolation between the two neighbors; outside the values the first or the last is taken. nan if the window contains a nan. #### `ta.percentrank(src, length)` Percentage of the previous length values that are less than or equal to the current value. From 0 to 100; nan if the current value or one of the previous ones is nan. #### `ta.correlation(a, b, length)` Pearson correlation coefficient between a and b over the last length values, from -1 to 1. If one of the two series is constant in the window the correlation doesn’t exist, and it’s 0. #### `ta.rci(src, length)` Rank Correlation Index, from -100 to 100. Over the last length values it compares the rank in time (1 the most recent) with the rank in price (1 the highest): 100 if the price rose at every candle, -100 if it fell. Equal prices take the average of the ranks they occupy. nan until the window is full, or if it contains a nan. ### Events #### `ta.shift(src, offset)` The series shifted by offset candles, to the right if positive. Shifted to the right it loses the last offset values: the chart doesn’t draw them beyond the latest candle. Shifted to the left, each candle receives the value of a later one. #### `ta.change(src, length=1)` Difference between each value and the one length candles before; nan on the first length. #### `ta.crossover(a, b)` True where a crosses above b: now a > b, before a <= b. b can be a number. #### `ta.crossunder(a, b)` True where a crosses below b: now a < b, before a >= b. b can be a number. #### `ta.cross(a, b)` True where a and b cross, in either direction. b can be a number. #### `ta.rising(src, length)` True if src rose at every candle of the last length. #### `ta.falling(src, length)` True if src fell at every candle of the last length. #### `ta.barssince(cond)` Candles passed since the last one where cond was true: 0 on that same one. nan before. #### `ta.valuewhen(cond, src, occurrence=0)` The value of src on the candle where cond was true, occurrence times ago (0: the latest). nan until cond has been true enough times. #### `ta.pivothigh(src, left, right)` Local highs: the pivot value on the candle that confirms it, nan elsewhere. The pivot is right candles before: greater than or equal to the left values on its left and greater than the right ones on its right. The value arrives when the right following candles exist. #### `ta.pivotlow(src, left, right)` Local lows, like pivothigh: less than or equal on the left, less on the right. #### `ta.zigzag(high, low, deviation, depth)` The Zig Zag points: a list of (index, price, high), from the first. A high is a pivot if it exceeds the depth // 2 highs before and none of the depth // 2 after exceeds it; a low the same way. Each pivot is read on the candle that confirms it, the high before the low. If it goes in the same direction as the last point, it moves it when it’s more extreme; if it goes the opposite way, it becomes a new point when it moves away by at least deviation percent, a number or a series read on the confirming candle. The others are ignored: the points alternate highs (high True) and lows. It isn’t a series, but the points as seen from the latest candle: the last one can still move. ### Candles #### `ta.heikinashi(open, high, low, close)` (open, high, low, close) of the Heikin Ashi candles. The close is the average of the four prices; the open is the average of the previous Heikin Ashi open and close, and on the first candle, or after a nan, of the real open and close. #### `ta.candle_trend(close, kind)` (up, down): the trend that precedes candlestick patterns, as bool series. kind "sma50": uptrend with the close above the 50-candle simple average, downtrend below. "sma50_sma200": in addition the 50 average above the 200 one in an uptrend, below in a downtrend. None: no trend, that is (None, None), which the patterns don’t check. #### `ta.doji(open, high, low, close)` Doji: open and close almost equal, with the body within 5% of the candle. #### `ta.dragonfly_doji(open, high, low, close, trend=None)` Dragonfly doji: a doji at the high, with the long lower shadow. After a downtrend. #### `ta.gravestone_doji(open, high, low, close, trend=None)` Gravestone doji: a doji at the low, with the long upper shadow. After an uptrend. #### `ta.hammer(open, high, low, close, trend=None)` Hammer: small body at the top and long lower shadow. After a downtrend. #### `ta.hanging_man(open, high, low, close, trend=None)` Hanging man: the hammer’s shape, but after an uptrend. #### `ta.inverted_hammer(open, high, low, close, trend=None)` Inverted hammer: small body at the bottom and long upper shadow. After a downtrend. #### `ta.shooting_star(open, high, low, close, trend=None)` Shooting star: the inverted hammer’s shape, but after an uptrend. #### `ta.long_lower_shadow(open, high, low, close)` Long lower shadow: at least two thirds of the candle. #### `ta.long_upper_shadow(open, high, low, close)` Long upper shadow: at least two thirds of the candle. #### `ta.marubozu_white(open, high, low, close)` White marubozu: a long white body, with no shadows. #### `ta.marubozu_black(open, high, low, close)` Black marubozu: a long black body, with no shadows. #### `ta.spinning_top_white(open, high, low, close)` White spinning top: a small white body between two shadows longer than it. #### `ta.spinning_top_black(open, high, low, close)` Black spinning top: a small black body between two shadows longer than it. #### `ta.engulfing_bullish(open, high, low, close, trend=None)` Bullish engulfing: a white body engulfs the previous black body. After a downtrend. #### `ta.engulfing_bearish(open, high, low, close, trend=None)` Bearish engulfing: a black body engulfs the previous white body. After an uptrend. #### `ta.harami_bullish(open, high, low, close, trend=None)` Bullish harami: a white body inside the previous long black body. After a downtrend. #### `ta.harami_bearish(open, high, low, close, trend=None)` Bearish harami: a black body inside the previous long white body. After an uptrend. #### `ta.harami_cross_bullish(open, high, low, close, trend=None)` Bullish harami cross: a doji inside the previous long black body. After a downtrend. #### `ta.harami_cross_bearish(open, high, low, close, trend=None)` Bearish harami cross: a doji inside the previous long white body. After an uptrend. #### `ta.doji_star_bullish(open, high, low, close, trend=None)` Bullish doji star: a doji gapping below a long black body. After a downtrend. #### `ta.doji_star_bearish(open, high, low, close, trend=None)` Bearish doji star: a doji gapping above a long white body. After an uptrend. #### `ta.piercing(open, high, low, close, trend=None)` Piercing: a white candle that opens below and climbs back past the middle of the long black body. After a downtrend. #### `ta.dark_cloud_cover(open, high, low, close, trend=None)` Dark cloud cover: a black candle that opens above and falls past the middle of the long white body. After an uptrend. #### `ta.on_neck(open, high, low, close, trend=None)` On-neck: a white candle that opens below the low of the previous long black candle and closes there. After a downtrend, which continues. #### `ta.kicking_bullish(open, high, low, close)` Bullish kicking: a black marubozu and then a white one, gapping up. #### `ta.kicking_bearish(open, high, low, close)` Bearish kicking: a white marubozu and then a black one, gapping down. #### `ta.tweezer_bottom(open, high, low, close, trend=None)` Tweezer bottom: a black and a white candle with the same low. After a downtrend. #### `ta.tweezer_top(open, high, low, close, trend=None)` Tweezer top: a white and a black candle with the same high. After an uptrend. #### `ta.rising_window(open, high, low, close, trend=None)` Rising window: a gap up between the shadows. After an uptrend, which continues. #### `ta.falling_window(open, high, low, close, trend=None)` Falling window: a gap down between the shadows. After a downtrend, which continues. #### `ta.morning_star(open, high, low, close, trend=None)` Morning star: long black body, small star gapping below, white candle climbing back. After a downtrend. #### `ta.evening_star(open, high, low, close, trend=None)` Evening star: long white body, small star gapping above, black candle falling. After an uptrend. #### `ta.morning_doji_star(open, high, low, close, trend=None)` Morning doji star: the morning star with a doji in the middle. After a downtrend. #### `ta.evening_doji_star(open, high, low, close, trend=None)` Evening doji star: the evening star with a doji in the middle. After an uptrend. #### `ta.abandoned_baby_bullish(open, high, low, close, trend=None)` Bullish abandoned baby: a doji isolated by two gaps between a long black candle and a white one. After a downtrend. #### `ta.abandoned_baby_bearish(open, high, low, close, trend=None)` Bearish abandoned baby: a doji isolated by two gaps between a long white candle and a black one. After an uptrend. #### `ta.tri_star_bullish(open, high, low, close, trend=None)` Bullish tri-star: three dojis, with the middle one gapping below the others. After a downtrend. #### `ta.tri_star_bearish(open, high, low, close, trend=None)` Bearish tri-star: three dojis, with the middle one gapping above the others. After an uptrend. #### `ta.three_white_soldiers(open, high, low, close, trend=None)` Three white soldiers: three long white candles, each one higher. After a downtrend. #### `ta.three_black_crows(open, high, low, close, trend=None)` Three black crows: three long black candles, each one lower. After an uptrend. #### `ta.upside_tasuki_gap(open, high, low, close, trend=None)` Upside Tasuki gap: two white candles with a gap and a black one that doesn’t close the gap. After an uptrend, which continues. #### `ta.downside_tasuki_gap(open, high, low, close, trend=None)` Downside Tasuki gap: two black candles with a gap and a white one that doesn’t close the gap. After a downtrend, which continues. #### `ta.rising_three_methods(open, high, low, close, trend=None)` Rising three methods: long white candle, three small black candles within its range, white candle higher up. After an uptrend, which continues. #### `ta.falling_three_methods(open, high, low, close, trend=None)` Falling three methods: long black candle, three small white candles within its range, black candle lower down. After a downtrend, which continues. ### Input choices #### `ta.source(open, high, low, close, name)` The series chosen with a "Source" input. name is "close", "open", "high", "low", "hl2", "hlc3", "ohlc4" or "hlcc4": the averages are calculated candle by candle. #### `ta.ma(src, length, kind, volume=None)` The average chosen with an "MA type" input. kind is "sma", "ema", "rma" (the smoothed average, SMMA), "wma", "vwma" or "hma"; "vwma" also needs the volume. #### `ta.smoothing(src, kind, length, mult, volume=None)` The "Smoothing" group: (average, upper band, lower band). kind is None (nothing), an ma type, or "bb": the SMA with Bollinger Bands at mult standard deviations. Whatever the chosen type doesn’t show is all nan. --- # math Python’s math, with the same names and errors, plus sign and round_to_tick. As in Python, arguments are passed only by position: `math.log(8, 2)`, not `math.log(8, base=2)`. Functions on series are in [ta](https://www.totaltrade.ai/en/indicatori/documentazione/ta). #### `math.pi` · *constant* Pi, 3.14159… #### `math.e` · *constant* Euler’s number, 2.71828… #### `math.nan` · *constant* The missing value: in a plot it leaves a gap. #### `math.inf` · *constant* Positive infinity. #### `math.sqrt(x)` The square root. With a negative `x` it’s a `ValueError`. #### `math.exp(x)` `e` raised to `x`. #### `math.log(x, base)` The natural logarithm of `x` or, with `base`, in that base. `x` must be positive. #### `math.log10(x)` The base-10 logarithm. #### `math.sin(x)` The sine, with `x` in radians. #### `math.cos(x)` The cosine, with `x` in radians. #### `math.tan(x)` The tangent, with `x` in radians. #### `math.asin(x)` The arcsine in radians, with `x` between -1 and 1. #### `math.acos(x)` The arccosine in radians, with `x` between -1 and 1. #### `math.atan(x)` The arctangent in radians. #### `math.atan2(y, x)` The angle in radians of the point `(x, y)`, from -π to π: it takes the quadrant into account. #### `math.degrees(x)` From radians to degrees. #### `math.radians(x)` From degrees to radians. #### `math.floor(x)` The largest integer not greater than `x`. #### `math.ceil(x)` The smallest integer not less than `x`. #### `math.trunc(x)` The integer part of `x`, towards zero. #### `math.copysign(x, y)` The value of `x` with the sign of `y`. #### `math.isnan(x)` `True` if `x` is `nan`, the missing value. #### `math.isfinite(x)` `True` if `x` is neither `nan` nor infinite. #### `math.sign(x)` -1, 0 or 1, the sign of `x`; `nan` stays `nan`. #### `math.round_to_tick(x, tick)` The multiple of `tick` closest to `x`, rounded like `round`. For example `math.round_to_tick(x, bars.symbol.tick_size)`. --- # format Numbers written the way the chart writes them, for drawing texts. #### `format.price(x)` With the symbol’s decimals: `21534` becomes `"21534.00"`. #### `format.quantity(x)` Like volumes: whole numbers below 10,000, then K, M and B. `12345` becomes `"12.3K"`. #### `format.percent(x)` With the percent sign: `12.5` becomes `"12.50%"`. #### `format.number(x, precision)` With `precision` decimals: `format.number(1.23456, 2)` gives `"1.23"`. --- # draw All the chart drawings, with how many points they need. Each point is `(index, price)`; after the points come the settings, by name, as in the drawing’s dialog. See [Drawings](https://www.totaltrade.ai/en/indicatori/documentazione/disegni). ### Lines #### `draw.trend_line(p1, p2, **settings)` Trend line, with 2 `(index, price)` points. #### `draw.ray(p1, p2, **settings)` Ray, with 2 `(index, price)` points. #### `draw.info_line(p1, p2, **settings)` Info line, with 2 `(index, price)` points. #### `draw.extended_line(p1, p2, **settings)` Extended line, with 2 `(index, price)` points. #### `draw.trend_angle(p1, p2, **settings)` Trend angle, with 2 `(index, price)` points. #### `draw.horizontal_line(point, **settings)` Horizontal line, with one `(index, price)` point. #### `draw.horizontal_ray(point, **settings)` Horizontal ray, with one `(index, price)` point. #### `draw.vertical_line(point, **settings)` Vertical line, with one `(index, price)` point. #### `draw.cross_line(point, **settings)` Cross line, with one `(index, price)` point. ### Arrows #### `draw.arrow_line(p1, p2, **settings)` Arrow, with 2 `(index, price)` points. #### `draw.arrow_marker(p1, p2, **settings)` Arrow marker, with 2 `(index, price)` points. #### `draw.arrow_up(point, **settings)` Arrow up, with one `(index, price)` point. #### `draw.arrow_down(point, **settings)` Arrow down, with one `(index, price)` point. ### Channels #### `draw.parallel_channel(p1, p2, p3, **settings)` Parallel channel, with 3 `(index, price)` points. #### `draw.regression_trend(p1, p2, **settings)` Regression trend, with 2 `(index, price)` points. ### Pitchforks #### `draw.pitchfork(p1, p2, p3, **settings)` Pitchfork, with 3 `(index, price)` points. #### `draw.inside_pitchfork(p1, p2, p3, **settings)` Inside pitchfork, with 3 `(index, price)` points. ### Fibonacci #### `draw.fib_retracement(p1, p2, **settings)` Fib retracement, with 2 `(index, price)` points. #### `draw.fib_extension(p1, p2, p3, **settings)` Trend-based fib extension, with 3 `(index, price)` points. #### `draw.fib_channel(p1, p2, p3, **settings)` Fib channel, with 3 `(index, price)` points. #### `draw.fib_time_zone(p1, p2, **settings)` Fib time zone, with 2 `(index, price)` points. #### `draw.fib_speed_fan(p1, p2, **settings)` Fib speed resistance fan, with 2 `(index, price)` points. #### `draw.fib_trend_time(p1, p2, p3, **settings)` Trend-based fib time, with 3 `(index, price)` points. #### `draw.fib_circles(p1, p2, **settings)` Fib circles, with 2 `(index, price)` points. #### `draw.fib_spiral(p1, p2, **settings)` Fib spiral, with 2 `(index, price)` points. #### `draw.fib_arcs(p1, p2, **settings)` Fib speed resistance arcs, with 2 `(index, price)` points. #### `draw.fib_wedge(p1, p2, p3, **settings)` Fib wedge, with 3 `(index, price)` points. #### `draw.pitchfan(p1, p2, p3, **settings)` Pitchfan, with 3 `(index, price)` points. ### Gann #### `draw.gann_box(p1, p2, **settings)` Gann box, with 2 `(index, price)` points. #### `draw.gann_fixed(p1, p2, **settings)` Gann square fixed, with 2 `(index, price)` points. #### `draw.gann_square(p1, p2, **settings)` Gann square, with 2 `(index, price)` points. #### `draw.gann_fan(p1, p2, **settings)` Gann fan, with 2 `(index, price)` points. ### Chart patterns #### `draw.xabcd_pattern(p1, p2, p3, p4, p5, **settings)` XABCD pattern, with 5 `(index, price)` points. #### `draw.cypher_pattern(p1, p2, p3, p4, p5, **settings)` Cypher pattern, with 5 `(index, price)` points. #### `draw.head_and_shoulders(p1, p2, p3, p4, p5, p6, p7, **settings)` Head and shoulders, with 7 `(index, price)` points. #### `draw.abcd_pattern(p1, p2, p3, p4, **settings)` ABCD pattern, with 4 `(index, price)` points. #### `draw.triangle_pattern(p1, p2, p3, p4, **settings)` Triangle pattern, with 4 `(index, price)` points. #### `draw.three_drives(p1, p2, p3, p4, p5, p6, p7, **settings)` Three drives pattern, with 7 `(index, price)` points. ### Elliott waves #### `draw.elliott_impulse(p1, p2, p3, p4, p5, p6, **settings)` Elliott impulse wave (1·2·3·4·5), with 6 `(index, price)` points. #### `draw.elliott_correction(p1, p2, p3, p4, **settings)` Elliott correction wave (A·B·C), with 4 `(index, price)` points. #### `draw.elliott_triangle(p1, p2, p3, p4, p5, p6, **settings)` Elliott triangle wave (A·B·C·D·E), with 6 `(index, price)` points. #### `draw.elliott_double_combo(p1, p2, p3, p4, **settings)` Elliott double combo wave (W·X·Y), with 4 `(index, price)` points. #### `draw.elliott_triple_combo(p1, p2, p3, p4, p5, p6, **settings)` Elliott triple combo wave (W·X·Y·X·Z), with 6 `(index, price)` points. ### Cycles #### `draw.cyclic_lines(p1, p2, **settings)` Cyclic lines, with 2 `(index, price)` points. #### `draw.time_cycles(p1, p2, **settings)` Time cycles, with 2 `(index, price)` points. ### Volume profiles #### `draw.fixed_range_volume_profile(p1, p2, **settings)` Fixed range volume profile, with 2 `(index, price)` points. #### `draw.anchored_volume_profile(point, **settings)` Anchored volume profile, with one `(index, price)` point. ### TPO #### `draw.fixed_range_tpo(p1, p2, **settings)` Fixed range TPO, with 2 `(index, price)` points. #### `draw.anchored_tpo(point, **settings)` Anchored TPO, with one `(index, price)` point. ### VWAP #### `draw.anchored_vwap(point, **settings)` Anchored VWAP, with one `(index, price)` point. ### Brushes #### `draw.brush(p1, …, **settings)` Brush, with at least one `(index, price)` point. #### `draw.highlighter(p1, …, **settings)` Highlighter, with at least one `(index, price)` point. ### Shapes #### `draw.rectangle(p1, p2, **settings)` Rectangle, with 2 `(index, price)` points. #### `draw.rotated_rectangle(p1, p2, p3, **settings)` Rotated rectangle, with 3 `(index, price)` points. #### `draw.path(p1, …, **settings)` Path, with at least one `(index, price)` point. #### `draw.circle(p1, p2, **settings)` Circle, with 2 `(index, price)` points. #### `draw.ellipse(p1, p2, p3, **settings)` Ellipse, with 3 `(index, price)` points. #### `draw.polyline(p1, …, **settings)` Polyline, with at least one `(index, price)` point. #### `draw.triangle(p1, p2, p3, **settings)` Triangle, with 3 `(index, price)` points. #### `draw.arc(p1, p2, p3, **settings)` Arc, with 3 `(index, price)` points. #### `draw.curve(p1, p2, p3, **settings)` Curve, with 3 `(index, price)` points. #### `draw.double_curve(p1, p2, p3, p4, **settings)` Double curve, with 4 `(index, price)` points. ### Forecasting #### `draw.long_position(p1, p2, p3, p4, **settings)` Long position, with 4 `(index, price)` points. #### `draw.short_position(p1, p2, p3, p4, **settings)` Short position, with 4 `(index, price)` points. #### `draw.forecast(p1, p2, **settings)` Forecast, with 2 `(index, price)` points. #### `draw.bars_pattern(p1, p2, **settings)` Bars pattern, with 2 `(index, price)` points. #### `draw.ghost_feed(p1, p2, …, **settings)` Ghost feed, with at least 2 `(index, price)` points. #### `draw.projection(p1, p2, p3, **settings)` Projection, with 3 `(index, price)` points. ### Measurers #### `draw.price_range(p1, p2, **settings)` Price range, with 2 `(index, price)` points. #### `draw.date_range(p1, p2, **settings)` Date range, with 2 `(index, price)` points. #### `draw.date_and_price_range(p1, p2, **settings)` Date and price range, with 2 `(index, price)` points. ### Emoji #### `draw.emoji(point, **settings)` Emoji, with one `(index, price)` point. ### Icons #### `draw.icon(point, **settings)` Icon, with one `(index, price)` point. ### Text and notes #### `draw.text(point, **settings)` Text, with one `(index, price)` point. #### `draw.anchored_text(point, **settings)` Anchored text, with one `(index, price)` point. #### `draw.note(p1, p2, **settings)` Note, with 2 `(index, price)` points. #### `draw.price_note(p1, p2, **settings)` Price note, with 2 `(index, price)` points. #### `draw.pin(point, **settings)` Pin, with one `(index, price)` point. #### `draw.anchored_note(point, **settings)` Anchored note, with one `(index, price)` point. #### `draw.callout(p1, p2, **settings)` Callout, with 2 `(index, price)` points. #### `draw.comment(point, **settings)` Comment, with one `(index, price)` point. ### Markers #### `draw.price_label(point, **settings)` Price label, with one `(index, price)` point. #### `draw.flag_mark(point, **settings)` Flag mark, with one `(index, price)` point. --- # Lists and dictionaries The methods of lists and dictionaries, as in Python. ## Lists #### `list.append(x)` · *method* Adds `x` at the end. #### `list.extend(items)` · *method* Adds all the elements of `items` at the end. #### `list.insert(i, x)` · *method* Inserts `x` at position `i`. #### `list.pop(i=-1)` · *method* Removes and returns the element at position `i`, the last one if missing. #### `list.remove(x)` · *method* Removes the first element equal to `x`. #### `list.index(x)` · *method* The position of the first element equal to `x`. #### `list.count(x)` · *method* How many elements are equal to `x`. #### `list.reverse()` · *method* Reverses the list. #### `list.sort(key=None, reverse=False)` · *method* Sorts the list; `key` is the function that gives the value to compare. #### `list.copy()` · *method* A copy of the list. #### `list.clear()` · *method* Removes all the elements. ## Dictionaries #### `dict.get(key, default=None)` · *method* The value of `key`, or `default` if it isn’t there. #### `dict.items()` · *method* The `(key, value)` pairs, in insertion order. #### `dict.keys()` · *method* The keys, in insertion order. #### `dict.values()` · *method* The values, in insertion order. #### `dict.pop(key, default)` · *method* Removes `key` and returns its value, or `default` if it isn’t there. #### `dict.copy()` · *method* A copy of the dictionary. #### `dict.clear()` · *method* Removes all the entries.